babylon.max.js 3.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495
  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.addVector3 = function (otherVector) {
  412. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  413. };
  414. Vector2.prototype.subtract = function (otherVector) {
  415. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  416. };
  417. Vector2.prototype.subtractToRef = function (otherVector, result) {
  418. result.x = this.x - otherVector.x;
  419. result.y = this.y - otherVector.y;
  420. return this;
  421. };
  422. Vector2.prototype.subtractInPlace = function (otherVector) {
  423. this.x -= otherVector.x;
  424. this.y -= otherVector.y;
  425. return this;
  426. };
  427. Vector2.prototype.multiplyInPlace = function (otherVector) {
  428. this.x *= otherVector.x;
  429. this.y *= otherVector.y;
  430. return this;
  431. };
  432. Vector2.prototype.multiply = function (otherVector) {
  433. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  434. };
  435. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  436. result.x = this.x * otherVector.x;
  437. result.y = this.y * otherVector.y;
  438. return this;
  439. };
  440. Vector2.prototype.multiplyByFloats = function (x, y) {
  441. return new Vector2(this.x * x, this.y * y);
  442. };
  443. Vector2.prototype.divide = function (otherVector) {
  444. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  445. };
  446. Vector2.prototype.divideToRef = function (otherVector, result) {
  447. result.x = this.x / otherVector.x;
  448. result.y = this.y / otherVector.y;
  449. return this;
  450. };
  451. Vector2.prototype.negate = function () {
  452. return new Vector2(-this.x, -this.y);
  453. };
  454. Vector2.prototype.scaleInPlace = function (scale) {
  455. this.x *= scale;
  456. this.y *= scale;
  457. return this;
  458. };
  459. Vector2.prototype.scale = function (scale) {
  460. return new Vector2(this.x * scale, this.y * scale);
  461. };
  462. Vector2.prototype.equals = function (otherVector) {
  463. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  464. };
  465. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  466. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  467. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  468. };
  469. // Properties
  470. Vector2.prototype.length = function () {
  471. return Math.sqrt(this.x * this.x + this.y * this.y);
  472. };
  473. Vector2.prototype.lengthSquared = function () {
  474. return (this.x * this.x + this.y * this.y);
  475. };
  476. // Methods
  477. Vector2.prototype.normalize = function () {
  478. var len = this.length();
  479. if (len === 0)
  480. return this;
  481. var num = 1.0 / len;
  482. this.x *= num;
  483. this.y *= num;
  484. return this;
  485. };
  486. Vector2.prototype.clone = function () {
  487. return new Vector2(this.x, this.y);
  488. };
  489. // Statics
  490. Vector2.Zero = function () {
  491. return new Vector2(0, 0);
  492. };
  493. Vector2.FromArray = function (array, offset) {
  494. if (offset === void 0) { offset = 0; }
  495. return new Vector2(array[offset], array[offset + 1]);
  496. };
  497. Vector2.FromArrayToRef = function (array, offset, result) {
  498. result.x = array[offset];
  499. result.y = array[offset + 1];
  500. };
  501. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  502. var squared = amount * amount;
  503. var cubed = amount * squared;
  504. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  505. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  506. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  507. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  508. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  509. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  510. return new Vector2(x, y);
  511. };
  512. Vector2.Clamp = function (value, min, max) {
  513. var x = value.x;
  514. x = (x > max.x) ? max.x : x;
  515. x = (x < min.x) ? min.x : x;
  516. var y = value.y;
  517. y = (y > max.y) ? max.y : y;
  518. y = (y < min.y) ? min.y : y;
  519. return new Vector2(x, y);
  520. };
  521. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  522. var squared = amount * amount;
  523. var cubed = amount * squared;
  524. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  525. var part2 = (-2.0 * cubed) + (3.0 * squared);
  526. var part3 = (cubed - (2.0 * squared)) + amount;
  527. var part4 = cubed - squared;
  528. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  529. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  530. return new Vector2(x, y);
  531. };
  532. Vector2.Lerp = function (start, end, amount) {
  533. var x = start.x + ((end.x - start.x) * amount);
  534. var y = start.y + ((end.y - start.y) * amount);
  535. return new Vector2(x, y);
  536. };
  537. Vector2.Dot = function (left, right) {
  538. return left.x * right.x + left.y * right.y;
  539. };
  540. Vector2.Normalize = function (vector) {
  541. var newVector = vector.clone();
  542. newVector.normalize();
  543. return newVector;
  544. };
  545. Vector2.Minimize = function (left, right) {
  546. var x = (left.x < right.x) ? left.x : right.x;
  547. var y = (left.y < right.y) ? left.y : right.y;
  548. return new Vector2(x, y);
  549. };
  550. Vector2.Maximize = 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.Transform = function (vector, transformation) {
  556. var r = Vector2.Zero();
  557. Vector2.TransformToRef(vector, transformation, r);
  558. return r;
  559. };
  560. Vector2.TransformToRef = function (vector, transformation, result) {
  561. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  562. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  563. result.x = x;
  564. result.y = y;
  565. };
  566. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  567. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  568. var sign = a < 0 ? -1 : 1;
  569. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  570. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  571. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  572. };
  573. Vector2.Distance = function (value1, value2) {
  574. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  575. };
  576. Vector2.DistanceSquared = function (value1, value2) {
  577. var x = value1.x - value2.x;
  578. var y = value1.y - value2.y;
  579. return (x * x) + (y * y);
  580. };
  581. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  582. var l2 = Vector2.DistanceSquared(segA, segB);
  583. if (l2 === 0.0) {
  584. return Vector2.Distance(p, segA);
  585. }
  586. var v = segB.subtract(segA);
  587. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  588. var proj = segA.add(v.multiplyByFloats(t, t));
  589. return Vector2.Distance(p, proj);
  590. };
  591. return Vector2;
  592. }());
  593. BABYLON.Vector2 = Vector2;
  594. var Vector3 = (function () {
  595. function Vector3(x, y, z) {
  596. this.x = x;
  597. this.y = y;
  598. this.z = z;
  599. }
  600. Vector3.prototype.toString = function () {
  601. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  602. };
  603. Vector3.prototype.getClassName = function () {
  604. return "Vector3";
  605. };
  606. Vector3.prototype.getHashCode = function () {
  607. var hash = this.x || 0;
  608. hash = (hash * 397) ^ (this.y || 0);
  609. hash = (hash * 397) ^ (this.z || 0);
  610. return hash;
  611. };
  612. // Operators
  613. Vector3.prototype.asArray = function () {
  614. var result = [];
  615. this.toArray(result, 0);
  616. return result;
  617. };
  618. Vector3.prototype.toArray = function (array, index) {
  619. if (index === void 0) { index = 0; }
  620. array[index] = this.x;
  621. array[index + 1] = this.y;
  622. array[index + 2] = this.z;
  623. return this;
  624. };
  625. Vector3.prototype.toQuaternion = function () {
  626. var result = new Quaternion(0, 0, 0, 1);
  627. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  628. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  629. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  630. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  631. var cosy = Math.cos(this.y * 0.5);
  632. var siny = Math.sin(this.y * 0.5);
  633. result.x = coszMinusx * siny;
  634. result.y = -sinzMinusx * siny;
  635. result.z = sinxPlusz * cosy;
  636. result.w = cosxPlusz * cosy;
  637. return result;
  638. };
  639. Vector3.prototype.addInPlace = function (otherVector) {
  640. this.x += otherVector.x;
  641. this.y += otherVector.y;
  642. this.z += otherVector.z;
  643. return this;
  644. };
  645. Vector3.prototype.add = function (otherVector) {
  646. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  647. };
  648. Vector3.prototype.addToRef = function (otherVector, result) {
  649. result.x = this.x + otherVector.x;
  650. result.y = this.y + otherVector.y;
  651. result.z = this.z + otherVector.z;
  652. return this;
  653. };
  654. Vector3.prototype.subtractInPlace = function (otherVector) {
  655. this.x -= otherVector.x;
  656. this.y -= otherVector.y;
  657. this.z -= otherVector.z;
  658. return this;
  659. };
  660. Vector3.prototype.subtract = function (otherVector) {
  661. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  662. };
  663. Vector3.prototype.subtractToRef = function (otherVector, result) {
  664. result.x = this.x - otherVector.x;
  665. result.y = this.y - otherVector.y;
  666. result.z = this.z - otherVector.z;
  667. return this;
  668. };
  669. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  670. return new Vector3(this.x - x, this.y - y, this.z - z);
  671. };
  672. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  673. result.x = this.x - x;
  674. result.y = this.y - y;
  675. result.z = this.z - z;
  676. return this;
  677. };
  678. Vector3.prototype.negate = function () {
  679. return new Vector3(-this.x, -this.y, -this.z);
  680. };
  681. Vector3.prototype.scaleInPlace = function (scale) {
  682. this.x *= scale;
  683. this.y *= scale;
  684. this.z *= scale;
  685. return this;
  686. };
  687. Vector3.prototype.scale = function (scale) {
  688. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  689. };
  690. Vector3.prototype.scaleToRef = function (scale, result) {
  691. result.x = this.x * scale;
  692. result.y = this.y * scale;
  693. result.z = this.z * scale;
  694. };
  695. Vector3.prototype.equals = function (otherVector) {
  696. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  697. };
  698. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  699. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  700. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  701. };
  702. Vector3.prototype.equalsToFloats = function (x, y, z) {
  703. return this.x === x && this.y === y && this.z === z;
  704. };
  705. Vector3.prototype.multiplyInPlace = function (otherVector) {
  706. this.x *= otherVector.x;
  707. this.y *= otherVector.y;
  708. this.z *= otherVector.z;
  709. return this;
  710. };
  711. Vector3.prototype.multiply = function (otherVector) {
  712. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  713. };
  714. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  715. result.x = this.x * otherVector.x;
  716. result.y = this.y * otherVector.y;
  717. result.z = this.z * otherVector.z;
  718. return this;
  719. };
  720. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  721. return new Vector3(this.x * x, this.y * y, this.z * z);
  722. };
  723. Vector3.prototype.divide = function (otherVector) {
  724. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  725. };
  726. Vector3.prototype.divideToRef = function (otherVector, result) {
  727. result.x = this.x / otherVector.x;
  728. result.y = this.y / otherVector.y;
  729. result.z = this.z / otherVector.z;
  730. return this;
  731. };
  732. Vector3.prototype.MinimizeInPlace = function (other) {
  733. if (other.x < this.x)
  734. this.x = other.x;
  735. if (other.y < this.y)
  736. this.y = other.y;
  737. if (other.z < this.z)
  738. this.z = other.z;
  739. return this;
  740. };
  741. Vector3.prototype.MaximizeInPlace = function (other) {
  742. if (other.x > this.x)
  743. this.x = other.x;
  744. if (other.y > this.y)
  745. this.y = other.y;
  746. if (other.z > this.z)
  747. this.z = other.z;
  748. return this;
  749. };
  750. // Properties
  751. Vector3.prototype.length = function () {
  752. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  753. };
  754. Vector3.prototype.lengthSquared = function () {
  755. return (this.x * this.x + this.y * this.y + this.z * this.z);
  756. };
  757. // Methods
  758. Vector3.prototype.normalize = function () {
  759. var len = this.length();
  760. if (len === 0 || len === 1.0)
  761. return this;
  762. var num = 1.0 / len;
  763. this.x *= num;
  764. this.y *= num;
  765. this.z *= num;
  766. return this;
  767. };
  768. Vector3.prototype.clone = function () {
  769. return new Vector3(this.x, this.y, this.z);
  770. };
  771. Vector3.prototype.copyFrom = function (source) {
  772. this.x = source.x;
  773. this.y = source.y;
  774. this.z = source.z;
  775. return this;
  776. };
  777. Vector3.prototype.copyFromFloats = function (x, y, z) {
  778. this.x = x;
  779. this.y = y;
  780. this.z = z;
  781. return this;
  782. };
  783. // Statics
  784. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  785. var d0 = Vector3.Dot(vector0, axis) - size;
  786. var d1 = Vector3.Dot(vector1, axis) - size;
  787. var s = d0 / (d0 - d1);
  788. return s;
  789. };
  790. Vector3.FromArray = function (array, offset) {
  791. if (!offset) {
  792. offset = 0;
  793. }
  794. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  795. };
  796. Vector3.FromFloatArray = function (array, offset) {
  797. if (!offset) {
  798. offset = 0;
  799. }
  800. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  801. };
  802. Vector3.FromArrayToRef = function (array, offset, result) {
  803. result.x = array[offset];
  804. result.y = array[offset + 1];
  805. result.z = array[offset + 2];
  806. };
  807. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  808. result.x = array[offset];
  809. result.y = array[offset + 1];
  810. result.z = array[offset + 2];
  811. };
  812. Vector3.FromFloatsToRef = function (x, y, z, result) {
  813. result.x = x;
  814. result.y = y;
  815. result.z = z;
  816. };
  817. Vector3.Zero = function () {
  818. return new Vector3(0, 0, 0);
  819. };
  820. Vector3.Up = function () {
  821. return new Vector3(0, 1.0, 0);
  822. };
  823. Vector3.TransformCoordinates = function (vector, transformation) {
  824. var result = Vector3.Zero();
  825. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  826. return result;
  827. };
  828. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  829. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  830. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  831. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  832. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  833. result.x = x / w;
  834. result.y = y / w;
  835. result.z = z / w;
  836. };
  837. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  838. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  839. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  840. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  841. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  842. result.x = rx / rw;
  843. result.y = ry / rw;
  844. result.z = rz / rw;
  845. };
  846. Vector3.TransformNormal = function (vector, transformation) {
  847. var result = Vector3.Zero();
  848. Vector3.TransformNormalToRef(vector, transformation, result);
  849. return result;
  850. };
  851. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  852. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  853. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  854. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  855. };
  856. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  857. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  858. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  859. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  860. };
  861. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  862. var squared = amount * amount;
  863. var cubed = amount * squared;
  864. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  865. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  866. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  867. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  868. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  869. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  870. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  871. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  872. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  873. return new Vector3(x, y, z);
  874. };
  875. Vector3.Clamp = function (value, min, max) {
  876. var x = value.x;
  877. x = (x > max.x) ? max.x : x;
  878. x = (x < min.x) ? min.x : x;
  879. var y = value.y;
  880. y = (y > max.y) ? max.y : y;
  881. y = (y < min.y) ? min.y : y;
  882. var z = value.z;
  883. z = (z > max.z) ? max.z : z;
  884. z = (z < min.z) ? min.z : z;
  885. return new Vector3(x, y, z);
  886. };
  887. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  888. var squared = amount * amount;
  889. var cubed = amount * squared;
  890. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  891. var part2 = (-2.0 * cubed) + (3.0 * squared);
  892. var part3 = (cubed - (2.0 * squared)) + amount;
  893. var part4 = cubed - squared;
  894. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  895. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  896. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  897. return new Vector3(x, y, z);
  898. };
  899. Vector3.Lerp = function (start, end, amount) {
  900. var x = start.x + ((end.x - start.x) * amount);
  901. var y = start.y + ((end.y - start.y) * amount);
  902. var z = start.z + ((end.z - start.z) * amount);
  903. return new Vector3(x, y, z);
  904. };
  905. Vector3.Dot = function (left, right) {
  906. return (left.x * right.x + left.y * right.y + left.z * right.z);
  907. };
  908. Vector3.Cross = function (left, right) {
  909. var result = Vector3.Zero();
  910. Vector3.CrossToRef(left, right, result);
  911. return result;
  912. };
  913. Vector3.CrossToRef = function (left, right, result) {
  914. Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  915. Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  916. Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  917. result.copyFrom(Tmp.Vector3[0]);
  918. };
  919. Vector3.Normalize = function (vector) {
  920. var result = Vector3.Zero();
  921. Vector3.NormalizeToRef(vector, result);
  922. return result;
  923. };
  924. Vector3.NormalizeToRef = function (vector, result) {
  925. result.copyFrom(vector);
  926. result.normalize();
  927. };
  928. Vector3.Project = function (vector, world, transform, viewport) {
  929. var cw = viewport.width;
  930. var ch = viewport.height;
  931. var cx = viewport.x;
  932. var cy = viewport.y;
  933. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  934. 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);
  935. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  936. world.multiplyToRef(transform, matrix);
  937. matrix.multiplyToRef(viewportMatrix, matrix);
  938. return Vector3.TransformCoordinates(vector, matrix);
  939. };
  940. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  941. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  942. world.multiplyToRef(transform, matrix);
  943. matrix.invert();
  944. source.x = source.x / viewportWidth * 2 - 1;
  945. source.y = -(source.y / viewportHeight * 2 - 1);
  946. var vector = Vector3.TransformCoordinates(source, matrix);
  947. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  948. if (MathTools.WithinEpsilon(num, 1.0)) {
  949. vector = vector.scale(1.0 / num);
  950. }
  951. return vector;
  952. };
  953. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  954. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  955. world.multiplyToRef(view, matrix);
  956. matrix.multiplyToRef(projection, matrix);
  957. matrix.invert();
  958. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  959. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  960. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  961. if (MathTools.WithinEpsilon(num, 1.0)) {
  962. vector = vector.scale(1.0 / num);
  963. }
  964. return vector;
  965. };
  966. Vector3.Minimize = function (left, right) {
  967. var min = left.clone();
  968. min.MinimizeInPlace(right);
  969. return min;
  970. };
  971. Vector3.Maximize = function (left, right) {
  972. var max = left.clone();
  973. max.MaximizeInPlace(right);
  974. return max;
  975. };
  976. Vector3.Distance = function (value1, value2) {
  977. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  978. };
  979. Vector3.DistanceSquared = function (value1, value2) {
  980. var x = value1.x - value2.x;
  981. var y = value1.y - value2.y;
  982. var z = value1.z - value2.z;
  983. return (x * x) + (y * y) + (z * z);
  984. };
  985. Vector3.Center = function (value1, value2) {
  986. var center = value1.add(value2);
  987. center.scaleInPlace(0.5);
  988. return center;
  989. };
  990. /**
  991. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  992. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  993. * to something in order to rotate it from its local system to the given target system.
  994. */
  995. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  996. var rotation = Vector3.Zero();
  997. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  998. return rotation;
  999. };
  1000. /**
  1001. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  1002. */
  1003. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1004. var u = axis1.normalize();
  1005. var w = axis3.normalize();
  1006. // world axis
  1007. var X = Axis.X;
  1008. var Y = Axis.Y;
  1009. // equation unknowns and vars
  1010. var yaw = 0.0;
  1011. var pitch = 0.0;
  1012. var roll = 0.0;
  1013. var x = 0.0;
  1014. var y = 0.0;
  1015. var z = 0.0;
  1016. var t = 0.0;
  1017. var sign = -1.0;
  1018. var nbRevert = 0;
  1019. var cross = Tmp.Vector3[0];
  1020. var dot = 0.0;
  1021. // step 1 : rotation around w
  1022. // Rv3(u) = u1, and u1 belongs to plane xOz
  1023. // Rv3(w) = w1 = w invariant
  1024. var u1 = Tmp.Vector3[1];
  1025. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1026. z = 1.0;
  1027. }
  1028. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  1029. x = 1.0;
  1030. }
  1031. else {
  1032. t = w.z / w.x;
  1033. x = -t * Math.sqrt(1 / (1 + t * t));
  1034. z = Math.sqrt(1 / (1 + t * t));
  1035. }
  1036. u1.x = x;
  1037. u1.y = y;
  1038. u1.z = z;
  1039. u1.normalize();
  1040. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  1041. cross.normalize();
  1042. if (Vector3.Dot(w, cross) < 0) {
  1043. sign = 1.0;
  1044. }
  1045. dot = Vector3.Dot(u, u1);
  1046. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1047. roll = Math.acos(dot) * sign;
  1048. if (Vector3.Dot(u1, X) < 0) {
  1049. roll = Math.PI + roll;
  1050. u1 = u1.scaleInPlace(-1);
  1051. nbRevert++;
  1052. }
  1053. // step 2 : rotate around u1
  1054. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1055. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1056. var w2 = Tmp.Vector3[2];
  1057. var v2 = Tmp.Vector3[3];
  1058. x = 0.0;
  1059. y = 0.0;
  1060. z = 0.0;
  1061. sign = -1.0;
  1062. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1063. x = 1.0;
  1064. }
  1065. else {
  1066. t = u1.z / u1.x;
  1067. x = -t * Math.sqrt(1 / (1 + t * t));
  1068. z = Math.sqrt(1 / (1 + t * t));
  1069. }
  1070. w2.x = x;
  1071. w2.y = y;
  1072. w2.z = z;
  1073. w2.normalize();
  1074. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1075. v2.normalize();
  1076. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1077. cross.normalize();
  1078. if (Vector3.Dot(u1, cross) < 0) {
  1079. sign = 1.0;
  1080. }
  1081. dot = Vector3.Dot(w, w2);
  1082. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1083. pitch = Math.acos(dot) * sign;
  1084. if (Vector3.Dot(v2, Y) < 0) {
  1085. pitch = Math.PI + pitch;
  1086. nbRevert++;
  1087. }
  1088. // step 3 : rotate around v2
  1089. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1090. sign = -1.0;
  1091. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1092. cross.normalize();
  1093. if (Vector3.Dot(cross, Y) < 0) {
  1094. sign = 1.0;
  1095. }
  1096. dot = Vector3.Dot(u1, X);
  1097. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1098. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1099. if (dot < 0 && nbRevert < 2) {
  1100. yaw = Math.PI + yaw;
  1101. }
  1102. ref.x = pitch;
  1103. ref.y = yaw;
  1104. ref.z = roll;
  1105. };
  1106. return Vector3;
  1107. }());
  1108. BABYLON.Vector3 = Vector3;
  1109. //Vector4 class created for EulerAngle class conversion to Quaternion
  1110. var Vector4 = (function () {
  1111. function Vector4(x, y, z, w) {
  1112. this.x = x;
  1113. this.y = y;
  1114. this.z = z;
  1115. this.w = w;
  1116. }
  1117. Vector4.prototype.toString = function () {
  1118. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1119. };
  1120. Vector4.prototype.getClassName = function () {
  1121. return "Vector4";
  1122. };
  1123. Vector4.prototype.getHashCode = function () {
  1124. var hash = this.x || 0;
  1125. hash = (hash * 397) ^ (this.y || 0);
  1126. hash = (hash * 397) ^ (this.z || 0);
  1127. hash = (hash * 397) ^ (this.w || 0);
  1128. return hash;
  1129. };
  1130. // Operators
  1131. Vector4.prototype.asArray = function () {
  1132. var result = [];
  1133. this.toArray(result, 0);
  1134. return result;
  1135. };
  1136. Vector4.prototype.toArray = function (array, index) {
  1137. if (index === undefined) {
  1138. index = 0;
  1139. }
  1140. array[index] = this.x;
  1141. array[index + 1] = this.y;
  1142. array[index + 2] = this.z;
  1143. array[index + 3] = this.w;
  1144. return this;
  1145. };
  1146. Vector4.prototype.addInPlace = function (otherVector) {
  1147. this.x += otherVector.x;
  1148. this.y += otherVector.y;
  1149. this.z += otherVector.z;
  1150. this.w += otherVector.w;
  1151. return this;
  1152. };
  1153. Vector4.prototype.add = function (otherVector) {
  1154. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1155. };
  1156. Vector4.prototype.addToRef = function (otherVector, result) {
  1157. result.x = this.x + otherVector.x;
  1158. result.y = this.y + otherVector.y;
  1159. result.z = this.z + otherVector.z;
  1160. result.w = this.w + otherVector.w;
  1161. return this;
  1162. };
  1163. Vector4.prototype.subtractInPlace = function (otherVector) {
  1164. this.x -= otherVector.x;
  1165. this.y -= otherVector.y;
  1166. this.z -= otherVector.z;
  1167. this.w -= otherVector.w;
  1168. return this;
  1169. };
  1170. Vector4.prototype.subtract = function (otherVector) {
  1171. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1172. };
  1173. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1174. result.x = this.x - otherVector.x;
  1175. result.y = this.y - otherVector.y;
  1176. result.z = this.z - otherVector.z;
  1177. result.w = this.w - otherVector.w;
  1178. return this;
  1179. };
  1180. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1181. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1182. };
  1183. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1184. result.x = this.x - x;
  1185. result.y = this.y - y;
  1186. result.z = this.z - z;
  1187. result.w = this.w - w;
  1188. return this;
  1189. };
  1190. Vector4.prototype.negate = function () {
  1191. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1192. };
  1193. Vector4.prototype.scaleInPlace = function (scale) {
  1194. this.x *= scale;
  1195. this.y *= scale;
  1196. this.z *= scale;
  1197. this.w *= scale;
  1198. return this;
  1199. };
  1200. Vector4.prototype.scale = function (scale) {
  1201. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1202. };
  1203. Vector4.prototype.scaleToRef = function (scale, result) {
  1204. result.x = this.x * scale;
  1205. result.y = this.y * scale;
  1206. result.z = this.z * scale;
  1207. result.w = this.w * scale;
  1208. };
  1209. Vector4.prototype.equals = function (otherVector) {
  1210. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1211. };
  1212. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1213. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1214. return otherVector
  1215. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1216. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1217. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1218. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1219. };
  1220. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1221. return this.x === x && this.y === y && this.z === z && this.w === w;
  1222. };
  1223. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1224. this.x *= otherVector.x;
  1225. this.y *= otherVector.y;
  1226. this.z *= otherVector.z;
  1227. this.w *= otherVector.w;
  1228. return this;
  1229. };
  1230. Vector4.prototype.multiply = function (otherVector) {
  1231. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1232. };
  1233. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1234. result.x = this.x * otherVector.x;
  1235. result.y = this.y * otherVector.y;
  1236. result.z = this.z * otherVector.z;
  1237. result.w = this.w * otherVector.w;
  1238. return this;
  1239. };
  1240. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1241. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1242. };
  1243. Vector4.prototype.divide = function (otherVector) {
  1244. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1245. };
  1246. Vector4.prototype.divideToRef = function (otherVector, result) {
  1247. result.x = this.x / otherVector.x;
  1248. result.y = this.y / otherVector.y;
  1249. result.z = this.z / otherVector.z;
  1250. result.w = this.w / otherVector.w;
  1251. return this;
  1252. };
  1253. Vector4.prototype.MinimizeInPlace = function (other) {
  1254. if (other.x < this.x)
  1255. this.x = other.x;
  1256. if (other.y < this.y)
  1257. this.y = other.y;
  1258. if (other.z < this.z)
  1259. this.z = other.z;
  1260. if (other.w < this.w)
  1261. this.w = other.w;
  1262. return this;
  1263. };
  1264. Vector4.prototype.MaximizeInPlace = function (other) {
  1265. if (other.x > this.x)
  1266. this.x = other.x;
  1267. if (other.y > this.y)
  1268. this.y = other.y;
  1269. if (other.z > this.z)
  1270. this.z = other.z;
  1271. if (other.w > this.w)
  1272. this.w = other.w;
  1273. return this;
  1274. };
  1275. // Properties
  1276. Vector4.prototype.length = function () {
  1277. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1278. };
  1279. Vector4.prototype.lengthSquared = function () {
  1280. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1281. };
  1282. // Methods
  1283. Vector4.prototype.normalize = function () {
  1284. var len = this.length();
  1285. if (len === 0)
  1286. return this;
  1287. var num = 1.0 / len;
  1288. this.x *= num;
  1289. this.y *= num;
  1290. this.z *= num;
  1291. this.w *= num;
  1292. return this;
  1293. };
  1294. Vector4.prototype.toVector3 = function () {
  1295. return new Vector3(this.x, this.y, this.z);
  1296. };
  1297. Vector4.prototype.clone = function () {
  1298. return new Vector4(this.x, this.y, this.z, this.w);
  1299. };
  1300. Vector4.prototype.copyFrom = function (source) {
  1301. this.x = source.x;
  1302. this.y = source.y;
  1303. this.z = source.z;
  1304. this.w = source.w;
  1305. return this;
  1306. };
  1307. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1308. this.x = x;
  1309. this.y = y;
  1310. this.z = z;
  1311. this.w = w;
  1312. return this;
  1313. };
  1314. // Statics
  1315. Vector4.FromArray = function (array, offset) {
  1316. if (!offset) {
  1317. offset = 0;
  1318. }
  1319. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1320. };
  1321. Vector4.FromArrayToRef = function (array, offset, result) {
  1322. result.x = array[offset];
  1323. result.y = array[offset + 1];
  1324. result.z = array[offset + 2];
  1325. result.w = array[offset + 3];
  1326. };
  1327. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1328. result.x = array[offset];
  1329. result.y = array[offset + 1];
  1330. result.z = array[offset + 2];
  1331. result.w = array[offset + 3];
  1332. };
  1333. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1334. result.x = x;
  1335. result.y = y;
  1336. result.z = z;
  1337. result.w = w;
  1338. };
  1339. Vector4.Zero = function () {
  1340. return new Vector4(0, 0, 0, 0);
  1341. };
  1342. Vector4.Normalize = function (vector) {
  1343. var result = Vector4.Zero();
  1344. Vector4.NormalizeToRef(vector, result);
  1345. return result;
  1346. };
  1347. Vector4.NormalizeToRef = function (vector, result) {
  1348. result.copyFrom(vector);
  1349. result.normalize();
  1350. };
  1351. Vector4.Minimize = function (left, right) {
  1352. var min = left.clone();
  1353. min.MinimizeInPlace(right);
  1354. return min;
  1355. };
  1356. Vector4.Maximize = function (left, right) {
  1357. var max = left.clone();
  1358. max.MaximizeInPlace(right);
  1359. return max;
  1360. };
  1361. Vector4.Distance = function (value1, value2) {
  1362. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1363. };
  1364. Vector4.DistanceSquared = function (value1, value2) {
  1365. var x = value1.x - value2.x;
  1366. var y = value1.y - value2.y;
  1367. var z = value1.z - value2.z;
  1368. var w = value1.w - value2.w;
  1369. return (x * x) + (y * y) + (z * z) + (w * w);
  1370. };
  1371. Vector4.Center = function (value1, value2) {
  1372. var center = value1.add(value2);
  1373. center.scaleInPlace(0.5);
  1374. return center;
  1375. };
  1376. return Vector4;
  1377. }());
  1378. BABYLON.Vector4 = Vector4;
  1379. var Size = (function () {
  1380. function Size(width, height) {
  1381. this.width = width;
  1382. this.height = height;
  1383. }
  1384. Size.prototype.toString = function () {
  1385. return "{W: " + this.width + ", H: " + this.height + "}";
  1386. };
  1387. Size.prototype.getClassName = function () {
  1388. return "Size";
  1389. };
  1390. Size.prototype.getHashCode = function () {
  1391. var hash = this.width || 0;
  1392. hash = (hash * 397) ^ (this.height || 0);
  1393. return hash;
  1394. };
  1395. Size.prototype.copyFrom = function (src) {
  1396. this.width = src.width;
  1397. this.height = src.height;
  1398. };
  1399. Size.prototype.copyFromFloats = function (width, height) {
  1400. this.width = width;
  1401. this.height = height;
  1402. };
  1403. Size.prototype.multiplyByFloats = function (w, h) {
  1404. return new Size(this.width * w, this.height * h);
  1405. };
  1406. Size.prototype.clone = function () {
  1407. return new Size(this.width, this.height);
  1408. };
  1409. Size.prototype.equals = function (other) {
  1410. if (!other) {
  1411. return false;
  1412. }
  1413. return (this.width === other.width) && (this.height === other.height);
  1414. };
  1415. Object.defineProperty(Size.prototype, "surface", {
  1416. get: function () {
  1417. return this.width * this.height;
  1418. },
  1419. enumerable: true,
  1420. configurable: true
  1421. });
  1422. Size.Zero = function () {
  1423. return new Size(0, 0);
  1424. };
  1425. Size.prototype.add = function (otherSize) {
  1426. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1427. return r;
  1428. };
  1429. Size.prototype.substract = function (otherSize) {
  1430. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1431. return r;
  1432. };
  1433. Size.Lerp = function (start, end, amount) {
  1434. var w = start.width + ((end.width - start.width) * amount);
  1435. var h = start.height + ((end.height - start.height) * amount);
  1436. return new Size(w, h);
  1437. };
  1438. return Size;
  1439. }());
  1440. BABYLON.Size = Size;
  1441. var Quaternion = (function () {
  1442. function Quaternion(x, y, z, w) {
  1443. if (x === void 0) { x = 0; }
  1444. if (y === void 0) { y = 0; }
  1445. if (z === void 0) { z = 0; }
  1446. if (w === void 0) { w = 1; }
  1447. this.x = x;
  1448. this.y = y;
  1449. this.z = z;
  1450. this.w = w;
  1451. }
  1452. Quaternion.prototype.toString = function () {
  1453. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1454. };
  1455. Quaternion.prototype.getClassName = function () {
  1456. return "Quaternion";
  1457. };
  1458. Quaternion.prototype.getHashCode = function () {
  1459. var hash = this.x || 0;
  1460. hash = (hash * 397) ^ (this.y || 0);
  1461. hash = (hash * 397) ^ (this.z || 0);
  1462. hash = (hash * 397) ^ (this.w || 0);
  1463. return hash;
  1464. };
  1465. Quaternion.prototype.asArray = function () {
  1466. return [this.x, this.y, this.z, this.w];
  1467. };
  1468. Quaternion.prototype.equals = function (otherQuaternion) {
  1469. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1470. };
  1471. Quaternion.prototype.clone = function () {
  1472. return new Quaternion(this.x, this.y, this.z, this.w);
  1473. };
  1474. Quaternion.prototype.copyFrom = function (other) {
  1475. this.x = other.x;
  1476. this.y = other.y;
  1477. this.z = other.z;
  1478. this.w = other.w;
  1479. return this;
  1480. };
  1481. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1482. this.x = x;
  1483. this.y = y;
  1484. this.z = z;
  1485. this.w = w;
  1486. return this;
  1487. };
  1488. Quaternion.prototype.add = function (other) {
  1489. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1490. };
  1491. Quaternion.prototype.subtract = function (other) {
  1492. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1493. };
  1494. Quaternion.prototype.scale = function (value) {
  1495. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1496. };
  1497. Quaternion.prototype.multiply = function (q1) {
  1498. var result = new Quaternion(0, 0, 0, 1.0);
  1499. this.multiplyToRef(q1, result);
  1500. return result;
  1501. };
  1502. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1503. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1504. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1505. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1506. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1507. result.copyFromFloats(x, y, z, w);
  1508. return this;
  1509. };
  1510. Quaternion.prototype.multiplyInPlace = function (q1) {
  1511. this.multiplyToRef(q1, this);
  1512. return this;
  1513. };
  1514. Quaternion.prototype.conjugateToRef = function (ref) {
  1515. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1516. return this;
  1517. };
  1518. Quaternion.prototype.conjugateInPlace = function () {
  1519. this.x *= -1;
  1520. this.y *= -1;
  1521. this.z *= -1;
  1522. return this;
  1523. };
  1524. Quaternion.prototype.conjugate = function () {
  1525. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1526. return result;
  1527. };
  1528. Quaternion.prototype.length = function () {
  1529. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1530. };
  1531. Quaternion.prototype.normalize = function () {
  1532. var length = 1.0 / this.length();
  1533. this.x *= length;
  1534. this.y *= length;
  1535. this.z *= length;
  1536. this.w *= length;
  1537. return this;
  1538. };
  1539. Quaternion.prototype.toEulerAngles = function (order) {
  1540. if (order === void 0) { order = "YZX"; }
  1541. var result = Vector3.Zero();
  1542. this.toEulerAnglesToRef(result, order);
  1543. return result;
  1544. };
  1545. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1546. if (order === void 0) { order = "YZX"; }
  1547. var heading, attitude, bank;
  1548. var x = this.x, y = this.y, z = this.z, w = this.w;
  1549. switch (order) {
  1550. case "YZX":
  1551. var test = x * y + z * w;
  1552. if (test > 0.499) {
  1553. heading = 2 * Math.atan2(x, w);
  1554. attitude = Math.PI / 2;
  1555. bank = 0;
  1556. }
  1557. if (test < -0.499) {
  1558. heading = -2 * Math.atan2(x, w);
  1559. attitude = -Math.PI / 2;
  1560. bank = 0;
  1561. }
  1562. if (isNaN(heading)) {
  1563. var sqx = x * x;
  1564. var sqy = y * y;
  1565. var sqz = z * z;
  1566. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1567. attitude = Math.asin(2 * test); // attitude
  1568. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1569. }
  1570. break;
  1571. default:
  1572. throw new Error("Euler order " + order + " not supported yet.");
  1573. }
  1574. result.y = heading;
  1575. result.z = attitude;
  1576. result.x = bank;
  1577. return this;
  1578. };
  1579. ;
  1580. Quaternion.prototype.toRotationMatrix = function (result) {
  1581. var xx = this.x * this.x;
  1582. var yy = this.y * this.y;
  1583. var zz = this.z * this.z;
  1584. var xy = this.x * this.y;
  1585. var zw = this.z * this.w;
  1586. var zx = this.z * this.x;
  1587. var yw = this.y * this.w;
  1588. var yz = this.y * this.z;
  1589. var xw = this.x * this.w;
  1590. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1591. result.m[1] = 2.0 * (xy + zw);
  1592. result.m[2] = 2.0 * (zx - yw);
  1593. result.m[3] = 0;
  1594. result.m[4] = 2.0 * (xy - zw);
  1595. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1596. result.m[6] = 2.0 * (yz + xw);
  1597. result.m[7] = 0;
  1598. result.m[8] = 2.0 * (zx + yw);
  1599. result.m[9] = 2.0 * (yz - xw);
  1600. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1601. result.m[11] = 0;
  1602. result.m[12] = 0;
  1603. result.m[13] = 0;
  1604. result.m[14] = 0;
  1605. result.m[15] = 1.0;
  1606. return this;
  1607. };
  1608. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1609. Quaternion.FromRotationMatrixToRef(matrix, this);
  1610. return this;
  1611. };
  1612. // Statics
  1613. Quaternion.FromRotationMatrix = function (matrix) {
  1614. var result = new Quaternion();
  1615. Quaternion.FromRotationMatrixToRef(matrix, result);
  1616. return result;
  1617. };
  1618. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1619. var data = matrix.m;
  1620. var m11 = data[0], m12 = data[4], m13 = data[8];
  1621. var m21 = data[1], m22 = data[5], m23 = data[9];
  1622. var m31 = data[2], m32 = data[6], m33 = data[10];
  1623. var trace = m11 + m22 + m33;
  1624. var s;
  1625. if (trace > 0) {
  1626. s = 0.5 / Math.sqrt(trace + 1.0);
  1627. result.w = 0.25 / s;
  1628. result.x = (m32 - m23) * s;
  1629. result.y = (m13 - m31) * s;
  1630. result.z = (m21 - m12) * s;
  1631. }
  1632. else if (m11 > m22 && m11 > m33) {
  1633. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1634. result.w = (m32 - m23) / s;
  1635. result.x = 0.25 * s;
  1636. result.y = (m12 + m21) / s;
  1637. result.z = (m13 + m31) / s;
  1638. }
  1639. else if (m22 > m33) {
  1640. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1641. result.w = (m13 - m31) / s;
  1642. result.x = (m12 + m21) / s;
  1643. result.y = 0.25 * s;
  1644. result.z = (m23 + m32) / s;
  1645. }
  1646. else {
  1647. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1648. result.w = (m21 - m12) / s;
  1649. result.x = (m13 + m31) / s;
  1650. result.y = (m23 + m32) / s;
  1651. result.z = 0.25 * s;
  1652. }
  1653. };
  1654. Quaternion.Inverse = function (q) {
  1655. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1656. };
  1657. Quaternion.Identity = function () {
  1658. return new Quaternion(0, 0, 0, 1);
  1659. };
  1660. Quaternion.RotationAxis = function (axis, angle) {
  1661. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  1662. };
  1663. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  1664. var sin = Math.sin(angle / 2);
  1665. axis.normalize();
  1666. result.w = Math.cos(angle / 2);
  1667. result.x = axis.x * sin;
  1668. result.y = axis.y * sin;
  1669. result.z = axis.z * sin;
  1670. return result;
  1671. };
  1672. Quaternion.FromArray = function (array, offset) {
  1673. if (!offset) {
  1674. offset = 0;
  1675. }
  1676. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1677. };
  1678. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1679. var q = new Quaternion();
  1680. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  1681. return q;
  1682. };
  1683. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1684. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1685. var halfRoll = roll * 0.5;
  1686. var halfPitch = pitch * 0.5;
  1687. var halfYaw = yaw * 0.5;
  1688. var sinRoll = Math.sin(halfRoll);
  1689. var cosRoll = Math.cos(halfRoll);
  1690. var sinPitch = Math.sin(halfPitch);
  1691. var cosPitch = Math.cos(halfPitch);
  1692. var sinYaw = Math.sin(halfYaw);
  1693. var cosYaw = Math.cos(halfYaw);
  1694. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1695. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1696. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1697. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1698. };
  1699. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1700. var result = new Quaternion();
  1701. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1702. return result;
  1703. };
  1704. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1705. // Produces a quaternion from Euler angles in the z-x-z orientation
  1706. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1707. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1708. var halfBeta = beta * 0.5;
  1709. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1710. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1711. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1712. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1713. };
  1714. Quaternion.Slerp = function (left, right, amount) {
  1715. var num2;
  1716. var num3;
  1717. var num = amount;
  1718. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1719. var flag = false;
  1720. if (num4 < 0) {
  1721. flag = true;
  1722. num4 = -num4;
  1723. }
  1724. if (num4 > 0.999999) {
  1725. num3 = 1 - num;
  1726. num2 = flag ? -num : num;
  1727. }
  1728. else {
  1729. var num5 = Math.acos(num4);
  1730. var num6 = (1.0 / Math.sin(num5));
  1731. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1732. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1733. }
  1734. 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));
  1735. };
  1736. return Quaternion;
  1737. }());
  1738. BABYLON.Quaternion = Quaternion;
  1739. var Matrix = (function () {
  1740. function Matrix() {
  1741. this.m = new Float32Array(16);
  1742. }
  1743. // Properties
  1744. Matrix.prototype.isIdentity = function () {
  1745. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1746. return false;
  1747. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1748. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1749. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1750. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1751. return false;
  1752. return true;
  1753. };
  1754. Matrix.prototype.determinant = function () {
  1755. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1756. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1757. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1758. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1759. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1760. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1761. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1762. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1763. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1764. };
  1765. // Methods
  1766. Matrix.prototype.toArray = function () {
  1767. return this.m;
  1768. };
  1769. Matrix.prototype.asArray = function () {
  1770. return this.toArray();
  1771. };
  1772. Matrix.prototype.invert = function () {
  1773. this.invertToRef(this);
  1774. return this;
  1775. };
  1776. Matrix.prototype.reset = function () {
  1777. for (var index = 0; index < 16; index++) {
  1778. this.m[index] = 0;
  1779. }
  1780. return this;
  1781. };
  1782. Matrix.prototype.add = function (other) {
  1783. var result = new Matrix();
  1784. this.addToRef(other, result);
  1785. return result;
  1786. };
  1787. Matrix.prototype.addToRef = function (other, result) {
  1788. for (var index = 0; index < 16; index++) {
  1789. result.m[index] = this.m[index] + other.m[index];
  1790. }
  1791. return this;
  1792. };
  1793. Matrix.prototype.addToSelf = function (other) {
  1794. for (var index = 0; index < 16; index++) {
  1795. this.m[index] += other.m[index];
  1796. }
  1797. return this;
  1798. };
  1799. Matrix.prototype.invertToRef = function (other) {
  1800. var l1 = this.m[0];
  1801. var l2 = this.m[1];
  1802. var l3 = this.m[2];
  1803. var l4 = this.m[3];
  1804. var l5 = this.m[4];
  1805. var l6 = this.m[5];
  1806. var l7 = this.m[6];
  1807. var l8 = this.m[7];
  1808. var l9 = this.m[8];
  1809. var l10 = this.m[9];
  1810. var l11 = this.m[10];
  1811. var l12 = this.m[11];
  1812. var l13 = this.m[12];
  1813. var l14 = this.m[13];
  1814. var l15 = this.m[14];
  1815. var l16 = this.m[15];
  1816. var l17 = (l11 * l16) - (l12 * l15);
  1817. var l18 = (l10 * l16) - (l12 * l14);
  1818. var l19 = (l10 * l15) - (l11 * l14);
  1819. var l20 = (l9 * l16) - (l12 * l13);
  1820. var l21 = (l9 * l15) - (l11 * l13);
  1821. var l22 = (l9 * l14) - (l10 * l13);
  1822. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1823. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1824. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1825. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1826. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1827. var l28 = (l7 * l16) - (l8 * l15);
  1828. var l29 = (l6 * l16) - (l8 * l14);
  1829. var l30 = (l6 * l15) - (l7 * l14);
  1830. var l31 = (l5 * l16) - (l8 * l13);
  1831. var l32 = (l5 * l15) - (l7 * l13);
  1832. var l33 = (l5 * l14) - (l6 * l13);
  1833. var l34 = (l7 * l12) - (l8 * l11);
  1834. var l35 = (l6 * l12) - (l8 * l10);
  1835. var l36 = (l6 * l11) - (l7 * l10);
  1836. var l37 = (l5 * l12) - (l8 * l9);
  1837. var l38 = (l5 * l11) - (l7 * l9);
  1838. var l39 = (l5 * l10) - (l6 * l9);
  1839. other.m[0] = l23 * l27;
  1840. other.m[4] = l24 * l27;
  1841. other.m[8] = l25 * l27;
  1842. other.m[12] = l26 * l27;
  1843. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1844. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1845. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1846. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1847. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1848. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1849. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1850. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1851. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1852. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1853. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1854. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1855. return this;
  1856. };
  1857. Matrix.prototype.setTranslation = function (vector3) {
  1858. this.m[12] = vector3.x;
  1859. this.m[13] = vector3.y;
  1860. this.m[14] = vector3.z;
  1861. return this;
  1862. };
  1863. Matrix.prototype.getTranslation = function () {
  1864. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1865. };
  1866. Matrix.prototype.multiply = function (other) {
  1867. var result = new Matrix();
  1868. this.multiplyToRef(other, result);
  1869. return result;
  1870. };
  1871. Matrix.prototype.copyFrom = function (other) {
  1872. for (var index = 0; index < 16; index++) {
  1873. this.m[index] = other.m[index];
  1874. }
  1875. return this;
  1876. };
  1877. Matrix.prototype.copyToArray = function (array, offset) {
  1878. if (offset === void 0) { offset = 0; }
  1879. for (var index = 0; index < 16; index++) {
  1880. array[offset + index] = this.m[index];
  1881. }
  1882. return this;
  1883. };
  1884. Matrix.prototype.multiplyToRef = function (other, result) {
  1885. this.multiplyToArray(other, result.m, 0);
  1886. return this;
  1887. };
  1888. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1889. var tm0 = this.m[0];
  1890. var tm1 = this.m[1];
  1891. var tm2 = this.m[2];
  1892. var tm3 = this.m[3];
  1893. var tm4 = this.m[4];
  1894. var tm5 = this.m[5];
  1895. var tm6 = this.m[6];
  1896. var tm7 = this.m[7];
  1897. var tm8 = this.m[8];
  1898. var tm9 = this.m[9];
  1899. var tm10 = this.m[10];
  1900. var tm11 = this.m[11];
  1901. var tm12 = this.m[12];
  1902. var tm13 = this.m[13];
  1903. var tm14 = this.m[14];
  1904. var tm15 = this.m[15];
  1905. var om0 = other.m[0];
  1906. var om1 = other.m[1];
  1907. var om2 = other.m[2];
  1908. var om3 = other.m[3];
  1909. var om4 = other.m[4];
  1910. var om5 = other.m[5];
  1911. var om6 = other.m[6];
  1912. var om7 = other.m[7];
  1913. var om8 = other.m[8];
  1914. var om9 = other.m[9];
  1915. var om10 = other.m[10];
  1916. var om11 = other.m[11];
  1917. var om12 = other.m[12];
  1918. var om13 = other.m[13];
  1919. var om14 = other.m[14];
  1920. var om15 = other.m[15];
  1921. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1922. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1923. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1924. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1925. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1926. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1927. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1928. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1929. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1930. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1931. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1932. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1933. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1934. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1935. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1936. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1937. return this;
  1938. };
  1939. Matrix.prototype.equals = function (value) {
  1940. return value &&
  1941. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1942. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1943. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1944. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1945. };
  1946. Matrix.prototype.clone = function () {
  1947. 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]);
  1948. };
  1949. Matrix.prototype.getClassName = function () {
  1950. return "Matrix";
  1951. };
  1952. Matrix.prototype.getHashCode = function () {
  1953. var hash = this.m[0] || 0;
  1954. for (var i = 1; i < 16; i++) {
  1955. hash = (hash * 397) ^ (this.m[i] || 0);
  1956. }
  1957. return hash;
  1958. };
  1959. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1960. translation.x = this.m[12];
  1961. translation.y = this.m[13];
  1962. translation.z = this.m[14];
  1963. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1964. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1965. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1966. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1967. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1968. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1969. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1970. rotation.x = 0;
  1971. rotation.y = 0;
  1972. rotation.z = 0;
  1973. rotation.w = 1;
  1974. return false;
  1975. }
  1976. 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);
  1977. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1978. return true;
  1979. };
  1980. // Statics
  1981. Matrix.FromArray = function (array, offset) {
  1982. var result = new Matrix();
  1983. if (!offset) {
  1984. offset = 0;
  1985. }
  1986. Matrix.FromArrayToRef(array, offset, result);
  1987. return result;
  1988. };
  1989. Matrix.FromArrayToRef = function (array, offset, result) {
  1990. for (var index = 0; index < 16; index++) {
  1991. result.m[index] = array[index + offset];
  1992. }
  1993. };
  1994. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1995. for (var index = 0; index < 16; index++) {
  1996. result.m[index] = array[index + offset] * scale;
  1997. }
  1998. };
  1999. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2000. result.m[0] = initialM11;
  2001. result.m[1] = initialM12;
  2002. result.m[2] = initialM13;
  2003. result.m[3] = initialM14;
  2004. result.m[4] = initialM21;
  2005. result.m[5] = initialM22;
  2006. result.m[6] = initialM23;
  2007. result.m[7] = initialM24;
  2008. result.m[8] = initialM31;
  2009. result.m[9] = initialM32;
  2010. result.m[10] = initialM33;
  2011. result.m[11] = initialM34;
  2012. result.m[12] = initialM41;
  2013. result.m[13] = initialM42;
  2014. result.m[14] = initialM43;
  2015. result.m[15] = initialM44;
  2016. };
  2017. Matrix.prototype.getRow = function (index) {
  2018. if (index < 0 || index > 3) {
  2019. return null;
  2020. }
  2021. var i = index * 4;
  2022. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2023. };
  2024. Matrix.prototype.setRow = function (index, row) {
  2025. if (index < 0 || index > 3) {
  2026. return this;
  2027. }
  2028. var i = index * 4;
  2029. this.m[i + 0] = row.x;
  2030. this.m[i + 1] = row.y;
  2031. this.m[i + 2] = row.z;
  2032. this.m[i + 3] = row.w;
  2033. return this;
  2034. };
  2035. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2036. var result = new Matrix();
  2037. result.m[0] = initialM11;
  2038. result.m[1] = initialM12;
  2039. result.m[2] = initialM13;
  2040. result.m[3] = initialM14;
  2041. result.m[4] = initialM21;
  2042. result.m[5] = initialM22;
  2043. result.m[6] = initialM23;
  2044. result.m[7] = initialM24;
  2045. result.m[8] = initialM31;
  2046. result.m[9] = initialM32;
  2047. result.m[10] = initialM33;
  2048. result.m[11] = initialM34;
  2049. result.m[12] = initialM41;
  2050. result.m[13] = initialM42;
  2051. result.m[14] = initialM43;
  2052. result.m[15] = initialM44;
  2053. return result;
  2054. };
  2055. Matrix.Compose = function (scale, rotation, translation) {
  2056. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2057. var rotationMatrix = Matrix.Identity();
  2058. rotation.toRotationMatrix(rotationMatrix);
  2059. result = result.multiply(rotationMatrix);
  2060. result.setTranslation(translation);
  2061. return result;
  2062. };
  2063. Matrix.Identity = function () {
  2064. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2065. };
  2066. Matrix.IdentityToRef = function (result) {
  2067. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2068. };
  2069. Matrix.Zero = function () {
  2070. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2071. };
  2072. Matrix.RotationX = function (angle) {
  2073. var result = new Matrix();
  2074. Matrix.RotationXToRef(angle, result);
  2075. return result;
  2076. };
  2077. Matrix.Invert = function (source) {
  2078. var result = new Matrix();
  2079. source.invertToRef(result);
  2080. return result;
  2081. };
  2082. Matrix.RotationXToRef = function (angle, result) {
  2083. var s = Math.sin(angle);
  2084. var c = Math.cos(angle);
  2085. result.m[0] = 1.0;
  2086. result.m[15] = 1.0;
  2087. result.m[5] = c;
  2088. result.m[10] = c;
  2089. result.m[9] = -s;
  2090. result.m[6] = s;
  2091. result.m[1] = 0;
  2092. result.m[2] = 0;
  2093. result.m[3] = 0;
  2094. result.m[4] = 0;
  2095. result.m[7] = 0;
  2096. result.m[8] = 0;
  2097. result.m[11] = 0;
  2098. result.m[12] = 0;
  2099. result.m[13] = 0;
  2100. result.m[14] = 0;
  2101. };
  2102. Matrix.RotationY = function (angle) {
  2103. var result = new Matrix();
  2104. Matrix.RotationYToRef(angle, result);
  2105. return result;
  2106. };
  2107. Matrix.RotationYToRef = function (angle, result) {
  2108. var s = Math.sin(angle);
  2109. var c = Math.cos(angle);
  2110. result.m[5] = 1.0;
  2111. result.m[15] = 1.0;
  2112. result.m[0] = c;
  2113. result.m[2] = -s;
  2114. result.m[8] = s;
  2115. result.m[10] = c;
  2116. result.m[1] = 0;
  2117. result.m[3] = 0;
  2118. result.m[4] = 0;
  2119. result.m[6] = 0;
  2120. result.m[7] = 0;
  2121. result.m[9] = 0;
  2122. result.m[11] = 0;
  2123. result.m[12] = 0;
  2124. result.m[13] = 0;
  2125. result.m[14] = 0;
  2126. };
  2127. Matrix.RotationZ = function (angle) {
  2128. var result = new Matrix();
  2129. Matrix.RotationZToRef(angle, result);
  2130. return result;
  2131. };
  2132. Matrix.RotationZToRef = function (angle, result) {
  2133. var s = Math.sin(angle);
  2134. var c = Math.cos(angle);
  2135. result.m[10] = 1.0;
  2136. result.m[15] = 1.0;
  2137. result.m[0] = c;
  2138. result.m[1] = s;
  2139. result.m[4] = -s;
  2140. result.m[5] = c;
  2141. result.m[2] = 0;
  2142. result.m[3] = 0;
  2143. result.m[6] = 0;
  2144. result.m[7] = 0;
  2145. result.m[8] = 0;
  2146. result.m[9] = 0;
  2147. result.m[11] = 0;
  2148. result.m[12] = 0;
  2149. result.m[13] = 0;
  2150. result.m[14] = 0;
  2151. };
  2152. Matrix.RotationAxis = function (axis, angle) {
  2153. var result = Matrix.Zero();
  2154. Matrix.RotationAxisToRef(axis, angle, result);
  2155. return result;
  2156. };
  2157. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2158. var s = Math.sin(-angle);
  2159. var c = Math.cos(-angle);
  2160. var c1 = 1 - c;
  2161. axis.normalize();
  2162. result.m[0] = (axis.x * axis.x) * c1 + c;
  2163. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2164. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2165. result.m[3] = 0.0;
  2166. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2167. result.m[5] = (axis.y * axis.y) * c1 + c;
  2168. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2169. result.m[7] = 0.0;
  2170. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2171. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2172. result.m[10] = (axis.z * axis.z) * c1 + c;
  2173. result.m[11] = 0.0;
  2174. result.m[15] = 1.0;
  2175. };
  2176. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2177. var result = new Matrix();
  2178. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2179. return result;
  2180. };
  2181. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2182. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2183. this._tempQuaternion.toRotationMatrix(result);
  2184. };
  2185. Matrix.Scaling = function (x, y, z) {
  2186. var result = Matrix.Zero();
  2187. Matrix.ScalingToRef(x, y, z, result);
  2188. return result;
  2189. };
  2190. Matrix.ScalingToRef = function (x, y, z, result) {
  2191. result.m[0] = x;
  2192. result.m[1] = 0;
  2193. result.m[2] = 0;
  2194. result.m[3] = 0;
  2195. result.m[4] = 0;
  2196. result.m[5] = y;
  2197. result.m[6] = 0;
  2198. result.m[7] = 0;
  2199. result.m[8] = 0;
  2200. result.m[9] = 0;
  2201. result.m[10] = z;
  2202. result.m[11] = 0;
  2203. result.m[12] = 0;
  2204. result.m[13] = 0;
  2205. result.m[14] = 0;
  2206. result.m[15] = 1.0;
  2207. };
  2208. Matrix.Translation = function (x, y, z) {
  2209. var result = Matrix.Identity();
  2210. Matrix.TranslationToRef(x, y, z, result);
  2211. return result;
  2212. };
  2213. Matrix.TranslationToRef = function (x, y, z, result) {
  2214. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2215. };
  2216. Matrix.Lerp = function (startValue, endValue, gradient) {
  2217. var result = Matrix.Zero();
  2218. for (var index = 0; index < 16; index++) {
  2219. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2220. }
  2221. return result;
  2222. };
  2223. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2224. var startScale = new Vector3(0, 0, 0);
  2225. var startRotation = new Quaternion();
  2226. var startTranslation = new Vector3(0, 0, 0);
  2227. startValue.decompose(startScale, startRotation, startTranslation);
  2228. var endScale = new Vector3(0, 0, 0);
  2229. var endRotation = new Quaternion();
  2230. var endTranslation = new Vector3(0, 0, 0);
  2231. endValue.decompose(endScale, endRotation, endTranslation);
  2232. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2233. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2234. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2235. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2236. };
  2237. Matrix.LookAtLH = function (eye, target, up) {
  2238. var result = Matrix.Zero();
  2239. Matrix.LookAtLHToRef(eye, target, up, result);
  2240. return result;
  2241. };
  2242. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2243. // Z axis
  2244. target.subtractToRef(eye, this._zAxis);
  2245. this._zAxis.normalize();
  2246. // X axis
  2247. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2248. if (this._xAxis.lengthSquared() === 0) {
  2249. this._xAxis.x = 1.0;
  2250. }
  2251. else {
  2252. this._xAxis.normalize();
  2253. }
  2254. // Y axis
  2255. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2256. this._yAxis.normalize();
  2257. // Eye angles
  2258. var ex = -Vector3.Dot(this._xAxis, eye);
  2259. var ey = -Vector3.Dot(this._yAxis, eye);
  2260. var ez = -Vector3.Dot(this._zAxis, eye);
  2261. 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);
  2262. };
  2263. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2264. var matrix = Matrix.Zero();
  2265. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2266. return matrix;
  2267. };
  2268. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2269. var hw = 2.0 / width;
  2270. var hh = 2.0 / height;
  2271. var id = 1.0 / (zfar - znear);
  2272. var nid = znear / (znear - zfar);
  2273. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2274. };
  2275. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2276. var matrix = Matrix.Zero();
  2277. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2278. return matrix;
  2279. };
  2280. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2281. result.m[0] = 2.0 / (right - left);
  2282. result.m[1] = result.m[2] = result.m[3] = 0;
  2283. result.m[5] = 2.0 / (top - bottom);
  2284. result.m[4] = result.m[6] = result.m[7] = 0;
  2285. result.m[10] = -1.0 / (znear - zfar);
  2286. result.m[8] = result.m[9] = result.m[11] = 0;
  2287. result.m[12] = (left + right) / (left - right);
  2288. result.m[13] = (top + bottom) / (bottom - top);
  2289. result.m[14] = znear / (znear - zfar);
  2290. result.m[15] = 1.0;
  2291. };
  2292. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2293. var matrix = Matrix.Zero();
  2294. matrix.m[0] = (2.0 * znear) / width;
  2295. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2296. matrix.m[5] = (2.0 * znear) / height;
  2297. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2298. matrix.m[10] = -zfar / (znear - zfar);
  2299. matrix.m[8] = matrix.m[9] = 0.0;
  2300. matrix.m[11] = 1.0;
  2301. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2302. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2303. return matrix;
  2304. };
  2305. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2306. var matrix = Matrix.Zero();
  2307. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2308. return matrix;
  2309. };
  2310. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2311. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2312. var tan = 1.0 / (Math.tan(fov * 0.5));
  2313. if (isVerticalFovFixed) {
  2314. result.m[0] = tan / aspect;
  2315. }
  2316. else {
  2317. result.m[0] = tan;
  2318. }
  2319. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2320. if (isVerticalFovFixed) {
  2321. result.m[5] = tan;
  2322. }
  2323. else {
  2324. result.m[5] = tan * aspect;
  2325. }
  2326. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2327. result.m[8] = result.m[9] = 0.0;
  2328. result.m[10] = -zfar / (znear - zfar);
  2329. result.m[11] = 1.0;
  2330. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2331. result.m[14] = (znear * zfar) / (znear - zfar);
  2332. };
  2333. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2334. var cw = viewport.width;
  2335. var ch = viewport.height;
  2336. var cx = viewport.x;
  2337. var cy = viewport.y;
  2338. 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);
  2339. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2340. };
  2341. Matrix.GetAsMatrix2x2 = function (matrix) {
  2342. return new Float32Array([
  2343. matrix.m[0], matrix.m[1],
  2344. matrix.m[4], matrix.m[5]
  2345. ]);
  2346. };
  2347. Matrix.GetAsMatrix3x3 = function (matrix) {
  2348. return new Float32Array([
  2349. matrix.m[0], matrix.m[1], matrix.m[2],
  2350. matrix.m[4], matrix.m[5], matrix.m[6],
  2351. matrix.m[8], matrix.m[9], matrix.m[10]
  2352. ]);
  2353. };
  2354. Matrix.Transpose = function (matrix) {
  2355. var result = new Matrix();
  2356. result.m[0] = matrix.m[0];
  2357. result.m[1] = matrix.m[4];
  2358. result.m[2] = matrix.m[8];
  2359. result.m[3] = matrix.m[12];
  2360. result.m[4] = matrix.m[1];
  2361. result.m[5] = matrix.m[5];
  2362. result.m[6] = matrix.m[9];
  2363. result.m[7] = matrix.m[13];
  2364. result.m[8] = matrix.m[2];
  2365. result.m[9] = matrix.m[6];
  2366. result.m[10] = matrix.m[10];
  2367. result.m[11] = matrix.m[14];
  2368. result.m[12] = matrix.m[3];
  2369. result.m[13] = matrix.m[7];
  2370. result.m[14] = matrix.m[11];
  2371. result.m[15] = matrix.m[15];
  2372. return result;
  2373. };
  2374. Matrix.Reflection = function (plane) {
  2375. var matrix = new Matrix();
  2376. Matrix.ReflectionToRef(plane, matrix);
  2377. return matrix;
  2378. };
  2379. Matrix.ReflectionToRef = function (plane, result) {
  2380. plane.normalize();
  2381. var x = plane.normal.x;
  2382. var y = plane.normal.y;
  2383. var z = plane.normal.z;
  2384. var temp = -2 * x;
  2385. var temp2 = -2 * y;
  2386. var temp3 = -2 * z;
  2387. result.m[0] = (temp * x) + 1;
  2388. result.m[1] = temp2 * x;
  2389. result.m[2] = temp3 * x;
  2390. result.m[3] = 0.0;
  2391. result.m[4] = temp * y;
  2392. result.m[5] = (temp2 * y) + 1;
  2393. result.m[6] = temp3 * y;
  2394. result.m[7] = 0.0;
  2395. result.m[8] = temp * z;
  2396. result.m[9] = temp2 * z;
  2397. result.m[10] = (temp3 * z) + 1;
  2398. result.m[11] = 0.0;
  2399. result.m[12] = temp * plane.d;
  2400. result.m[13] = temp2 * plane.d;
  2401. result.m[14] = temp3 * plane.d;
  2402. result.m[15] = 1.0;
  2403. };
  2404. Matrix._tempQuaternion = new Quaternion();
  2405. Matrix._xAxis = Vector3.Zero();
  2406. Matrix._yAxis = Vector3.Zero();
  2407. Matrix._zAxis = Vector3.Zero();
  2408. return Matrix;
  2409. }());
  2410. BABYLON.Matrix = Matrix;
  2411. var Plane = (function () {
  2412. function Plane(a, b, c, d) {
  2413. this.normal = new Vector3(a, b, c);
  2414. this.d = d;
  2415. }
  2416. Plane.prototype.asArray = function () {
  2417. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2418. };
  2419. // Methods
  2420. Plane.prototype.clone = function () {
  2421. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2422. };
  2423. Plane.prototype.getClassName = function () {
  2424. return "Plane";
  2425. };
  2426. Plane.prototype.getHashCode = function () {
  2427. var hash = this.normal.getHashCode();
  2428. hash = (hash * 397) ^ (this.d || 0);
  2429. return hash;
  2430. };
  2431. Plane.prototype.normalize = function () {
  2432. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2433. var magnitude = 0;
  2434. if (norm !== 0) {
  2435. magnitude = 1.0 / norm;
  2436. }
  2437. this.normal.x *= magnitude;
  2438. this.normal.y *= magnitude;
  2439. this.normal.z *= magnitude;
  2440. this.d *= magnitude;
  2441. return this;
  2442. };
  2443. Plane.prototype.transform = function (transformation) {
  2444. var transposedMatrix = Matrix.Transpose(transformation);
  2445. var x = this.normal.x;
  2446. var y = this.normal.y;
  2447. var z = this.normal.z;
  2448. var d = this.d;
  2449. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2450. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2451. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2452. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2453. return new Plane(normalX, normalY, normalZ, finalD);
  2454. };
  2455. Plane.prototype.dotCoordinate = function (point) {
  2456. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2457. };
  2458. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2459. var x1 = point2.x - point1.x;
  2460. var y1 = point2.y - point1.y;
  2461. var z1 = point2.z - point1.z;
  2462. var x2 = point3.x - point1.x;
  2463. var y2 = point3.y - point1.y;
  2464. var z2 = point3.z - point1.z;
  2465. var yz = (y1 * z2) - (z1 * y2);
  2466. var xz = (z1 * x2) - (x1 * z2);
  2467. var xy = (x1 * y2) - (y1 * x2);
  2468. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2469. var invPyth;
  2470. if (pyth !== 0) {
  2471. invPyth = 1.0 / pyth;
  2472. }
  2473. else {
  2474. invPyth = 0;
  2475. }
  2476. this.normal.x = yz * invPyth;
  2477. this.normal.y = xz * invPyth;
  2478. this.normal.z = xy * invPyth;
  2479. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2480. return this;
  2481. };
  2482. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2483. var dot = Vector3.Dot(this.normal, direction);
  2484. return (dot <= epsilon);
  2485. };
  2486. Plane.prototype.signedDistanceTo = function (point) {
  2487. return Vector3.Dot(point, this.normal) + this.d;
  2488. };
  2489. // Statics
  2490. Plane.FromArray = function (array) {
  2491. return new Plane(array[0], array[1], array[2], array[3]);
  2492. };
  2493. Plane.FromPoints = function (point1, point2, point3) {
  2494. var result = new Plane(0, 0, 0, 0);
  2495. result.copyFromPoints(point1, point2, point3);
  2496. return result;
  2497. };
  2498. Plane.FromPositionAndNormal = function (origin, normal) {
  2499. var result = new Plane(0, 0, 0, 0);
  2500. normal.normalize();
  2501. result.normal = normal;
  2502. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2503. return result;
  2504. };
  2505. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2506. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2507. return Vector3.Dot(point, normal) + d;
  2508. };
  2509. return Plane;
  2510. }());
  2511. BABYLON.Plane = Plane;
  2512. var Viewport = (function () {
  2513. function Viewport(x, y, width, height) {
  2514. this.x = x;
  2515. this.y = y;
  2516. this.width = width;
  2517. this.height = height;
  2518. }
  2519. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2520. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2521. };
  2522. return Viewport;
  2523. }());
  2524. BABYLON.Viewport = Viewport;
  2525. var Frustum = (function () {
  2526. function Frustum() {
  2527. }
  2528. Frustum.GetPlanes = function (transform) {
  2529. var frustumPlanes = [];
  2530. for (var index = 0; index < 6; index++) {
  2531. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2532. }
  2533. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2534. return frustumPlanes;
  2535. };
  2536. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2537. // Near
  2538. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2539. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2540. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2541. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2542. frustumPlanes[0].normalize();
  2543. // Far
  2544. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2545. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2546. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2547. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2548. frustumPlanes[1].normalize();
  2549. // Left
  2550. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2551. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2552. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2553. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2554. frustumPlanes[2].normalize();
  2555. // Right
  2556. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2557. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2558. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2559. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2560. frustumPlanes[3].normalize();
  2561. // Top
  2562. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2563. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2564. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2565. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2566. frustumPlanes[4].normalize();
  2567. // Bottom
  2568. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2569. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2570. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2571. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2572. frustumPlanes[5].normalize();
  2573. };
  2574. return Frustum;
  2575. }());
  2576. BABYLON.Frustum = Frustum;
  2577. (function (Space) {
  2578. Space[Space["LOCAL"] = 0] = "LOCAL";
  2579. Space[Space["WORLD"] = 1] = "WORLD";
  2580. })(BABYLON.Space || (BABYLON.Space = {}));
  2581. var Space = BABYLON.Space;
  2582. var Axis = (function () {
  2583. function Axis() {
  2584. }
  2585. Axis.X = new Vector3(1, 0, 0);
  2586. Axis.Y = new Vector3(0, 1, 0);
  2587. Axis.Z = new Vector3(0, 0, 1);
  2588. return Axis;
  2589. }());
  2590. BABYLON.Axis = Axis;
  2591. ;
  2592. var BezierCurve = (function () {
  2593. function BezierCurve() {
  2594. }
  2595. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2596. // Extract X (which is equal to time here)
  2597. var f0 = 1 - 3 * x2 + 3 * x1;
  2598. var f1 = 3 * x2 - 6 * x1;
  2599. var f2 = 3 * x1;
  2600. var refinedT = t;
  2601. for (var i = 0; i < 5; i++) {
  2602. var refinedT2 = refinedT * refinedT;
  2603. var refinedT3 = refinedT2 * refinedT;
  2604. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2605. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2606. refinedT -= (x - t) * slope;
  2607. refinedT = Math.min(1, Math.max(0, refinedT));
  2608. }
  2609. // Resolve cubic bezier for the given x
  2610. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2611. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2612. Math.pow(refinedT, 3);
  2613. };
  2614. return BezierCurve;
  2615. }());
  2616. BABYLON.BezierCurve = BezierCurve;
  2617. (function (Orientation) {
  2618. Orientation[Orientation["CW"] = 0] = "CW";
  2619. Orientation[Orientation["CCW"] = 1] = "CCW";
  2620. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2621. var Orientation = BABYLON.Orientation;
  2622. var Angle = (function () {
  2623. function Angle(radians) {
  2624. var _this = this;
  2625. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2626. this.radians = function () { return _this._radians; };
  2627. this._radians = radians;
  2628. if (this._radians < 0)
  2629. this._radians += (2 * Math.PI);
  2630. }
  2631. Angle.BetweenTwoPoints = function (a, b) {
  2632. var delta = b.subtract(a);
  2633. var theta = Math.atan2(delta.y, delta.x);
  2634. return new Angle(theta);
  2635. };
  2636. Angle.FromRadians = function (radians) {
  2637. return new Angle(radians);
  2638. };
  2639. Angle.FromDegrees = function (degrees) {
  2640. return new Angle(degrees * Math.PI / 180);
  2641. };
  2642. return Angle;
  2643. }());
  2644. BABYLON.Angle = Angle;
  2645. var Arc2 = (function () {
  2646. function Arc2(startPoint, midPoint, endPoint) {
  2647. this.startPoint = startPoint;
  2648. this.midPoint = midPoint;
  2649. this.endPoint = endPoint;
  2650. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2651. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2652. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2653. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2654. 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);
  2655. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2656. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2657. var a1 = this.startAngle.degrees();
  2658. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2659. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2660. // angles correction
  2661. if (a2 - a1 > +180.0)
  2662. a2 -= 360.0;
  2663. if (a2 - a1 < -180.0)
  2664. a2 += 360.0;
  2665. if (a3 - a2 > +180.0)
  2666. a3 -= 360.0;
  2667. if (a3 - a2 < -180.0)
  2668. a3 += 360.0;
  2669. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2670. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2671. }
  2672. return Arc2;
  2673. }());
  2674. BABYLON.Arc2 = Arc2;
  2675. var Path2 = (function () {
  2676. function Path2(x, y) {
  2677. this._points = new Array();
  2678. this._length = 0;
  2679. this.closed = false;
  2680. this._points.push(new Vector2(x, y));
  2681. }
  2682. Path2.prototype.addLineTo = function (x, y) {
  2683. if (closed) {
  2684. //Tools.Error("cannot add lines to closed paths");
  2685. return this;
  2686. }
  2687. var newPoint = new Vector2(x, y);
  2688. var previousPoint = this._points[this._points.length - 1];
  2689. this._points.push(newPoint);
  2690. this._length += newPoint.subtract(previousPoint).length();
  2691. return this;
  2692. };
  2693. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2694. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2695. if (closed) {
  2696. //Tools.Error("cannot add arcs to closed paths");
  2697. return this;
  2698. }
  2699. var startPoint = this._points[this._points.length - 1];
  2700. var midPoint = new Vector2(midX, midY);
  2701. var endPoint = new Vector2(endX, endY);
  2702. var arc = new Arc2(startPoint, midPoint, endPoint);
  2703. var increment = arc.angle.radians() / numberOfSegments;
  2704. if (arc.orientation === Orientation.CW)
  2705. increment *= -1;
  2706. var currentAngle = arc.startAngle.radians() + increment;
  2707. for (var i = 0; i < numberOfSegments; i++) {
  2708. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2709. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2710. this.addLineTo(x, y);
  2711. currentAngle += increment;
  2712. }
  2713. return this;
  2714. };
  2715. Path2.prototype.close = function () {
  2716. this.closed = true;
  2717. return this;
  2718. };
  2719. Path2.prototype.length = function () {
  2720. var result = this._length;
  2721. if (!this.closed) {
  2722. var lastPoint = this._points[this._points.length - 1];
  2723. var firstPoint = this._points[0];
  2724. result += (firstPoint.subtract(lastPoint).length());
  2725. }
  2726. return result;
  2727. };
  2728. Path2.prototype.getPoints = function () {
  2729. return this._points;
  2730. };
  2731. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2732. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2733. //Tools.Error("normalized length position should be between 0 and 1.");
  2734. return Vector2.Zero();
  2735. }
  2736. var lengthPosition = normalizedLengthPosition * this.length();
  2737. var previousOffset = 0;
  2738. for (var i = 0; i < this._points.length; i++) {
  2739. var j = (i + 1) % this._points.length;
  2740. var a = this._points[i];
  2741. var b = this._points[j];
  2742. var bToA = b.subtract(a);
  2743. var nextOffset = (bToA.length() + previousOffset);
  2744. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2745. var dir = bToA.normalize();
  2746. var localOffset = lengthPosition - previousOffset;
  2747. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2748. }
  2749. previousOffset = nextOffset;
  2750. }
  2751. //Tools.Error("internal error");
  2752. return Vector2.Zero();
  2753. };
  2754. Path2.StartingAt = function (x, y) {
  2755. return new Path2(x, y);
  2756. };
  2757. return Path2;
  2758. }());
  2759. BABYLON.Path2 = Path2;
  2760. var Path3D = (function () {
  2761. /**
  2762. * new Path3D(path, normal, raw)
  2763. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2764. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2765. * path : an array of Vector3, the curve axis of the Path3D
  2766. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2767. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2768. */
  2769. function Path3D(path, firstNormal, raw) {
  2770. this.path = path;
  2771. this._curve = new Array();
  2772. this._distances = new Array();
  2773. this._tangents = new Array();
  2774. this._normals = new Array();
  2775. this._binormals = new Array();
  2776. for (var p = 0; p < path.length; p++) {
  2777. this._curve[p] = path[p].clone(); // hard copy
  2778. }
  2779. this._raw = raw || false;
  2780. this._compute(firstNormal);
  2781. }
  2782. /**
  2783. * Returns the Path3D array of successive Vector3 designing its curve.
  2784. */
  2785. Path3D.prototype.getCurve = function () {
  2786. return this._curve;
  2787. };
  2788. /**
  2789. * Returns an array populated with tangent vectors on each Path3D curve point.
  2790. */
  2791. Path3D.prototype.getTangents = function () {
  2792. return this._tangents;
  2793. };
  2794. /**
  2795. * Returns an array populated with normal vectors on each Path3D curve point.
  2796. */
  2797. Path3D.prototype.getNormals = function () {
  2798. return this._normals;
  2799. };
  2800. /**
  2801. * Returns an array populated with binormal vectors on each Path3D curve point.
  2802. */
  2803. Path3D.prototype.getBinormals = function () {
  2804. return this._binormals;
  2805. };
  2806. /**
  2807. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2808. */
  2809. Path3D.prototype.getDistances = function () {
  2810. return this._distances;
  2811. };
  2812. /**
  2813. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2814. * Returns the same object updated.
  2815. */
  2816. Path3D.prototype.update = function (path, firstNormal) {
  2817. for (var p = 0; p < path.length; p++) {
  2818. this._curve[p].x = path[p].x;
  2819. this._curve[p].y = path[p].y;
  2820. this._curve[p].z = path[p].z;
  2821. }
  2822. this._compute(firstNormal);
  2823. return this;
  2824. };
  2825. // private function compute() : computes tangents, normals and binormals
  2826. Path3D.prototype._compute = function (firstNormal) {
  2827. var l = this._curve.length;
  2828. // first and last tangents
  2829. this._tangents[0] = this._getFirstNonNullVector(0);
  2830. if (!this._raw) {
  2831. this._tangents[0].normalize();
  2832. }
  2833. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2834. if (!this._raw) {
  2835. this._tangents[l - 1].normalize();
  2836. }
  2837. // normals and binormals at first point : arbitrary vector with _normalVector()
  2838. var tg0 = this._tangents[0];
  2839. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2840. this._normals[0] = pp0;
  2841. if (!this._raw) {
  2842. this._normals[0].normalize();
  2843. }
  2844. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2845. if (!this._raw) {
  2846. this._binormals[0].normalize();
  2847. }
  2848. this._distances[0] = 0;
  2849. // normals and binormals : next points
  2850. var prev; // previous vector (segment)
  2851. var cur; // current vector (segment)
  2852. var curTang; // current tangent
  2853. // previous normal
  2854. var prevBinor; // previous binormal
  2855. for (var i = 1; i < l; i++) {
  2856. // tangents
  2857. prev = this._getLastNonNullVector(i);
  2858. if (i < l - 1) {
  2859. cur = this._getFirstNonNullVector(i);
  2860. this._tangents[i] = prev.add(cur);
  2861. this._tangents[i].normalize();
  2862. }
  2863. this._distances[i] = this._distances[i - 1] + prev.length();
  2864. // normals and binormals
  2865. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2866. curTang = this._tangents[i];
  2867. prevBinor = this._binormals[i - 1];
  2868. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2869. if (!this._raw) {
  2870. this._normals[i].normalize();
  2871. }
  2872. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2873. if (!this._raw) {
  2874. this._binormals[i].normalize();
  2875. }
  2876. }
  2877. };
  2878. // private function getFirstNonNullVector(index)
  2879. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2880. Path3D.prototype._getFirstNonNullVector = function (index) {
  2881. var i = 1;
  2882. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2883. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2884. i++;
  2885. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2886. }
  2887. return nNVector;
  2888. };
  2889. // private function getLastNonNullVector(index)
  2890. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2891. Path3D.prototype._getLastNonNullVector = function (index) {
  2892. var i = 1;
  2893. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2894. while (nLVector.length() === 0 && index > i + 1) {
  2895. i++;
  2896. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2897. }
  2898. return nLVector;
  2899. };
  2900. // private function normalVector(v0, vt, va) :
  2901. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2902. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2903. Path3D.prototype._normalVector = function (v0, vt, va) {
  2904. var normal0;
  2905. if (va === undefined || va === null) {
  2906. var point;
  2907. if (!MathTools.WithinEpsilon(vt.y, 1, BABYLON.Epsilon)) {
  2908. point = new Vector3(0, -1, 0);
  2909. }
  2910. else if (!MathTools.WithinEpsilon(vt.x, 1, BABYLON.Epsilon)) {
  2911. point = new Vector3(1, 0, 0);
  2912. }
  2913. else if (!MathTools.WithinEpsilon(vt.z, 1, BABYLON.Epsilon)) {
  2914. point = new Vector3(0, 0, 1);
  2915. }
  2916. normal0 = Vector3.Cross(vt, point);
  2917. }
  2918. else {
  2919. normal0 = Vector3.Cross(vt, va);
  2920. Vector3.CrossToRef(normal0, vt, normal0);
  2921. }
  2922. normal0.normalize();
  2923. return normal0;
  2924. };
  2925. return Path3D;
  2926. }());
  2927. BABYLON.Path3D = Path3D;
  2928. var Curve3 = (function () {
  2929. /**
  2930. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  2931. * A Curve3 is designed from a series of successive Vector3.
  2932. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  2933. */
  2934. function Curve3(points) {
  2935. this._length = 0;
  2936. this._points = points;
  2937. this._length = this._computeLength(points);
  2938. }
  2939. /**
  2940. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  2941. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  2942. * @param v1 (Vector3) the control point
  2943. * @param v2 (Vector3) the end point of the Quadratic Bezier
  2944. * @param nbPoints (integer) the wanted number of points in the curve
  2945. */
  2946. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2947. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2948. var bez = new Array();
  2949. var equation = function (t, val0, val1, val2) {
  2950. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2951. return res;
  2952. };
  2953. for (var i = 0; i <= nbPoints; i++) {
  2954. 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)));
  2955. }
  2956. return new Curve3(bez);
  2957. };
  2958. /**
  2959. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  2960. * @param v0 (Vector3) the origin point of the Cubic Bezier
  2961. * @param v1 (Vector3) the first control point
  2962. * @param v2 (Vector3) the second control point
  2963. * @param v3 (Vector3) the end point of the Cubic Bezier
  2964. * @param nbPoints (integer) the wanted number of points in the curve
  2965. */
  2966. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2967. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2968. var bez = new Array();
  2969. var equation = function (t, val0, val1, val2, val3) {
  2970. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2971. return res;
  2972. };
  2973. for (var i = 0; i <= nbPoints; i++) {
  2974. 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)));
  2975. }
  2976. return new Curve3(bez);
  2977. };
  2978. /**
  2979. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  2980. * @param p1 (Vector3) the origin point of the Hermite Spline
  2981. * @param t1 (Vector3) the tangent vector at the origin point
  2982. * @param p2 (Vector3) the end point of the Hermite Spline
  2983. * @param t2 (Vector3) the tangent vector at the end point
  2984. * @param nbPoints (integer) the wanted number of points in the curve
  2985. */
  2986. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2987. var hermite = new Array();
  2988. var step = 1 / nbPoints;
  2989. for (var i = 0; i <= nbPoints; i++) {
  2990. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2991. }
  2992. return new Curve3(hermite);
  2993. };
  2994. /**
  2995. * Returns the Curve3 stored array of successive Vector3
  2996. */
  2997. Curve3.prototype.getPoints = function () {
  2998. return this._points;
  2999. };
  3000. /**
  3001. * Returns the computed length (float) of the curve.
  3002. */
  3003. Curve3.prototype.length = function () {
  3004. return this._length;
  3005. };
  3006. /**
  3007. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  3008. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  3009. * curveA and curveB keep unchanged.
  3010. */
  3011. Curve3.prototype.continue = function (curve) {
  3012. var lastPoint = this._points[this._points.length - 1];
  3013. var continuedPoints = this._points.slice();
  3014. var curvePoints = curve.getPoints();
  3015. for (var i = 1; i < curvePoints.length; i++) {
  3016. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3017. }
  3018. var continuedCurve = new Curve3(continuedPoints);
  3019. return continuedCurve;
  3020. };
  3021. Curve3.prototype._computeLength = function (path) {
  3022. var l = 0;
  3023. for (var i = 1; i < path.length; i++) {
  3024. l += (path[i].subtract(path[i - 1])).length();
  3025. }
  3026. return l;
  3027. };
  3028. return Curve3;
  3029. }());
  3030. BABYLON.Curve3 = Curve3;
  3031. // SphericalHarmonics
  3032. var SphericalHarmonics = (function () {
  3033. function SphericalHarmonics() {
  3034. this.L00 = Vector3.Zero();
  3035. this.L1_1 = Vector3.Zero();
  3036. this.L10 = Vector3.Zero();
  3037. this.L11 = Vector3.Zero();
  3038. this.L2_2 = Vector3.Zero();
  3039. this.L2_1 = Vector3.Zero();
  3040. this.L20 = Vector3.Zero();
  3041. this.L21 = Vector3.Zero();
  3042. this.L22 = Vector3.Zero();
  3043. }
  3044. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3045. var colorVector = new Vector3(color.r, color.g, color.b);
  3046. var c = colorVector.scale(deltaSolidAngle);
  3047. this.L00 = this.L00.add(c.scale(0.282095));
  3048. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3049. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3050. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3051. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3052. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3053. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3054. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3055. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3056. };
  3057. SphericalHarmonics.prototype.scale = function (scale) {
  3058. this.L00 = this.L00.scale(scale);
  3059. this.L1_1 = this.L1_1.scale(scale);
  3060. this.L10 = this.L10.scale(scale);
  3061. this.L11 = this.L11.scale(scale);
  3062. this.L2_2 = this.L2_2.scale(scale);
  3063. this.L2_1 = this.L2_1.scale(scale);
  3064. this.L20 = this.L20.scale(scale);
  3065. this.L21 = this.L21.scale(scale);
  3066. this.L22 = this.L22.scale(scale);
  3067. };
  3068. return SphericalHarmonics;
  3069. }());
  3070. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3071. // SphericalPolynomial
  3072. var SphericalPolynomial = (function () {
  3073. function SphericalPolynomial() {
  3074. this.x = Vector3.Zero();
  3075. this.y = Vector3.Zero();
  3076. this.z = Vector3.Zero();
  3077. this.xx = Vector3.Zero();
  3078. this.yy = Vector3.Zero();
  3079. this.zz = Vector3.Zero();
  3080. this.xy = Vector3.Zero();
  3081. this.yz = Vector3.Zero();
  3082. this.zx = Vector3.Zero();
  3083. }
  3084. SphericalPolynomial.prototype.addAmbient = function (color) {
  3085. var colorVector = new Vector3(color.r, color.g, color.b);
  3086. this.xx = this.xx.add(colorVector);
  3087. this.yy = this.yy.add(colorVector);
  3088. this.zz = this.zz.add(colorVector);
  3089. };
  3090. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3091. var result = new SphericalPolynomial();
  3092. result.x = harmonics.L11.scale(1.02333);
  3093. result.y = harmonics.L1_1.scale(1.02333);
  3094. result.z = harmonics.L10.scale(1.02333);
  3095. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3096. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3097. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3098. result.yz = harmonics.L2_1.scale(0.858086);
  3099. result.zx = harmonics.L21.scale(0.858086);
  3100. result.xy = harmonics.L2_2.scale(0.858086);
  3101. return result;
  3102. };
  3103. return SphericalPolynomial;
  3104. }());
  3105. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3106. // Vertex formats
  3107. var PositionNormalVertex = (function () {
  3108. function PositionNormalVertex(position, normal) {
  3109. if (position === void 0) { position = Vector3.Zero(); }
  3110. if (normal === void 0) { normal = Vector3.Up(); }
  3111. this.position = position;
  3112. this.normal = normal;
  3113. }
  3114. PositionNormalVertex.prototype.clone = function () {
  3115. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3116. };
  3117. return PositionNormalVertex;
  3118. }());
  3119. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3120. var PositionNormalTextureVertex = (function () {
  3121. function PositionNormalTextureVertex(position, normal, uv) {
  3122. if (position === void 0) { position = Vector3.Zero(); }
  3123. if (normal === void 0) { normal = Vector3.Up(); }
  3124. if (uv === void 0) { uv = Vector2.Zero(); }
  3125. this.position = position;
  3126. this.normal = normal;
  3127. this.uv = uv;
  3128. }
  3129. PositionNormalTextureVertex.prototype.clone = function () {
  3130. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3131. };
  3132. return PositionNormalTextureVertex;
  3133. }());
  3134. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3135. // Temporary pre-allocated objects for engine internal use
  3136. // usage in any internal function :
  3137. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3138. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3139. var Tmp = (function () {
  3140. function Tmp() {
  3141. }
  3142. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3143. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3144. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3145. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3146. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3147. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3148. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3149. Matrix.Zero(), Matrix.Zero(),
  3150. Matrix.Zero(), Matrix.Zero(),
  3151. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3152. return Tmp;
  3153. }());
  3154. BABYLON.Tmp = Tmp;
  3155. })(BABYLON || (BABYLON = {}));
  3156. var BABYLON;
  3157. (function (BABYLON) {
  3158. function generateSerializableMember(type, sourceName) {
  3159. return function (target, propertyKey) {
  3160. if (!target.__serializableMembers) {
  3161. target.__serializableMembers = {};
  3162. }
  3163. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3164. };
  3165. }
  3166. function serialize(sourceName) {
  3167. return generateSerializableMember(0, sourceName); // value member
  3168. }
  3169. BABYLON.serialize = serialize;
  3170. function serializeAsTexture(sourceName) {
  3171. return generateSerializableMember(1, sourceName); // texture member
  3172. }
  3173. BABYLON.serializeAsTexture = serializeAsTexture;
  3174. function serializeAsColor3(sourceName) {
  3175. return generateSerializableMember(2, sourceName); // color3 member
  3176. }
  3177. BABYLON.serializeAsColor3 = serializeAsColor3;
  3178. function serializeAsFresnelParameters(sourceName) {
  3179. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3180. }
  3181. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3182. function serializeAsVector2(sourceName) {
  3183. return generateSerializableMember(4, sourceName); // vector2 member
  3184. }
  3185. BABYLON.serializeAsVector2 = serializeAsVector2;
  3186. function serializeAsVector3(sourceName) {
  3187. return generateSerializableMember(5, sourceName); // vector3 member
  3188. }
  3189. BABYLON.serializeAsVector3 = serializeAsVector3;
  3190. function serializeAsMeshReference(sourceName) {
  3191. return generateSerializableMember(6, sourceName); // mesh reference member
  3192. }
  3193. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3194. function serializeAsColorCurves(sourceName) {
  3195. return generateSerializableMember(7, sourceName); // color curves
  3196. }
  3197. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3198. var SerializationHelper = (function () {
  3199. function SerializationHelper() {
  3200. }
  3201. SerializationHelper.Serialize = function (entity, serializationObject) {
  3202. if (!serializationObject) {
  3203. serializationObject = {};
  3204. }
  3205. // Tags
  3206. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3207. // Properties
  3208. for (var property in entity.__serializableMembers) {
  3209. var propertyDescriptor = entity.__serializableMembers[property];
  3210. var targetPropertyName = propertyDescriptor.sourceName || property;
  3211. var propertyType = propertyDescriptor.type;
  3212. var sourceProperty = entity[property];
  3213. if (sourceProperty !== undefined && sourceProperty !== null) {
  3214. switch (propertyType) {
  3215. case 0:
  3216. serializationObject[targetPropertyName] = sourceProperty;
  3217. break;
  3218. case 1:
  3219. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3220. break;
  3221. case 2:
  3222. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3223. break;
  3224. case 3:
  3225. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3226. break;
  3227. case 4:
  3228. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3229. break;
  3230. case 5:
  3231. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3232. break;
  3233. case 6:
  3234. serializationObject[targetPropertyName] = sourceProperty.id;
  3235. break;
  3236. case 7:
  3237. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3238. break;
  3239. }
  3240. }
  3241. }
  3242. return serializationObject;
  3243. };
  3244. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3245. var destination = creationFunction();
  3246. // Tags
  3247. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3248. // Properties
  3249. for (var property in destination.__serializableMembers) {
  3250. var propertyDescriptor = destination.__serializableMembers[property];
  3251. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3252. var propertyType = propertyDescriptor.type;
  3253. if (sourceProperty !== undefined && sourceProperty !== null) {
  3254. switch (propertyType) {
  3255. case 0:
  3256. destination[property] = sourceProperty;
  3257. break;
  3258. case 1:
  3259. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3260. break;
  3261. case 2:
  3262. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3263. break;
  3264. case 3:
  3265. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3266. break;
  3267. case 4:
  3268. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3269. break;
  3270. case 5:
  3271. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3272. break;
  3273. case 6:
  3274. destination[property] = scene.getLastMeshByID(sourceProperty);
  3275. break;
  3276. case 7:
  3277. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3278. break;
  3279. }
  3280. }
  3281. }
  3282. return destination;
  3283. };
  3284. SerializationHelper.Clone = function (creationFunction, source) {
  3285. var destination = creationFunction();
  3286. // Tags
  3287. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3288. // Properties
  3289. for (var property in destination.__serializableMembers) {
  3290. var propertyDescriptor = destination.__serializableMembers[property];
  3291. var sourceProperty = source[property];
  3292. var propertyType = propertyDescriptor.type;
  3293. if (sourceProperty !== undefined && sourceProperty !== null) {
  3294. switch (propertyType) {
  3295. case 0: // Value
  3296. case 6:
  3297. destination[property] = sourceProperty;
  3298. break;
  3299. case 1: // Texture
  3300. case 2: // Color3
  3301. case 3: // FresnelParameters
  3302. case 4: // Vector2
  3303. case 5: // Vector3
  3304. case 7:
  3305. destination[property] = sourceProperty.clone();
  3306. break;
  3307. }
  3308. }
  3309. }
  3310. return destination;
  3311. };
  3312. return SerializationHelper;
  3313. }());
  3314. BABYLON.SerializationHelper = SerializationHelper;
  3315. })(BABYLON || (BABYLON = {}));
  3316. var BABYLON;
  3317. (function (BABYLON) {
  3318. /**
  3319. * A class serves as a medium between the observable and its observers
  3320. */
  3321. var EventState = (function () {
  3322. /**
  3323. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3324. */
  3325. function EventState(mask, skipNextObservers) {
  3326. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3327. this.initalize(mask, skipNextObservers);
  3328. }
  3329. EventState.prototype.initalize = function (mask, skipNextObservers) {
  3330. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3331. this.mask = mask;
  3332. this.skipNextObservers = skipNextObservers;
  3333. return this;
  3334. };
  3335. return EventState;
  3336. }());
  3337. BABYLON.EventState = EventState;
  3338. /**
  3339. * Represent an Observer registered to a given Observable object.
  3340. */
  3341. var Observer = (function () {
  3342. function Observer(callback, mask) {
  3343. this.callback = callback;
  3344. this.mask = mask;
  3345. }
  3346. return Observer;
  3347. }());
  3348. BABYLON.Observer = Observer;
  3349. /**
  3350. * The Observable class is a simple implementation of the Observable pattern.
  3351. * 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.
  3352. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3353. * 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).
  3354. * 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.
  3355. */
  3356. var Observable = (function () {
  3357. function Observable() {
  3358. this._observers = new Array();
  3359. }
  3360. /**
  3361. * Create a new Observer with the specified callback
  3362. * @param callback the callback that will be executed for that Observer
  3363. * @param mask the mask used to filter observers
  3364. * @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.
  3365. */
  3366. Observable.prototype.add = function (callback, mask, insertFirst) {
  3367. if (mask === void 0) { mask = -1; }
  3368. if (insertFirst === void 0) { insertFirst = false; }
  3369. if (!callback) {
  3370. return null;
  3371. }
  3372. var observer = new Observer(callback, mask);
  3373. if (insertFirst) {
  3374. this._observers.unshift(observer);
  3375. }
  3376. else {
  3377. this._observers.push(observer);
  3378. }
  3379. return observer;
  3380. };
  3381. /**
  3382. * Remove an Observer from the Observable object
  3383. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3384. */
  3385. Observable.prototype.remove = function (observer) {
  3386. var index = this._observers.indexOf(observer);
  3387. if (index !== -1) {
  3388. this._observers.splice(index, 1);
  3389. return true;
  3390. }
  3391. return false;
  3392. };
  3393. /**
  3394. * Remove a callback from the Observable object
  3395. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3396. */
  3397. Observable.prototype.removeCallback = function (callback) {
  3398. for (var index = 0; index < this._observers.length; index++) {
  3399. if (this._observers[index].callback === callback) {
  3400. this._observers.splice(index, 1);
  3401. return true;
  3402. }
  3403. }
  3404. return false;
  3405. };
  3406. /**
  3407. * Notify all Observers by calling their respective callback with the given data
  3408. * @param eventData
  3409. * @param mask
  3410. */
  3411. Observable.prototype.notifyObservers = function (eventData, mask) {
  3412. if (mask === void 0) { mask = -1; }
  3413. var state = Observable._pooledEventState ? Observable._pooledEventState.initalize(mask) : new EventState(mask);
  3414. Observable._pooledEventState = null;
  3415. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3416. var obs = _a[_i];
  3417. if (obs.mask & mask) {
  3418. obs.callback(eventData, state);
  3419. }
  3420. if (state.skipNextObservers) {
  3421. break;
  3422. }
  3423. }
  3424. Observable._pooledEventState = state;
  3425. };
  3426. /**
  3427. * return true is the Observable has at least one Observer registered
  3428. */
  3429. Observable.prototype.hasObservers = function () {
  3430. return this._observers.length > 0;
  3431. };
  3432. /**
  3433. * Clear the list of observers
  3434. */
  3435. Observable.prototype.clear = function () {
  3436. this._observers = new Array();
  3437. };
  3438. /**
  3439. * Clone the current observable
  3440. */
  3441. Observable.prototype.clone = function () {
  3442. var result = new Observable();
  3443. result._observers = this._observers.slice(0);
  3444. return result;
  3445. };
  3446. Observable._pooledEventState = null;
  3447. return Observable;
  3448. }());
  3449. BABYLON.Observable = Observable;
  3450. })(BABYLON || (BABYLON = {}));
  3451. var BABYLON;
  3452. (function (BABYLON) {
  3453. var Database = (function () {
  3454. function Database(urlToScene, callbackManifestChecked) {
  3455. // Handling various flavors of prefixed version of IndexedDB
  3456. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3457. this.callbackManifestChecked = callbackManifestChecked;
  3458. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3459. this.db = null;
  3460. this.enableSceneOffline = false;
  3461. this.enableTexturesOffline = false;
  3462. this.manifestVersionFound = 0;
  3463. this.mustUpdateRessources = false;
  3464. this.hasReachedQuota = false;
  3465. if (!Database.IDBStorageEnabled) {
  3466. this.callbackManifestChecked(true);
  3467. }
  3468. else {
  3469. this.checkManifestFile();
  3470. }
  3471. }
  3472. Database.prototype.checkManifestFile = function () {
  3473. var _this = this;
  3474. function noManifestFile() {
  3475. that.enableSceneOffline = false;
  3476. that.enableTexturesOffline = false;
  3477. that.callbackManifestChecked(false);
  3478. }
  3479. var that = this;
  3480. var timeStampUsed = false;
  3481. var manifestURL = this.currentSceneUrl + ".manifest";
  3482. var xhr = new XMLHttpRequest();
  3483. if (navigator.onLine) {
  3484. // Adding a timestamp to by-pass browsers' cache
  3485. timeStampUsed = true;
  3486. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3487. }
  3488. xhr.open("GET", manifestURL, true);
  3489. xhr.addEventListener("load", function () {
  3490. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3491. try {
  3492. var manifestFile = JSON.parse(xhr.response);
  3493. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3494. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3495. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3496. _this.manifestVersionFound = manifestFile.version;
  3497. }
  3498. if (_this.callbackManifestChecked) {
  3499. _this.callbackManifestChecked(true);
  3500. }
  3501. }
  3502. catch (ex) {
  3503. noManifestFile();
  3504. }
  3505. }
  3506. else {
  3507. noManifestFile();
  3508. }
  3509. }, false);
  3510. xhr.addEventListener("error", function (event) {
  3511. if (timeStampUsed) {
  3512. timeStampUsed = false;
  3513. // Let's retry without the timeStamp
  3514. // It could fail when coupled with HTML5 Offline API
  3515. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3516. xhr.open("GET", retryManifestURL, true);
  3517. xhr.send();
  3518. }
  3519. else {
  3520. noManifestFile();
  3521. }
  3522. }, false);
  3523. try {
  3524. xhr.send();
  3525. }
  3526. catch (ex) {
  3527. BABYLON.Tools.Error("Error on XHR send request.");
  3528. that.callbackManifestChecked(false);
  3529. }
  3530. };
  3531. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3532. var _this = this;
  3533. function handleError() {
  3534. that.isSupported = false;
  3535. if (errorCallback)
  3536. errorCallback();
  3537. }
  3538. var that = this;
  3539. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3540. // Your browser doesn't support IndexedDB
  3541. this.isSupported = false;
  3542. if (errorCallback)
  3543. errorCallback();
  3544. }
  3545. else {
  3546. // If the DB hasn't been opened or created yet
  3547. if (!this.db) {
  3548. this.hasReachedQuota = false;
  3549. this.isSupported = true;
  3550. var request = this.idbFactory.open("babylonjs", 1);
  3551. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3552. request.onerror = function (event) {
  3553. handleError();
  3554. };
  3555. // executes when a version change transaction cannot complete due to other active transactions
  3556. request.onblocked = function (event) {
  3557. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3558. handleError();
  3559. };
  3560. // DB has been opened successfully
  3561. request.onsuccess = function (event) {
  3562. _this.db = request.result;
  3563. successCallback();
  3564. };
  3565. // Initialization of the DB. Creating Scenes & Textures stores
  3566. request.onupgradeneeded = function (event) {
  3567. _this.db = (event.target).result;
  3568. try {
  3569. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3570. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3571. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3572. }
  3573. catch (ex) {
  3574. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3575. handleError();
  3576. }
  3577. };
  3578. }
  3579. else {
  3580. if (successCallback)
  3581. successCallback();
  3582. }
  3583. }
  3584. };
  3585. Database.prototype.loadImageFromDB = function (url, image) {
  3586. var _this = this;
  3587. var completeURL = Database.ReturnFullUrlLocation(url);
  3588. var saveAndLoadImage = function () {
  3589. if (!_this.hasReachedQuota && _this.db !== null) {
  3590. // the texture is not yet in the DB, let's try to save it
  3591. _this._saveImageIntoDBAsync(completeURL, image);
  3592. }
  3593. else {
  3594. image.src = url;
  3595. }
  3596. };
  3597. if (!this.mustUpdateRessources) {
  3598. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3599. }
  3600. else {
  3601. saveAndLoadImage();
  3602. }
  3603. };
  3604. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3605. if (this.isSupported && this.db !== null) {
  3606. var texture;
  3607. var transaction = this.db.transaction(["textures"]);
  3608. transaction.onabort = function (event) {
  3609. image.src = url;
  3610. };
  3611. transaction.oncomplete = function (event) {
  3612. var blobTextureURL;
  3613. if (texture) {
  3614. var URL = window.URL || window.webkitURL;
  3615. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3616. image.onerror = function () {
  3617. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3618. image.src = url;
  3619. };
  3620. image.src = blobTextureURL;
  3621. }
  3622. else {
  3623. notInDBCallback();
  3624. }
  3625. };
  3626. var getRequest = transaction.objectStore("textures").get(url);
  3627. getRequest.onsuccess = function (event) {
  3628. texture = (event.target).result;
  3629. };
  3630. getRequest.onerror = function (event) {
  3631. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3632. image.src = url;
  3633. };
  3634. }
  3635. else {
  3636. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3637. image.src = url;
  3638. }
  3639. };
  3640. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3641. var _this = this;
  3642. if (this.isSupported) {
  3643. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3644. var generateBlobUrl = function () {
  3645. var blobTextureURL;
  3646. if (blob) {
  3647. var URL = window.URL || window.webkitURL;
  3648. try {
  3649. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3650. }
  3651. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3652. catch (ex) {
  3653. blobTextureURL = URL.createObjectURL(blob);
  3654. }
  3655. }
  3656. image.src = blobTextureURL;
  3657. };
  3658. if (Database.IsUASupportingBlobStorage) {
  3659. var xhr = new XMLHttpRequest(), blob;
  3660. xhr.open("GET", url, true);
  3661. xhr.responseType = "blob";
  3662. xhr.addEventListener("load", function () {
  3663. if (xhr.status === 200) {
  3664. // Blob as response (XHR2)
  3665. blob = xhr.response;
  3666. var transaction = _this.db.transaction(["textures"], "readwrite");
  3667. // the transaction could abort because of a QuotaExceededError error
  3668. transaction.onabort = function (event) {
  3669. try {
  3670. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3671. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3672. this.hasReachedQuota = true;
  3673. }
  3674. }
  3675. catch (ex) { }
  3676. generateBlobUrl();
  3677. };
  3678. transaction.oncomplete = function (event) {
  3679. generateBlobUrl();
  3680. };
  3681. var newTexture = { textureUrl: url, data: blob };
  3682. try {
  3683. // Put the blob into the dabase
  3684. var addRequest = transaction.objectStore("textures").put(newTexture);
  3685. addRequest.onsuccess = function (event) {
  3686. };
  3687. addRequest.onerror = function (event) {
  3688. generateBlobUrl();
  3689. };
  3690. }
  3691. catch (ex) {
  3692. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3693. if (ex.code === 25) {
  3694. Database.IsUASupportingBlobStorage = false;
  3695. }
  3696. image.src = url;
  3697. }
  3698. }
  3699. else {
  3700. image.src = url;
  3701. }
  3702. }, false);
  3703. xhr.addEventListener("error", function (event) {
  3704. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3705. image.src = url;
  3706. }, false);
  3707. xhr.send();
  3708. }
  3709. else {
  3710. image.src = url;
  3711. }
  3712. }
  3713. else {
  3714. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3715. image.src = url;
  3716. }
  3717. };
  3718. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3719. var _this = this;
  3720. var updateVersion = function (event) {
  3721. // the version is not yet in the DB or we need to update it
  3722. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3723. };
  3724. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3725. };
  3726. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3727. var _this = this;
  3728. if (this.isSupported) {
  3729. var version;
  3730. try {
  3731. var transaction = this.db.transaction(["versions"]);
  3732. transaction.oncomplete = function (event) {
  3733. if (version) {
  3734. // If the version in the JSON file is > than the version in DB
  3735. if (_this.manifestVersionFound > version.data) {
  3736. _this.mustUpdateRessources = true;
  3737. updateInDBCallback();
  3738. }
  3739. else {
  3740. callback(version.data);
  3741. }
  3742. }
  3743. else {
  3744. _this.mustUpdateRessources = true;
  3745. updateInDBCallback();
  3746. }
  3747. };
  3748. transaction.onabort = function (event) {
  3749. callback(-1);
  3750. };
  3751. var getRequest = transaction.objectStore("versions").get(url);
  3752. getRequest.onsuccess = function (event) {
  3753. version = (event.target).result;
  3754. };
  3755. getRequest.onerror = function (event) {
  3756. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3757. callback(-1);
  3758. };
  3759. }
  3760. catch (ex) {
  3761. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3762. callback(-1);
  3763. }
  3764. }
  3765. else {
  3766. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3767. callback(-1);
  3768. }
  3769. };
  3770. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3771. var _this = this;
  3772. if (this.isSupported && !this.hasReachedQuota) {
  3773. try {
  3774. // Open a transaction to the database
  3775. var transaction = this.db.transaction(["versions"], "readwrite");
  3776. // the transaction could abort because of a QuotaExceededError error
  3777. transaction.onabort = function (event) {
  3778. try {
  3779. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3780. _this.hasReachedQuota = true;
  3781. }
  3782. }
  3783. catch (ex) { }
  3784. callback(-1);
  3785. };
  3786. transaction.oncomplete = function (event) {
  3787. callback(_this.manifestVersionFound);
  3788. };
  3789. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3790. // Put the scene into the database
  3791. var addRequest = transaction.objectStore("versions").put(newVersion);
  3792. addRequest.onsuccess = function (event) {
  3793. };
  3794. addRequest.onerror = function (event) {
  3795. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3796. };
  3797. }
  3798. catch (ex) {
  3799. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3800. callback(-1);
  3801. }
  3802. }
  3803. else {
  3804. callback(-1);
  3805. }
  3806. };
  3807. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3808. var _this = this;
  3809. var completeUrl = Database.ReturnFullUrlLocation(url);
  3810. var saveAndLoadFile = function (event) {
  3811. // the scene is not yet in the DB, let's try to save it
  3812. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3813. };
  3814. this._checkVersionFromDB(completeUrl, function (version) {
  3815. if (version !== -1) {
  3816. if (!_this.mustUpdateRessources) {
  3817. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3818. }
  3819. else {
  3820. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3821. }
  3822. }
  3823. else {
  3824. errorCallback();
  3825. }
  3826. });
  3827. };
  3828. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3829. if (this.isSupported) {
  3830. var targetStore;
  3831. if (url.indexOf(".babylon") !== -1) {
  3832. targetStore = "scenes";
  3833. }
  3834. else {
  3835. targetStore = "textures";
  3836. }
  3837. var file;
  3838. var transaction = this.db.transaction([targetStore]);
  3839. transaction.oncomplete = function (event) {
  3840. if (file) {
  3841. callback(file.data);
  3842. }
  3843. else {
  3844. notInDBCallback();
  3845. }
  3846. };
  3847. transaction.onabort = function (event) {
  3848. notInDBCallback();
  3849. };
  3850. var getRequest = transaction.objectStore(targetStore).get(url);
  3851. getRequest.onsuccess = function (event) {
  3852. file = (event.target).result;
  3853. };
  3854. getRequest.onerror = function (event) {
  3855. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3856. notInDBCallback();
  3857. };
  3858. }
  3859. else {
  3860. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3861. callback();
  3862. }
  3863. };
  3864. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3865. var _this = this;
  3866. if (this.isSupported) {
  3867. var targetStore;
  3868. if (url.indexOf(".babylon") !== -1) {
  3869. targetStore = "scenes";
  3870. }
  3871. else {
  3872. targetStore = "textures";
  3873. }
  3874. // Create XHR
  3875. var xhr = new XMLHttpRequest(), fileData;
  3876. xhr.open("GET", url, true);
  3877. if (useArrayBuffer) {
  3878. xhr.responseType = "arraybuffer";
  3879. }
  3880. xhr.onprogress = progressCallback;
  3881. xhr.addEventListener("load", function () {
  3882. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3883. // Blob as response (XHR2)
  3884. //fileData = xhr.responseText;
  3885. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3886. if (!_this.hasReachedQuota) {
  3887. // Open a transaction to the database
  3888. var transaction = _this.db.transaction([targetStore], "readwrite");
  3889. // the transaction could abort because of a QuotaExceededError error
  3890. transaction.onabort = function (event) {
  3891. try {
  3892. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3893. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3894. this.hasReachedQuota = true;
  3895. }
  3896. }
  3897. catch (ex) { }
  3898. callback(fileData);
  3899. };
  3900. transaction.oncomplete = function (event) {
  3901. callback(fileData);
  3902. };
  3903. var newFile;
  3904. if (targetStore === "scenes") {
  3905. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3906. }
  3907. else {
  3908. newFile = { textureUrl: url, data: fileData };
  3909. }
  3910. try {
  3911. // Put the scene into the database
  3912. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3913. addRequest.onsuccess = function (event) {
  3914. };
  3915. addRequest.onerror = function (event) {
  3916. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3917. };
  3918. }
  3919. catch (ex) {
  3920. callback(fileData);
  3921. }
  3922. }
  3923. else {
  3924. callback(fileData);
  3925. }
  3926. }
  3927. else {
  3928. callback();
  3929. }
  3930. }, false);
  3931. xhr.addEventListener("error", function (event) {
  3932. BABYLON.Tools.Error("error on XHR request.");
  3933. callback();
  3934. }, false);
  3935. xhr.send();
  3936. }
  3937. else {
  3938. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3939. callback();
  3940. }
  3941. };
  3942. Database.IsUASupportingBlobStorage = true;
  3943. Database.IDBStorageEnabled = true;
  3944. Database.parseURL = function (url) {
  3945. var a = document.createElement('a');
  3946. a.href = url;
  3947. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3948. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3949. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3950. return absLocation;
  3951. };
  3952. Database.ReturnFullUrlLocation = function (url) {
  3953. if (url.indexOf("http:/") === -1) {
  3954. return (Database.parseURL(window.location.href) + url);
  3955. }
  3956. else {
  3957. return url;
  3958. }
  3959. };
  3960. return Database;
  3961. }());
  3962. BABYLON.Database = Database;
  3963. })(BABYLON || (BABYLON = {}));
  3964. var BABYLON;
  3965. (function (BABYLON) {
  3966. var Internals;
  3967. (function (Internals) {
  3968. /*
  3969. * Based on jsTGALoader - Javascript loader for TGA file
  3970. * By Vincent Thibault
  3971. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3972. */
  3973. var TGATools = (function () {
  3974. function TGATools() {
  3975. }
  3976. TGATools.GetTGAHeader = function (data) {
  3977. var offset = 0;
  3978. var header = {
  3979. id_length: data[offset++],
  3980. colormap_type: data[offset++],
  3981. image_type: data[offset++],
  3982. colormap_index: data[offset++] | data[offset++] << 8,
  3983. colormap_length: data[offset++] | data[offset++] << 8,
  3984. colormap_size: data[offset++],
  3985. origin: [
  3986. data[offset++] | data[offset++] << 8,
  3987. data[offset++] | data[offset++] << 8
  3988. ],
  3989. width: data[offset++] | data[offset++] << 8,
  3990. height: data[offset++] | data[offset++] << 8,
  3991. pixel_size: data[offset++],
  3992. flags: data[offset++]
  3993. };
  3994. return header;
  3995. };
  3996. TGATools.UploadContent = function (gl, data) {
  3997. // Not enough data to contain header ?
  3998. if (data.length < 19) {
  3999. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  4000. return;
  4001. }
  4002. // Read Header
  4003. var offset = 18;
  4004. var header = TGATools.GetTGAHeader(data);
  4005. // Assume it's a valid Targa file.
  4006. if (header.id_length + offset > data.length) {
  4007. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  4008. return;
  4009. }
  4010. // Skip not needed data
  4011. offset += header.id_length;
  4012. var use_rle = false;
  4013. var use_pal = false;
  4014. var use_rgb = false;
  4015. var use_grey = false;
  4016. // Get some informations.
  4017. switch (header.image_type) {
  4018. case TGATools._TYPE_RLE_INDEXED:
  4019. use_rle = true;
  4020. case TGATools._TYPE_INDEXED:
  4021. use_pal = true;
  4022. break;
  4023. case TGATools._TYPE_RLE_RGB:
  4024. use_rle = true;
  4025. case TGATools._TYPE_RGB:
  4026. use_rgb = true;
  4027. break;
  4028. case TGATools._TYPE_RLE_GREY:
  4029. use_rle = true;
  4030. case TGATools._TYPE_GREY:
  4031. use_grey = true;
  4032. break;
  4033. }
  4034. var pixel_data;
  4035. var numAlphaBits = header.flags & 0xf;
  4036. var pixel_size = header.pixel_size >> 3;
  4037. var pixel_total = header.width * header.height * pixel_size;
  4038. // Read palettes
  4039. var palettes;
  4040. if (use_pal) {
  4041. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4042. }
  4043. // Read LRE
  4044. if (use_rle) {
  4045. pixel_data = new Uint8Array(pixel_total);
  4046. var c, count, i;
  4047. var localOffset = 0;
  4048. var pixels = new Uint8Array(pixel_size);
  4049. while (offset < pixel_total && localOffset < pixel_total) {
  4050. c = data[offset++];
  4051. count = (c & 0x7f) + 1;
  4052. // RLE pixels
  4053. if (c & 0x80) {
  4054. // Bind pixel tmp array
  4055. for (i = 0; i < pixel_size; ++i) {
  4056. pixels[i] = data[offset++];
  4057. }
  4058. // Copy pixel array
  4059. for (i = 0; i < count; ++i) {
  4060. pixel_data.set(pixels, localOffset + i * pixel_size);
  4061. }
  4062. localOffset += pixel_size * count;
  4063. }
  4064. else {
  4065. count *= pixel_size;
  4066. for (i = 0; i < count; ++i) {
  4067. pixel_data[localOffset + i] = data[offset++];
  4068. }
  4069. localOffset += count;
  4070. }
  4071. }
  4072. }
  4073. else {
  4074. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4075. }
  4076. // Load to texture
  4077. var x_start, y_start, x_step, y_step, y_end, x_end;
  4078. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4079. default:
  4080. case TGATools._ORIGIN_UL:
  4081. x_start = 0;
  4082. x_step = 1;
  4083. x_end = header.width;
  4084. y_start = 0;
  4085. y_step = 1;
  4086. y_end = header.height;
  4087. break;
  4088. case TGATools._ORIGIN_BL:
  4089. x_start = 0;
  4090. x_step = 1;
  4091. x_end = header.width;
  4092. y_start = header.height - 1;
  4093. y_step = -1;
  4094. y_end = -1;
  4095. break;
  4096. case TGATools._ORIGIN_UR:
  4097. x_start = header.width - 1;
  4098. x_step = -1;
  4099. x_end = -1;
  4100. y_start = 0;
  4101. y_step = 1;
  4102. y_end = header.height;
  4103. break;
  4104. case TGATools._ORIGIN_BR:
  4105. x_start = header.width - 1;
  4106. x_step = -1;
  4107. x_end = -1;
  4108. y_start = header.height - 1;
  4109. y_step = -1;
  4110. y_end = -1;
  4111. break;
  4112. }
  4113. // Load the specify method
  4114. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4115. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4116. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4117. };
  4118. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4119. var image = pixel_data, colormap = palettes;
  4120. var width = header.width, height = header.height;
  4121. var color, i = 0, x, y;
  4122. var imageData = new Uint8Array(width * height * 4);
  4123. for (y = y_start; y !== y_end; y += y_step) {
  4124. for (x = x_start; x !== x_end; x += x_step, i++) {
  4125. color = image[i];
  4126. imageData[(x + width * y) * 4 + 3] = 255;
  4127. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4128. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4129. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4130. }
  4131. }
  4132. return imageData;
  4133. };
  4134. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4135. var image = pixel_data;
  4136. var width = header.width, height = header.height;
  4137. var color, i = 0, x, y;
  4138. var imageData = new Uint8Array(width * height * 4);
  4139. for (y = y_start; y !== y_end; y += y_step) {
  4140. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4141. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4142. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4143. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4144. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4145. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4146. }
  4147. }
  4148. return imageData;
  4149. };
  4150. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4151. var image = pixel_data;
  4152. var width = header.width, height = header.height;
  4153. var i = 0, x, y;
  4154. var imageData = new Uint8Array(width * height * 4);
  4155. for (y = y_start; y !== y_end; y += y_step) {
  4156. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4157. imageData[(x + width * y) * 4 + 3] = 255;
  4158. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4159. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4160. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4161. }
  4162. }
  4163. return imageData;
  4164. };
  4165. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4166. var image = pixel_data;
  4167. var width = header.width, height = header.height;
  4168. var i = 0, x, y;
  4169. var imageData = new Uint8Array(width * height * 4);
  4170. for (y = y_start; y !== y_end; y += y_step) {
  4171. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4172. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4173. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4174. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4175. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4176. }
  4177. }
  4178. return imageData;
  4179. };
  4180. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4181. var image = pixel_data;
  4182. var width = header.width, height = header.height;
  4183. var color, i = 0, x, y;
  4184. var imageData = new Uint8Array(width * height * 4);
  4185. for (y = y_start; y !== y_end; y += y_step) {
  4186. for (x = x_start; x !== x_end; x += x_step, i++) {
  4187. color = image[i];
  4188. imageData[(x + width * y) * 4 + 0] = color;
  4189. imageData[(x + width * y) * 4 + 1] = color;
  4190. imageData[(x + width * y) * 4 + 2] = color;
  4191. imageData[(x + width * y) * 4 + 3] = 255;
  4192. }
  4193. }
  4194. return imageData;
  4195. };
  4196. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4197. var image = pixel_data;
  4198. var width = header.width, height = header.height;
  4199. var i = 0, x, y;
  4200. var imageData = new Uint8Array(width * height * 4);
  4201. for (y = y_start; y !== y_end; y += y_step) {
  4202. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4203. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4204. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4205. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4206. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4207. }
  4208. }
  4209. return imageData;
  4210. };
  4211. TGATools._TYPE_NO_DATA = 0;
  4212. TGATools._TYPE_INDEXED = 1;
  4213. TGATools._TYPE_RGB = 2;
  4214. TGATools._TYPE_GREY = 3;
  4215. TGATools._TYPE_RLE_INDEXED = 9;
  4216. TGATools._TYPE_RLE_RGB = 10;
  4217. TGATools._TYPE_RLE_GREY = 11;
  4218. TGATools._ORIGIN_MASK = 0x30;
  4219. TGATools._ORIGIN_SHIFT = 0x04;
  4220. TGATools._ORIGIN_BL = 0x00;
  4221. TGATools._ORIGIN_BR = 0x01;
  4222. TGATools._ORIGIN_UL = 0x02;
  4223. TGATools._ORIGIN_UR = 0x03;
  4224. return TGATools;
  4225. }());
  4226. Internals.TGATools = TGATools;
  4227. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4228. })(BABYLON || (BABYLON = {}));
  4229. var BABYLON;
  4230. (function (BABYLON) {
  4231. var SmartArray = (function () {
  4232. function SmartArray(capacity) {
  4233. this.length = 0;
  4234. this._duplicateId = 0;
  4235. this.data = new Array(capacity);
  4236. this._id = SmartArray._GlobalId++;
  4237. }
  4238. SmartArray.prototype.push = function (value) {
  4239. this.data[this.length++] = value;
  4240. if (this.length > this.data.length) {
  4241. this.data.length *= 2;
  4242. }
  4243. if (!value.__smartArrayFlags) {
  4244. value.__smartArrayFlags = {};
  4245. }
  4246. value.__smartArrayFlags[this._id] = this._duplicateId;
  4247. };
  4248. SmartArray.prototype.pushNoDuplicate = function (value) {
  4249. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4250. return false;
  4251. }
  4252. this.push(value);
  4253. return true;
  4254. };
  4255. SmartArray.prototype.sort = function (compareFn) {
  4256. this.data.sort(compareFn);
  4257. };
  4258. SmartArray.prototype.reset = function () {
  4259. this.length = 0;
  4260. this._duplicateId++;
  4261. };
  4262. SmartArray.prototype.concat = function (array) {
  4263. if (array.length === 0) {
  4264. return;
  4265. }
  4266. if (this.length + array.length > this.data.length) {
  4267. this.data.length = (this.length + array.length) * 2;
  4268. }
  4269. for (var index = 0; index < array.length; index++) {
  4270. this.data[this.length++] = (array.data || array)[index];
  4271. }
  4272. };
  4273. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4274. if (array.length === 0) {
  4275. return;
  4276. }
  4277. if (this.length + array.length > this.data.length) {
  4278. this.data.length = (this.length + array.length) * 2;
  4279. }
  4280. for (var index = 0; index < array.length; index++) {
  4281. var item = (array.data || array)[index];
  4282. this.pushNoDuplicate(item);
  4283. }
  4284. };
  4285. SmartArray.prototype.indexOf = function (value) {
  4286. var position = this.data.indexOf(value);
  4287. if (position >= this.length) {
  4288. return -1;
  4289. }
  4290. return position;
  4291. };
  4292. // Statics
  4293. SmartArray._GlobalId = 0;
  4294. return SmartArray;
  4295. }());
  4296. BABYLON.SmartArray = SmartArray;
  4297. })(BABYLON || (BABYLON = {}));
  4298. var BABYLON;
  4299. (function (BABYLON) {
  4300. /**
  4301. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4302. * The underlying implementation relies on an associative array to ensure the best performances.
  4303. * The value can be anything including 'null' but except 'undefined'
  4304. */
  4305. var StringDictionary = (function () {
  4306. function StringDictionary() {
  4307. this._count = 0;
  4308. this._data = {};
  4309. }
  4310. /**
  4311. * Get a value based from its key
  4312. * @param key the given key to get the matching value from
  4313. * @return the value if found, otherwise undefined is returned
  4314. */
  4315. StringDictionary.prototype.get = function (key) {
  4316. var val = this._data[key];
  4317. if (val !== undefined) {
  4318. return val;
  4319. }
  4320. return undefined;
  4321. };
  4322. /**
  4323. * Get a value from its key or add it if it doesn't exist.
  4324. * This method will ensure you that a given key/data will be present in the dictionary.
  4325. * @param key the given key to get the matching value from
  4326. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4327. * The factory will only be invoked if there's no data for the given key.
  4328. * @return the value corresponding to the key.
  4329. */
  4330. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4331. var val = this.get(key);
  4332. if (val !== undefined) {
  4333. return val;
  4334. }
  4335. val = factory(key);
  4336. if (val) {
  4337. this.add(key, val);
  4338. }
  4339. return val;
  4340. };
  4341. /**
  4342. * Get a value from its key if present in the dictionary otherwise add it
  4343. * @param key the key to get the value from
  4344. * @param val if there's no such key/value pair in the dictionary add it with this value
  4345. * @return the value corresponding to the key
  4346. */
  4347. StringDictionary.prototype.getOrAdd = function (key, val) {
  4348. var curVal = this.get(key);
  4349. if (curVal !== undefined) {
  4350. return curVal;
  4351. }
  4352. this.add(key, val);
  4353. return val;
  4354. };
  4355. /**
  4356. * Check if there's a given key in the dictionary
  4357. * @param key the key to check for
  4358. * @return true if the key is present, false otherwise
  4359. */
  4360. StringDictionary.prototype.contains = function (key) {
  4361. return this._data[key] !== undefined;
  4362. };
  4363. /**
  4364. * Add a new key and its corresponding value
  4365. * @param key the key to add
  4366. * @param value the value corresponding to the key
  4367. * @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
  4368. */
  4369. StringDictionary.prototype.add = function (key, value) {
  4370. if (this._data[key] !== undefined) {
  4371. return false;
  4372. }
  4373. this._data[key] = value;
  4374. ++this._count;
  4375. return true;
  4376. };
  4377. StringDictionary.prototype.set = function (key, value) {
  4378. if (this._data[key] === undefined) {
  4379. return false;
  4380. }
  4381. this._data[key] = value;
  4382. return true;
  4383. };
  4384. /**
  4385. * Remove a key/value from the dictionary.
  4386. * @param key the key to remove
  4387. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4388. */
  4389. StringDictionary.prototype.remove = function (key) {
  4390. if (this.contains(key)) {
  4391. delete this._data[key];
  4392. --this._count;
  4393. return true;
  4394. }
  4395. return false;
  4396. };
  4397. /**
  4398. * Clear the whole content of the dictionary
  4399. */
  4400. StringDictionary.prototype.clear = function () {
  4401. this._data = {};
  4402. this._count = 0;
  4403. };
  4404. Object.defineProperty(StringDictionary.prototype, "count", {
  4405. get: function () {
  4406. return this._count;
  4407. },
  4408. enumerable: true,
  4409. configurable: true
  4410. });
  4411. /**
  4412. * Execute a callback on each key/val of the dictionary.
  4413. * Note that you can remove any element in this dictionary in the callback implementation
  4414. * @param callback the callback to execute on a given key/value pair
  4415. */
  4416. StringDictionary.prototype.forEach = function (callback) {
  4417. for (var cur in this._data) {
  4418. var val = this._data[cur];
  4419. callback(cur, val);
  4420. }
  4421. };
  4422. /**
  4423. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4424. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4425. * Note that you can remove any element in this dictionary in the callback implementation
  4426. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4427. */
  4428. StringDictionary.prototype.first = function (callback) {
  4429. for (var cur in this._data) {
  4430. var val = this._data[cur];
  4431. var res = callback(cur, val);
  4432. if (res) {
  4433. return res;
  4434. }
  4435. }
  4436. return null;
  4437. };
  4438. return StringDictionary;
  4439. }());
  4440. BABYLON.StringDictionary = StringDictionary;
  4441. })(BABYLON || (BABYLON = {}));
  4442. var BABYLON;
  4443. (function (BABYLON) {
  4444. // Screenshots
  4445. var screenshotCanvas;
  4446. var cloneValue = function (source, destinationObject) {
  4447. if (!source)
  4448. return null;
  4449. if (source instanceof BABYLON.Mesh) {
  4450. return null;
  4451. }
  4452. if (source instanceof BABYLON.SubMesh) {
  4453. return source.clone(destinationObject);
  4454. }
  4455. else if (source.clone) {
  4456. return source.clone();
  4457. }
  4458. return null;
  4459. };
  4460. var Tools = (function () {
  4461. function Tools() {
  4462. }
  4463. Tools.Instantiate = function (className) {
  4464. var arr = className.split(".");
  4465. var fn = (window || this);
  4466. for (var i = 0, len = arr.length; i < len; i++) {
  4467. fn = fn[arr[i]];
  4468. }
  4469. if (typeof fn !== "function") {
  4470. return null;
  4471. }
  4472. return fn;
  4473. };
  4474. Tools.SetImmediate = function (action) {
  4475. if (window.setImmediate) {
  4476. window.setImmediate(action);
  4477. }
  4478. else {
  4479. setTimeout(action, 1);
  4480. }
  4481. };
  4482. Tools.IsExponentOfTwo = function (value) {
  4483. var count = 1;
  4484. do {
  4485. count *= 2;
  4486. } while (count < value);
  4487. return count === value;
  4488. };
  4489. Tools.GetExponentOfTwo = function (value, max) {
  4490. var count = 1;
  4491. do {
  4492. count *= 2;
  4493. } while (count < value);
  4494. if (count > max)
  4495. count = max;
  4496. return count;
  4497. };
  4498. Tools.GetFilename = function (path) {
  4499. var index = path.lastIndexOf("/");
  4500. if (index < 0)
  4501. return path;
  4502. return path.substring(index + 1);
  4503. };
  4504. Tools.GetDOMTextContent = function (element) {
  4505. var result = "";
  4506. var child = element.firstChild;
  4507. while (child) {
  4508. if (child.nodeType === 3) {
  4509. result += child.textContent;
  4510. }
  4511. child = child.nextSibling;
  4512. }
  4513. return result;
  4514. };
  4515. Tools.ToDegrees = function (angle) {
  4516. return angle * 180 / Math.PI;
  4517. };
  4518. Tools.ToRadians = function (angle) {
  4519. return angle * Math.PI / 180;
  4520. };
  4521. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4522. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4523. var output = "";
  4524. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4525. var i = 0;
  4526. var bytes = new Uint8Array(buffer);
  4527. while (i < bytes.length) {
  4528. chr1 = bytes[i++];
  4529. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4530. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4531. enc1 = chr1 >> 2;
  4532. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4533. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4534. enc4 = chr3 & 63;
  4535. if (isNaN(chr2)) {
  4536. enc3 = enc4 = 64;
  4537. }
  4538. else if (isNaN(chr3)) {
  4539. enc4 = 64;
  4540. }
  4541. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4542. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4543. }
  4544. return "data:image/png;base64," + output;
  4545. };
  4546. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4547. if (bias === void 0) { bias = null; }
  4548. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4549. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4550. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4551. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4552. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4553. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4554. }
  4555. if (bias) {
  4556. minimum.x -= minimum.x * bias.x + bias.y;
  4557. minimum.y -= minimum.y * bias.x + bias.y;
  4558. minimum.z -= minimum.z * bias.x + bias.y;
  4559. maximum.x += maximum.x * bias.x + bias.y;
  4560. maximum.y += maximum.y * bias.x + bias.y;
  4561. maximum.z += maximum.z * bias.x + bias.y;
  4562. }
  4563. return {
  4564. minimum: minimum,
  4565. maximum: maximum
  4566. };
  4567. };
  4568. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4569. if (bias === void 0) { bias = null; }
  4570. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4571. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4572. if (!stride) {
  4573. stride = 3;
  4574. }
  4575. for (var index = start; index < start + count; index++) {
  4576. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4577. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4578. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4579. }
  4580. if (bias) {
  4581. minimum.x -= minimum.x * bias.x + bias.y;
  4582. minimum.y -= minimum.y * bias.x + bias.y;
  4583. minimum.z -= minimum.z * bias.x + bias.y;
  4584. maximum.x += maximum.x * bias.x + bias.y;
  4585. maximum.y += maximum.y * bias.x + bias.y;
  4586. maximum.z += maximum.z * bias.x + bias.y;
  4587. }
  4588. return {
  4589. minimum: minimum,
  4590. maximum: maximum
  4591. };
  4592. };
  4593. Tools.Vector2ArrayFeeder = function (array) {
  4594. return function (index) {
  4595. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4596. var length = isFloatArray ? array.length / 2 : array.length;
  4597. if (index >= length) {
  4598. return null;
  4599. }
  4600. if (isFloatArray) {
  4601. var fa = array;
  4602. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4603. }
  4604. var a = array;
  4605. return a[index];
  4606. };
  4607. };
  4608. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4609. if (bias === void 0) { bias = null; }
  4610. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4611. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4612. var i = 0;
  4613. var cur = feeder(i++);
  4614. while (cur) {
  4615. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4616. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4617. cur = feeder(i++);
  4618. }
  4619. if (bias) {
  4620. minimum.x -= minimum.x * bias.x + bias.y;
  4621. minimum.y -= minimum.y * bias.x + bias.y;
  4622. maximum.x += maximum.x * bias.x + bias.y;
  4623. maximum.y += maximum.y * bias.x + bias.y;
  4624. }
  4625. return {
  4626. minimum: minimum,
  4627. maximum: maximum
  4628. };
  4629. };
  4630. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4631. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4632. return undefined;
  4633. return Array.isArray(obj) ? obj : [obj];
  4634. };
  4635. // Misc.
  4636. Tools.GetPointerPrefix = function () {
  4637. var eventPrefix = "pointer";
  4638. // Check if pointer events are supported
  4639. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4640. eventPrefix = "mouse";
  4641. }
  4642. return eventPrefix;
  4643. };
  4644. Tools.QueueNewFrame = function (func) {
  4645. if (window.requestAnimationFrame)
  4646. window.requestAnimationFrame(func);
  4647. else if (window.msRequestAnimationFrame)
  4648. window.msRequestAnimationFrame(func);
  4649. else if (window.webkitRequestAnimationFrame)
  4650. window.webkitRequestAnimationFrame(func);
  4651. else if (window.mozRequestAnimationFrame)
  4652. window.mozRequestAnimationFrame(func);
  4653. else if (window.oRequestAnimationFrame)
  4654. window.oRequestAnimationFrame(func);
  4655. else {
  4656. window.setTimeout(func, 16);
  4657. }
  4658. };
  4659. Tools.RequestFullscreen = function (element, options) {
  4660. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4661. if (!requestFunction)
  4662. return;
  4663. requestFunction.call(element, options);
  4664. };
  4665. Tools.ExitFullscreen = function () {
  4666. if (document.exitFullscreen) {
  4667. document.exitFullscreen();
  4668. }
  4669. else if (document.mozCancelFullScreen) {
  4670. document.mozCancelFullScreen();
  4671. }
  4672. else if (document.webkitCancelFullScreen) {
  4673. document.webkitCancelFullScreen();
  4674. }
  4675. else if (document.msCancelFullScreen) {
  4676. document.msCancelFullScreen();
  4677. }
  4678. };
  4679. // External files
  4680. Tools.CleanUrl = function (url) {
  4681. url = url.replace(/#/mg, "%23");
  4682. return url;
  4683. };
  4684. Tools.LoadImage = function (url, onload, onerror, database) {
  4685. if (url instanceof ArrayBuffer) {
  4686. url = Tools.EncodeArrayBufferTobase64(url);
  4687. }
  4688. url = Tools.CleanUrl(url);
  4689. var img = new Image();
  4690. if (url.substr(0, 5) !== "data:") {
  4691. if (Tools.CorsBehavior) {
  4692. switch (typeof (Tools.CorsBehavior)) {
  4693. case "function":
  4694. var result = Tools.CorsBehavior(url);
  4695. if (result) {
  4696. img.crossOrigin = result;
  4697. }
  4698. break;
  4699. case "string":
  4700. default:
  4701. img.crossOrigin = Tools.CorsBehavior;
  4702. break;
  4703. }
  4704. }
  4705. }
  4706. img.onload = function () {
  4707. onload(img);
  4708. };
  4709. img.onerror = function (err) {
  4710. Tools.Error("Error while trying to load texture: " + url);
  4711. if (Tools.UseFallbackTexture) {
  4712. 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";
  4713. onload(img);
  4714. }
  4715. else {
  4716. onerror();
  4717. }
  4718. };
  4719. var noIndexedDB = function () {
  4720. img.src = url;
  4721. };
  4722. var loadFromIndexedDB = function () {
  4723. database.loadImageFromDB(url, img);
  4724. };
  4725. //ANY database to do!
  4726. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4727. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4728. }
  4729. else {
  4730. if (url.indexOf("file:") === -1) {
  4731. noIndexedDB();
  4732. }
  4733. else {
  4734. try {
  4735. var textureName = url.substring(5).toLowerCase();
  4736. var blobURL;
  4737. try {
  4738. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4739. }
  4740. catch (ex) {
  4741. // Chrome doesn't support oneTimeOnly parameter
  4742. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4743. }
  4744. img.src = blobURL;
  4745. }
  4746. catch (e) {
  4747. img.src = null;
  4748. }
  4749. }
  4750. }
  4751. return img;
  4752. };
  4753. //ANY
  4754. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4755. url = Tools.CleanUrl(url);
  4756. var noIndexedDB = function () {
  4757. var request = new XMLHttpRequest();
  4758. var loadUrl = Tools.BaseUrl + url;
  4759. request.open('GET', loadUrl, true);
  4760. if (useArrayBuffer) {
  4761. request.responseType = "arraybuffer";
  4762. }
  4763. request.onprogress = progressCallBack;
  4764. request.onreadystatechange = function () {
  4765. if (request.readyState === 4) {
  4766. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4767. callback(!useArrayBuffer ? request.responseText : request.response);
  4768. }
  4769. else {
  4770. if (onError) {
  4771. onError();
  4772. }
  4773. else {
  4774. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4775. }
  4776. }
  4777. }
  4778. };
  4779. request.send(null);
  4780. };
  4781. var loadFromIndexedDB = function () {
  4782. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4783. };
  4784. if (url.indexOf("file:") !== -1) {
  4785. var fileName = url.substring(5).toLowerCase();
  4786. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4787. }
  4788. else {
  4789. // Caching all files
  4790. if (database && database.enableSceneOffline) {
  4791. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4792. }
  4793. else {
  4794. noIndexedDB();
  4795. }
  4796. }
  4797. };
  4798. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4799. var reader = new FileReader();
  4800. reader.onload = function (e) {
  4801. //target doesn't have result from ts 1.3
  4802. callback(e.target['result']);
  4803. };
  4804. reader.onprogress = progressCallback;
  4805. reader.readAsDataURL(fileToLoad);
  4806. };
  4807. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4808. var reader = new FileReader();
  4809. reader.onerror = function (e) {
  4810. Tools.Log("Error while reading file: " + fileToLoad.name);
  4811. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4812. };
  4813. reader.onload = function (e) {
  4814. //target doesn't have result from ts 1.3
  4815. callback(e.target['result']);
  4816. };
  4817. reader.onprogress = progressCallBack;
  4818. if (!useArrayBuffer) {
  4819. // Asynchronous read
  4820. reader.readAsText(fileToLoad);
  4821. }
  4822. else {
  4823. reader.readAsArrayBuffer(fileToLoad);
  4824. }
  4825. };
  4826. //returns a downloadable url to a file content.
  4827. Tools.FileAsURL = function (content) {
  4828. var fileBlob = new Blob([content]);
  4829. var url = window.URL || window.webkitURL;
  4830. var link = url.createObjectURL(fileBlob);
  4831. return link;
  4832. };
  4833. // Misc.
  4834. Tools.Format = function (value, decimals) {
  4835. if (decimals === void 0) { decimals = 2; }
  4836. return value.toFixed(decimals);
  4837. };
  4838. Tools.CheckExtends = function (v, min, max) {
  4839. if (v.x < min.x)
  4840. min.x = v.x;
  4841. if (v.y < min.y)
  4842. min.y = v.y;
  4843. if (v.z < min.z)
  4844. min.z = v.z;
  4845. if (v.x > max.x)
  4846. max.x = v.x;
  4847. if (v.y > max.y)
  4848. max.y = v.y;
  4849. if (v.z > max.z)
  4850. max.z = v.z;
  4851. };
  4852. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4853. for (var prop in source) {
  4854. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4855. continue;
  4856. }
  4857. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4858. continue;
  4859. }
  4860. var sourceValue = source[prop];
  4861. var typeOfSourceValue = typeof sourceValue;
  4862. if (typeOfSourceValue === "function") {
  4863. continue;
  4864. }
  4865. if (typeOfSourceValue === "object") {
  4866. if (sourceValue instanceof Array) {
  4867. destination[prop] = [];
  4868. if (sourceValue.length > 0) {
  4869. if (typeof sourceValue[0] == "object") {
  4870. for (var index = 0; index < sourceValue.length; index++) {
  4871. var clonedValue = cloneValue(sourceValue[index], destination);
  4872. if (destination[prop].indexOf(clonedValue) === -1) {
  4873. destination[prop].push(clonedValue);
  4874. }
  4875. }
  4876. }
  4877. else {
  4878. destination[prop] = sourceValue.slice(0);
  4879. }
  4880. }
  4881. }
  4882. else {
  4883. destination[prop] = cloneValue(sourceValue, destination);
  4884. }
  4885. }
  4886. else {
  4887. destination[prop] = sourceValue;
  4888. }
  4889. }
  4890. };
  4891. Tools.IsEmpty = function (obj) {
  4892. for (var i in obj) {
  4893. return false;
  4894. }
  4895. return true;
  4896. };
  4897. Tools.RegisterTopRootEvents = function (events) {
  4898. for (var index = 0; index < events.length; index++) {
  4899. var event = events[index];
  4900. window.addEventListener(event.name, event.handler, false);
  4901. try {
  4902. if (window.parent) {
  4903. window.parent.addEventListener(event.name, event.handler, false);
  4904. }
  4905. }
  4906. catch (e) {
  4907. }
  4908. }
  4909. };
  4910. Tools.UnregisterTopRootEvents = function (events) {
  4911. for (var index = 0; index < events.length; index++) {
  4912. var event = events[index];
  4913. window.removeEventListener(event.name, event.handler);
  4914. try {
  4915. if (window.parent) {
  4916. window.parent.removeEventListener(event.name, event.handler);
  4917. }
  4918. }
  4919. catch (e) {
  4920. }
  4921. }
  4922. };
  4923. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  4924. if (mimeType === void 0) { mimeType = "image/png"; }
  4925. // Read the contents of the framebuffer
  4926. var numberOfChannelsByLine = width * 4;
  4927. var halfHeight = height / 2;
  4928. //Reading datas from WebGL
  4929. var data = engine.readPixels(0, 0, width, height);
  4930. //To flip image on Y axis.
  4931. for (var i = 0; i < halfHeight; i++) {
  4932. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4933. var currentCell = j + i * numberOfChannelsByLine;
  4934. var targetLine = height - i - 1;
  4935. var targetCell = j + targetLine * numberOfChannelsByLine;
  4936. var temp = data[currentCell];
  4937. data[currentCell] = data[targetCell];
  4938. data[targetCell] = temp;
  4939. }
  4940. }
  4941. // Create a 2D canvas to store the result
  4942. if (!screenshotCanvas) {
  4943. screenshotCanvas = document.createElement('canvas');
  4944. }
  4945. screenshotCanvas.width = width;
  4946. screenshotCanvas.height = height;
  4947. var context = screenshotCanvas.getContext('2d');
  4948. // Copy the pixels to a 2D canvas
  4949. var imageData = context.createImageData(width, height);
  4950. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4951. var castData = imageData.data;
  4952. castData.set(data);
  4953. context.putImageData(imageData, 0, 0);
  4954. var base64Image = screenshotCanvas.toDataURL(mimeType);
  4955. if (successCallback) {
  4956. successCallback(base64Image);
  4957. }
  4958. else {
  4959. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4960. if (("download" in document.createElement("a"))) {
  4961. var a = window.document.createElement("a");
  4962. a.href = base64Image;
  4963. var date = new Date();
  4964. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4965. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4966. window.document.body.appendChild(a);
  4967. a.addEventListener("click", function () {
  4968. a.parentElement.removeChild(a);
  4969. });
  4970. a.click();
  4971. }
  4972. else {
  4973. var newWindow = window.open("");
  4974. var img = newWindow.document.createElement("img");
  4975. img.src = base64Image;
  4976. newWindow.document.body.appendChild(img);
  4977. }
  4978. }
  4979. };
  4980. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  4981. if (mimeType === void 0) { mimeType = "image/png"; }
  4982. var width;
  4983. var height;
  4984. //If a precision value is specified
  4985. if (size.precision) {
  4986. width = Math.round(engine.getRenderWidth() * size.precision);
  4987. height = Math.round(width / engine.getAspectRatio(camera));
  4988. size = { width: width, height: height };
  4989. }
  4990. else if (size.width && size.height) {
  4991. width = size.width;
  4992. height = size.height;
  4993. }
  4994. else if (size.width && !size.height) {
  4995. width = size.width;
  4996. height = Math.round(width / engine.getAspectRatio(camera));
  4997. size = { width: width, height: height };
  4998. }
  4999. else if (size.height && !size.width) {
  5000. height = size.height;
  5001. width = Math.round(height * engine.getAspectRatio(camera));
  5002. size = { width: width, height: height };
  5003. }
  5004. else if (!isNaN(size)) {
  5005. height = size;
  5006. width = size;
  5007. }
  5008. else {
  5009. Tools.Error("Invalid 'size' parameter !");
  5010. return;
  5011. }
  5012. var scene = camera.getScene();
  5013. var previousCamera = null;
  5014. if (scene.activeCamera !== camera) {
  5015. previousCamera = scene.activeCamera;
  5016. scene.activeCamera = camera;
  5017. }
  5018. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5019. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  5020. texture.renderList = scene.meshes;
  5021. texture.onAfterRenderObservable.add(function () {
  5022. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5023. });
  5024. scene.incrementRenderId();
  5025. scene.resetCachedMaterial();
  5026. texture.render(true);
  5027. texture.dispose();
  5028. if (previousCamera) {
  5029. scene.activeCamera = previousCamera;
  5030. }
  5031. camera.getProjectionMatrix(true); // Force cache refresh;
  5032. };
  5033. // XHR response validator for local file scenario
  5034. Tools.ValidateXHRData = function (xhr, dataType) {
  5035. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5036. if (dataType === void 0) { dataType = 7; }
  5037. try {
  5038. if (dataType & 1) {
  5039. if (xhr.responseText && xhr.responseText.length > 0) {
  5040. return true;
  5041. }
  5042. else if (dataType === 1) {
  5043. return false;
  5044. }
  5045. }
  5046. if (dataType & 2) {
  5047. // Check header width and height since there is no "TGA" magic number
  5048. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5049. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5050. return true;
  5051. }
  5052. else if (dataType === 2) {
  5053. return false;
  5054. }
  5055. }
  5056. if (dataType & 4) {
  5057. // Check for the "DDS" magic number
  5058. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5059. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5060. return true;
  5061. }
  5062. else {
  5063. return false;
  5064. }
  5065. }
  5066. }
  5067. catch (e) {
  5068. }
  5069. return false;
  5070. };
  5071. Object.defineProperty(Tools, "NoneLogLevel", {
  5072. get: function () {
  5073. return Tools._NoneLogLevel;
  5074. },
  5075. enumerable: true,
  5076. configurable: true
  5077. });
  5078. Object.defineProperty(Tools, "MessageLogLevel", {
  5079. get: function () {
  5080. return Tools._MessageLogLevel;
  5081. },
  5082. enumerable: true,
  5083. configurable: true
  5084. });
  5085. Object.defineProperty(Tools, "WarningLogLevel", {
  5086. get: function () {
  5087. return Tools._WarningLogLevel;
  5088. },
  5089. enumerable: true,
  5090. configurable: true
  5091. });
  5092. Object.defineProperty(Tools, "ErrorLogLevel", {
  5093. get: function () {
  5094. return Tools._ErrorLogLevel;
  5095. },
  5096. enumerable: true,
  5097. configurable: true
  5098. });
  5099. Object.defineProperty(Tools, "AllLogLevel", {
  5100. get: function () {
  5101. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5102. },
  5103. enumerable: true,
  5104. configurable: true
  5105. });
  5106. Tools._AddLogEntry = function (entry) {
  5107. Tools._LogCache = entry + Tools._LogCache;
  5108. if (Tools.OnNewCacheEntry) {
  5109. Tools.OnNewCacheEntry(entry);
  5110. }
  5111. };
  5112. Tools._FormatMessage = function (message) {
  5113. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5114. var date = new Date();
  5115. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5116. };
  5117. Tools._LogDisabled = function (message) {
  5118. // nothing to do
  5119. };
  5120. Tools._LogEnabled = function (message) {
  5121. var formattedMessage = Tools._FormatMessage(message);
  5122. console.log("BJS - " + formattedMessage);
  5123. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5124. Tools._AddLogEntry(entry);
  5125. };
  5126. Tools._WarnDisabled = function (message) {
  5127. // nothing to do
  5128. };
  5129. Tools._WarnEnabled = function (message) {
  5130. var formattedMessage = Tools._FormatMessage(message);
  5131. console.warn("BJS - " + formattedMessage);
  5132. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5133. Tools._AddLogEntry(entry);
  5134. };
  5135. Tools._ErrorDisabled = function (message) {
  5136. // nothing to do
  5137. };
  5138. Tools._ErrorEnabled = function (message) {
  5139. Tools.errorsCount++;
  5140. var formattedMessage = Tools._FormatMessage(message);
  5141. console.error("BJS - " + formattedMessage);
  5142. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5143. Tools._AddLogEntry(entry);
  5144. };
  5145. Object.defineProperty(Tools, "LogCache", {
  5146. get: function () {
  5147. return Tools._LogCache;
  5148. },
  5149. enumerable: true,
  5150. configurable: true
  5151. });
  5152. Tools.ClearLogCache = function () {
  5153. Tools._LogCache = "";
  5154. Tools.errorsCount = 0;
  5155. };
  5156. Object.defineProperty(Tools, "LogLevels", {
  5157. set: function (level) {
  5158. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5159. Tools.Log = Tools._LogEnabled;
  5160. }
  5161. else {
  5162. Tools.Log = Tools._LogDisabled;
  5163. }
  5164. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5165. Tools.Warn = Tools._WarnEnabled;
  5166. }
  5167. else {
  5168. Tools.Warn = Tools._WarnDisabled;
  5169. }
  5170. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5171. Tools.Error = Tools._ErrorEnabled;
  5172. }
  5173. else {
  5174. Tools.Error = Tools._ErrorDisabled;
  5175. }
  5176. },
  5177. enumerable: true,
  5178. configurable: true
  5179. });
  5180. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5181. get: function () {
  5182. return Tools._PerformanceNoneLogLevel;
  5183. },
  5184. enumerable: true,
  5185. configurable: true
  5186. });
  5187. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5188. get: function () {
  5189. return Tools._PerformanceUserMarkLogLevel;
  5190. },
  5191. enumerable: true,
  5192. configurable: true
  5193. });
  5194. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5195. get: function () {
  5196. return Tools._PerformanceConsoleLogLevel;
  5197. },
  5198. enumerable: true,
  5199. configurable: true
  5200. });
  5201. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5202. set: function (level) {
  5203. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5204. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5205. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5206. return;
  5207. }
  5208. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5209. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5210. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5211. return;
  5212. }
  5213. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5214. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5215. },
  5216. enumerable: true,
  5217. configurable: true
  5218. });
  5219. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5220. };
  5221. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5222. };
  5223. Tools._StartUserMark = function (counterName, condition) {
  5224. if (condition === void 0) { condition = true; }
  5225. if (!condition || !Tools._performance.mark) {
  5226. return;
  5227. }
  5228. Tools._performance.mark(counterName + "-Begin");
  5229. };
  5230. Tools._EndUserMark = function (counterName, condition) {
  5231. if (condition === void 0) { condition = true; }
  5232. if (!condition || !Tools._performance.mark) {
  5233. return;
  5234. }
  5235. Tools._performance.mark(counterName + "-End");
  5236. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5237. };
  5238. Tools._StartPerformanceConsole = function (counterName, condition) {
  5239. if (condition === void 0) { condition = true; }
  5240. if (!condition) {
  5241. return;
  5242. }
  5243. Tools._StartUserMark(counterName, condition);
  5244. if (console.time) {
  5245. console.time(counterName);
  5246. }
  5247. };
  5248. Tools._EndPerformanceConsole = function (counterName, condition) {
  5249. if (condition === void 0) { condition = true; }
  5250. if (!condition) {
  5251. return;
  5252. }
  5253. Tools._EndUserMark(counterName, condition);
  5254. if (console.time) {
  5255. console.timeEnd(counterName);
  5256. }
  5257. };
  5258. Object.defineProperty(Tools, "Now", {
  5259. get: function () {
  5260. if (window.performance && window.performance.now) {
  5261. return window.performance.now();
  5262. }
  5263. return new Date().getTime();
  5264. },
  5265. enumerable: true,
  5266. configurable: true
  5267. });
  5268. /**
  5269. * This method will return the name of the class used to create the instance of the given object.
  5270. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5271. * @param object the object to get the class name from
  5272. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5273. */
  5274. Tools.getClassName = function (object, isType) {
  5275. if (isType === void 0) { isType = false; }
  5276. var name = null;
  5277. if (!isType && object.getClassName) {
  5278. name = object.getClassName();
  5279. }
  5280. else {
  5281. if (object instanceof Object) {
  5282. var classObj = isType ? object : Object.getPrototypeOf(object);
  5283. name = classObj.constructor["__bjsclassName__"];
  5284. }
  5285. if (!name) {
  5286. name = typeof object;
  5287. }
  5288. }
  5289. return name;
  5290. };
  5291. Tools.first = function (array, predicate) {
  5292. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  5293. var el = array_1[_i];
  5294. if (predicate(el)) {
  5295. return el;
  5296. }
  5297. }
  5298. };
  5299. /**
  5300. * 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.
  5301. * @param array
  5302. */
  5303. Tools.arrayOrStringFeeder = function (array) {
  5304. return function (index) {
  5305. if (index >= array.length) {
  5306. return null;
  5307. }
  5308. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5309. if (val && val.getHashCode) {
  5310. val = val.getHashCode();
  5311. }
  5312. if (typeof val === "string") {
  5313. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5314. }
  5315. return val;
  5316. };
  5317. };
  5318. /**
  5319. * Compute the hashCode of a stream of number
  5320. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5321. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5322. * @return the hash code computed
  5323. */
  5324. Tools.hashCodeFromStream = function (feeder) {
  5325. // Based from here: http://stackoverflow.com/a/7616484/802124
  5326. var hash = 0;
  5327. var index = 0;
  5328. var chr = feeder(index++);
  5329. while (chr != null) {
  5330. hash = ((hash << 5) - hash) + chr;
  5331. hash |= 0; // Convert to 32bit integer
  5332. chr = feeder(index++);
  5333. }
  5334. return hash;
  5335. };
  5336. Tools.BaseUrl = "";
  5337. Tools.CorsBehavior = "anonymous";
  5338. Tools.UseFallbackTexture = true;
  5339. // Logs
  5340. Tools._NoneLogLevel = 0;
  5341. Tools._MessageLogLevel = 1;
  5342. Tools._WarningLogLevel = 2;
  5343. Tools._ErrorLogLevel = 4;
  5344. Tools._LogCache = "";
  5345. Tools.errorsCount = 0;
  5346. Tools.Log = Tools._LogEnabled;
  5347. Tools.Warn = Tools._WarnEnabled;
  5348. Tools.Error = Tools._ErrorEnabled;
  5349. // Performances
  5350. Tools._PerformanceNoneLogLevel = 0;
  5351. Tools._PerformanceUserMarkLogLevel = 1;
  5352. Tools._PerformanceConsoleLogLevel = 2;
  5353. Tools._performance = window.performance;
  5354. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5355. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5356. return Tools;
  5357. }());
  5358. BABYLON.Tools = Tools;
  5359. /**
  5360. * This class is used to track a performance counter which is number based.
  5361. * The user has access to many properties which give statistics of different nature
  5362. *
  5363. * The implementer can track two kinds of Performance Counter: time and count
  5364. * 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.
  5365. * 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.
  5366. */
  5367. var PerfCounter = (function () {
  5368. function PerfCounter() {
  5369. this._startMonitoringTime = 0;
  5370. this._min = 0;
  5371. this._max = 0;
  5372. this._average = 0;
  5373. this._lastSecAverage = 0;
  5374. this._current = 0;
  5375. this._totalValueCount = 0;
  5376. this._totalAccumulated = 0;
  5377. this._lastSecAccumulated = 0;
  5378. this._lastSecTime = 0;
  5379. this._lastSecValueCount = 0;
  5380. }
  5381. Object.defineProperty(PerfCounter.prototype, "min", {
  5382. /**
  5383. * Returns the smallest value ever
  5384. */
  5385. get: function () {
  5386. return this._min;
  5387. },
  5388. enumerable: true,
  5389. configurable: true
  5390. });
  5391. Object.defineProperty(PerfCounter.prototype, "max", {
  5392. /**
  5393. * Returns the biggest value ever
  5394. */
  5395. get: function () {
  5396. return this._max;
  5397. },
  5398. enumerable: true,
  5399. configurable: true
  5400. });
  5401. Object.defineProperty(PerfCounter.prototype, "average", {
  5402. /**
  5403. * Returns the average value since the performance counter is running
  5404. */
  5405. get: function () {
  5406. return this._average;
  5407. },
  5408. enumerable: true,
  5409. configurable: true
  5410. });
  5411. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5412. /**
  5413. * Returns the average value of the last second the counter was monitored
  5414. */
  5415. get: function () {
  5416. return this._lastSecAverage;
  5417. },
  5418. enumerable: true,
  5419. configurable: true
  5420. });
  5421. Object.defineProperty(PerfCounter.prototype, "current", {
  5422. /**
  5423. * Returns the current value
  5424. */
  5425. get: function () {
  5426. return this._current;
  5427. },
  5428. enumerable: true,
  5429. configurable: true
  5430. });
  5431. Object.defineProperty(PerfCounter.prototype, "total", {
  5432. get: function () {
  5433. return this._totalAccumulated;
  5434. },
  5435. enumerable: true,
  5436. configurable: true
  5437. });
  5438. /**
  5439. * Call this method to start monitoring a new frame.
  5440. * 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.
  5441. */
  5442. PerfCounter.prototype.fetchNewFrame = function () {
  5443. this._totalValueCount++;
  5444. this._current = 0;
  5445. this._lastSecValueCount++;
  5446. };
  5447. /**
  5448. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5449. * @param newCount the count value to add to the monitored count
  5450. * @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.
  5451. */
  5452. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5453. this._current += newCount;
  5454. if (fetchResult) {
  5455. this._fetchResult();
  5456. }
  5457. };
  5458. /**
  5459. * Start monitoring this performance counter
  5460. */
  5461. PerfCounter.prototype.beginMonitoring = function () {
  5462. this._startMonitoringTime = Tools.Now;
  5463. };
  5464. /**
  5465. * Compute the time lapsed since the previous beginMonitoring() call.
  5466. * @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
  5467. */
  5468. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5469. if (newFrame === void 0) { newFrame = true; }
  5470. if (newFrame) {
  5471. this.fetchNewFrame();
  5472. }
  5473. var currentTime = Tools.Now;
  5474. this._current = currentTime - this._startMonitoringTime;
  5475. if (newFrame) {
  5476. this._fetchResult();
  5477. }
  5478. };
  5479. PerfCounter.prototype._fetchResult = function () {
  5480. this._totalAccumulated += this._current;
  5481. this._lastSecAccumulated += this._current;
  5482. // Min/Max update
  5483. this._min = Math.min(this._min, this._current);
  5484. this._max = Math.max(this._max, this._current);
  5485. this._average = this._totalAccumulated / this._totalValueCount;
  5486. // Reset last sec?
  5487. var now = Tools.Now;
  5488. if ((now - this._lastSecTime) > 1000) {
  5489. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5490. this._lastSecTime = now;
  5491. this._lastSecAccumulated = 0;
  5492. this._lastSecValueCount = 0;
  5493. }
  5494. };
  5495. return PerfCounter;
  5496. }());
  5497. BABYLON.PerfCounter = PerfCounter;
  5498. /**
  5499. * Use this className as a decorator on a given class definition to add it a name.
  5500. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5501. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5502. * @param name
  5503. */
  5504. function className(name) {
  5505. return function (target) {
  5506. target["__bjsclassName__"] = name;
  5507. };
  5508. }
  5509. BABYLON.className = className;
  5510. /**
  5511. * An implementation of a loop for asynchronous functions.
  5512. */
  5513. var AsyncLoop = (function () {
  5514. /**
  5515. * Constroctor.
  5516. * @param iterations the number of iterations.
  5517. * @param _fn the function to run each iteration
  5518. * @param _successCallback the callback that will be called upon succesful execution
  5519. * @param offset starting offset.
  5520. */
  5521. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5522. if (offset === void 0) { offset = 0; }
  5523. this.iterations = iterations;
  5524. this._fn = _fn;
  5525. this._successCallback = _successCallback;
  5526. this.index = offset - 1;
  5527. this._done = false;
  5528. }
  5529. /**
  5530. * Execute the next iteration. Must be called after the last iteration was finished.
  5531. */
  5532. AsyncLoop.prototype.executeNext = function () {
  5533. if (!this._done) {
  5534. if (this.index + 1 < this.iterations) {
  5535. ++this.index;
  5536. this._fn(this);
  5537. }
  5538. else {
  5539. this.breakLoop();
  5540. }
  5541. }
  5542. };
  5543. /**
  5544. * Break the loop and run the success callback.
  5545. */
  5546. AsyncLoop.prototype.breakLoop = function () {
  5547. this._done = true;
  5548. this._successCallback();
  5549. };
  5550. /**
  5551. * Helper function
  5552. */
  5553. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5554. if (offset === void 0) { offset = 0; }
  5555. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5556. loop.executeNext();
  5557. return loop;
  5558. };
  5559. /**
  5560. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5561. * @param iterations total number of iterations
  5562. * @param syncedIterations number of synchronous iterations in each async iteration.
  5563. * @param fn the function to call each iteration.
  5564. * @param callback a success call back that will be called when iterating stops.
  5565. * @param breakFunction a break condition (optional)
  5566. * @param timeout timeout settings for the setTimeout function. default - 0.
  5567. * @constructor
  5568. */
  5569. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5570. if (timeout === void 0) { timeout = 0; }
  5571. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5572. if (breakFunction && breakFunction())
  5573. loop.breakLoop();
  5574. else {
  5575. setTimeout(function () {
  5576. for (var i = 0; i < syncedIterations; ++i) {
  5577. var iteration = (loop.index * syncedIterations) + i;
  5578. if (iteration >= iterations)
  5579. break;
  5580. fn(iteration);
  5581. if (breakFunction && breakFunction()) {
  5582. loop.breakLoop();
  5583. break;
  5584. }
  5585. }
  5586. loop.executeNext();
  5587. }, timeout);
  5588. }
  5589. }, callback);
  5590. };
  5591. return AsyncLoop;
  5592. }());
  5593. BABYLON.AsyncLoop = AsyncLoop;
  5594. })(BABYLON || (BABYLON = {}));
  5595. var BABYLON;
  5596. (function (BABYLON) {
  5597. var Internals;
  5598. (function (Internals) {
  5599. var _AlphaState = (function () {
  5600. function _AlphaState() {
  5601. this._isAlphaBlendDirty = false;
  5602. this._isBlendFunctionParametersDirty = false;
  5603. this._alphaBlend = false;
  5604. this._blendFunctionParameters = new Array(4);
  5605. }
  5606. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5607. get: function () {
  5608. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5609. },
  5610. enumerable: true,
  5611. configurable: true
  5612. });
  5613. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5614. get: function () {
  5615. return this._alphaBlend;
  5616. },
  5617. set: function (value) {
  5618. if (this._alphaBlend === value) {
  5619. return;
  5620. }
  5621. this._alphaBlend = value;
  5622. this._isAlphaBlendDirty = true;
  5623. },
  5624. enumerable: true,
  5625. configurable: true
  5626. });
  5627. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5628. if (this._blendFunctionParameters[0] === value0 &&
  5629. this._blendFunctionParameters[1] === value1 &&
  5630. this._blendFunctionParameters[2] === value2 &&
  5631. this._blendFunctionParameters[3] === value3) {
  5632. return;
  5633. }
  5634. this._blendFunctionParameters[0] = value0;
  5635. this._blendFunctionParameters[1] = value1;
  5636. this._blendFunctionParameters[2] = value2;
  5637. this._blendFunctionParameters[3] = value3;
  5638. this._isBlendFunctionParametersDirty = true;
  5639. };
  5640. _AlphaState.prototype.reset = function () {
  5641. this._alphaBlend = false;
  5642. this._blendFunctionParameters[0] = null;
  5643. this._blendFunctionParameters[1] = null;
  5644. this._blendFunctionParameters[2] = null;
  5645. this._blendFunctionParameters[3] = null;
  5646. this._isAlphaBlendDirty = true;
  5647. this._isBlendFunctionParametersDirty = false;
  5648. };
  5649. _AlphaState.prototype.apply = function (gl) {
  5650. if (!this.isDirty) {
  5651. return;
  5652. }
  5653. // Alpha blend
  5654. if (this._isAlphaBlendDirty) {
  5655. if (this._alphaBlend) {
  5656. gl.enable(gl.BLEND);
  5657. }
  5658. else {
  5659. gl.disable(gl.BLEND);
  5660. }
  5661. this._isAlphaBlendDirty = false;
  5662. }
  5663. // Alpha function
  5664. if (this._isBlendFunctionParametersDirty) {
  5665. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5666. this._isBlendFunctionParametersDirty = false;
  5667. }
  5668. };
  5669. return _AlphaState;
  5670. }());
  5671. Internals._AlphaState = _AlphaState;
  5672. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5673. })(BABYLON || (BABYLON = {}));
  5674. var BABYLON;
  5675. (function (BABYLON) {
  5676. var Internals;
  5677. (function (Internals) {
  5678. var _DepthCullingState = (function () {
  5679. function _DepthCullingState() {
  5680. this._isDepthTestDirty = false;
  5681. this._isDepthMaskDirty = false;
  5682. this._isDepthFuncDirty = false;
  5683. this._isCullFaceDirty = false;
  5684. this._isCullDirty = false;
  5685. this._isZOffsetDirty = false;
  5686. }
  5687. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5688. get: function () {
  5689. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5690. },
  5691. enumerable: true,
  5692. configurable: true
  5693. });
  5694. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5695. get: function () {
  5696. return this._zOffset;
  5697. },
  5698. set: function (value) {
  5699. if (this._zOffset === value) {
  5700. return;
  5701. }
  5702. this._zOffset = value;
  5703. this._isZOffsetDirty = true;
  5704. },
  5705. enumerable: true,
  5706. configurable: true
  5707. });
  5708. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5709. get: function () {
  5710. return this._cullFace;
  5711. },
  5712. set: function (value) {
  5713. if (this._cullFace === value) {
  5714. return;
  5715. }
  5716. this._cullFace = value;
  5717. this._isCullFaceDirty = true;
  5718. },
  5719. enumerable: true,
  5720. configurable: true
  5721. });
  5722. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5723. get: function () {
  5724. return this._cull;
  5725. },
  5726. set: function (value) {
  5727. if (this._cull === value) {
  5728. return;
  5729. }
  5730. this._cull = value;
  5731. this._isCullDirty = true;
  5732. },
  5733. enumerable: true,
  5734. configurable: true
  5735. });
  5736. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5737. get: function () {
  5738. return this._depthFunc;
  5739. },
  5740. set: function (value) {
  5741. if (this._depthFunc === value) {
  5742. return;
  5743. }
  5744. this._depthFunc = value;
  5745. this._isDepthFuncDirty = true;
  5746. },
  5747. enumerable: true,
  5748. configurable: true
  5749. });
  5750. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5751. get: function () {
  5752. return this._depthMask;
  5753. },
  5754. set: function (value) {
  5755. if (this._depthMask === value) {
  5756. return;
  5757. }
  5758. this._depthMask = value;
  5759. this._isDepthMaskDirty = true;
  5760. },
  5761. enumerable: true,
  5762. configurable: true
  5763. });
  5764. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5765. get: function () {
  5766. return this._depthTest;
  5767. },
  5768. set: function (value) {
  5769. if (this._depthTest === value) {
  5770. return;
  5771. }
  5772. this._depthTest = value;
  5773. this._isDepthTestDirty = true;
  5774. },
  5775. enumerable: true,
  5776. configurable: true
  5777. });
  5778. _DepthCullingState.prototype.reset = function () {
  5779. this._depthMask = true;
  5780. this._depthTest = true;
  5781. this._depthFunc = null;
  5782. this._cullFace = null;
  5783. this._cull = null;
  5784. this._zOffset = 0;
  5785. this._isDepthTestDirty = true;
  5786. this._isDepthMaskDirty = true;
  5787. this._isDepthFuncDirty = false;
  5788. this._isCullFaceDirty = false;
  5789. this._isCullDirty = false;
  5790. this._isZOffsetDirty = false;
  5791. };
  5792. _DepthCullingState.prototype.apply = function (gl) {
  5793. if (!this.isDirty) {
  5794. return;
  5795. }
  5796. // Cull
  5797. if (this._isCullDirty) {
  5798. if (this.cull) {
  5799. gl.enable(gl.CULL_FACE);
  5800. }
  5801. else {
  5802. gl.disable(gl.CULL_FACE);
  5803. }
  5804. this._isCullDirty = false;
  5805. }
  5806. // Cull face
  5807. if (this._isCullFaceDirty) {
  5808. gl.cullFace(this.cullFace);
  5809. this._isCullFaceDirty = false;
  5810. }
  5811. // Depth mask
  5812. if (this._isDepthMaskDirty) {
  5813. gl.depthMask(this.depthMask);
  5814. this._isDepthMaskDirty = false;
  5815. }
  5816. // Depth test
  5817. if (this._isDepthTestDirty) {
  5818. if (this.depthTest) {
  5819. gl.enable(gl.DEPTH_TEST);
  5820. }
  5821. else {
  5822. gl.disable(gl.DEPTH_TEST);
  5823. }
  5824. this._isDepthTestDirty = false;
  5825. }
  5826. // Depth func
  5827. if (this._isDepthFuncDirty) {
  5828. gl.depthFunc(this.depthFunc);
  5829. this._isDepthFuncDirty = false;
  5830. }
  5831. // zOffset
  5832. if (this._isZOffsetDirty) {
  5833. if (this.zOffset) {
  5834. gl.enable(gl.POLYGON_OFFSET_FILL);
  5835. gl.polygonOffset(this.zOffset, 0);
  5836. }
  5837. else {
  5838. gl.disable(gl.POLYGON_OFFSET_FILL);
  5839. }
  5840. this._isZOffsetDirty = false;
  5841. }
  5842. };
  5843. return _DepthCullingState;
  5844. }());
  5845. Internals._DepthCullingState = _DepthCullingState;
  5846. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5847. })(BABYLON || (BABYLON = {}));
  5848. var BABYLON;
  5849. (function (BABYLON) {
  5850. var compileShader = function (gl, source, type, defines) {
  5851. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5852. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5853. gl.compileShader(shader);
  5854. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5855. throw new Error(gl.getShaderInfoLog(shader));
  5856. }
  5857. return shader;
  5858. };
  5859. var HALF_FLOAT_OES = 0x8D61;
  5860. var getWebGLTextureType = function (gl, type) {
  5861. if (type === Engine.TEXTURETYPE_FLOAT) {
  5862. return gl.FLOAT;
  5863. }
  5864. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  5865. // Add Half Float Constant.
  5866. return HALF_FLOAT_OES;
  5867. }
  5868. return gl.UNSIGNED_BYTE;
  5869. };
  5870. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5871. var magFilter = gl.NEAREST;
  5872. var minFilter = gl.NEAREST;
  5873. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5874. magFilter = gl.LINEAR;
  5875. if (generateMipMaps) {
  5876. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5877. }
  5878. else {
  5879. minFilter = gl.LINEAR;
  5880. }
  5881. }
  5882. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5883. magFilter = gl.LINEAR;
  5884. if (generateMipMaps) {
  5885. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5886. }
  5887. else {
  5888. minFilter = gl.LINEAR;
  5889. }
  5890. }
  5891. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5892. magFilter = gl.NEAREST;
  5893. if (generateMipMaps) {
  5894. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5895. }
  5896. else {
  5897. minFilter = gl.NEAREST;
  5898. }
  5899. }
  5900. return {
  5901. min: minFilter,
  5902. mag: magFilter
  5903. };
  5904. };
  5905. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5906. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5907. var engine = scene.getEngine();
  5908. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5909. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5910. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  5911. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5912. texture._baseWidth = width;
  5913. texture._baseHeight = height;
  5914. texture._width = potWidth;
  5915. texture._height = potHeight;
  5916. texture.isReady = true;
  5917. processFunction(potWidth, potHeight);
  5918. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5919. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5920. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5921. if (!noMipmap && !isCompressed) {
  5922. gl.generateMipmap(gl.TEXTURE_2D);
  5923. }
  5924. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  5925. engine.resetTextureCache();
  5926. scene._removePendingData(texture);
  5927. if (onLoad) {
  5928. onLoad();
  5929. }
  5930. };
  5931. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5932. var img;
  5933. var onload = function () {
  5934. loadedImages[index] = img;
  5935. loadedImages._internalCount++;
  5936. scene._removePendingData(img);
  5937. if (loadedImages._internalCount === 6) {
  5938. onfinish(loadedImages);
  5939. }
  5940. };
  5941. var onerror = function () {
  5942. scene._removePendingData(img);
  5943. };
  5944. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5945. scene._addPendingData(img);
  5946. };
  5947. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5948. var loadedImages = [];
  5949. loadedImages._internalCount = 0;
  5950. for (var index = 0; index < 6; index++) {
  5951. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5952. }
  5953. };
  5954. var InstancingAttributeInfo = (function () {
  5955. function InstancingAttributeInfo() {
  5956. }
  5957. return InstancingAttributeInfo;
  5958. }());
  5959. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  5960. var EngineCapabilities = (function () {
  5961. function EngineCapabilities() {
  5962. }
  5963. return EngineCapabilities;
  5964. }());
  5965. BABYLON.EngineCapabilities = EngineCapabilities;
  5966. /**
  5967. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5968. */
  5969. var Engine = (function () {
  5970. /**
  5971. * @constructor
  5972. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5973. * @param {boolean} [antialias] - enable antialias
  5974. * @param options - further options to be sent to the getContext function
  5975. */
  5976. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5977. var _this = this;
  5978. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5979. // Public members
  5980. this.isFullscreen = false;
  5981. this.isPointerLock = false;
  5982. this.cullBackFaces = true;
  5983. this.renderEvenInBackground = true;
  5984. // To enable/disable IDB support and avoid XHR on .manifest
  5985. this.enableOfflineSupport = true;
  5986. this.scenes = new Array();
  5987. this._windowIsBackground = false;
  5988. this._webGLVersion = "1.0";
  5989. this._drawCalls = new BABYLON.PerfCounter();
  5990. this._renderingQueueLaunched = false;
  5991. this._activeRenderLoops = [];
  5992. // FPS
  5993. this.fpsRange = 60;
  5994. this.previousFramesDuration = [];
  5995. this.fps = 60;
  5996. this.deltaTime = 0;
  5997. // States
  5998. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5999. this._alphaState = new BABYLON.Internals._AlphaState();
  6000. this._alphaMode = Engine.ALPHA_DISABLE;
  6001. // Cache
  6002. this._loadedTexturesCache = new Array();
  6003. this._maxTextureChannels = 16;
  6004. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6005. this._compiledEffects = {};
  6006. this._uintIndicesCurrentlySet = false;
  6007. this._currentBoundBuffer = new Array();
  6008. this._currentBufferPointers = [];
  6009. this._currentInstanceLocations = new Array();
  6010. this._currentInstanceBuffers = new Array();
  6011. this._renderingCanvas = canvas;
  6012. this._externalData = new BABYLON.StringDictionary();
  6013. options = options || {};
  6014. options.antialias = antialias;
  6015. if (options.preserveDrawingBuffer === undefined) {
  6016. options.preserveDrawingBuffer = false;
  6017. }
  6018. // GL
  6019. //try {
  6020. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6021. // if (this._gl) {
  6022. // this._webGLVersion = "2.0";
  6023. // }
  6024. //} catch (e) {
  6025. // // Do nothing
  6026. //}
  6027. if (!this._gl) {
  6028. try {
  6029. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6030. }
  6031. catch (e) {
  6032. throw new Error("WebGL not supported");
  6033. }
  6034. }
  6035. if (!this._gl) {
  6036. throw new Error("WebGL not supported");
  6037. }
  6038. this._onBlur = function () {
  6039. _this._windowIsBackground = true;
  6040. };
  6041. this._onFocus = function () {
  6042. _this._windowIsBackground = false;
  6043. };
  6044. window.addEventListener("blur", this._onBlur);
  6045. window.addEventListener("focus", this._onFocus);
  6046. // Viewport
  6047. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6048. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6049. this.resize();
  6050. // Caps
  6051. this._caps = new EngineCapabilities();
  6052. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6053. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6054. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6055. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6056. // Infos
  6057. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6058. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6059. if (rendererInfo != null) {
  6060. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6061. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6062. }
  6063. if (!this._glVendor) {
  6064. this._glVendor = "Unknown vendor";
  6065. }
  6066. if (!this._glRenderer) {
  6067. this._glRenderer = "Unknown renderer";
  6068. }
  6069. // Extensions
  6070. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  6071. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  6072. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  6073. 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');
  6074. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6075. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  6076. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  6077. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  6078. this._caps.highPrecisionShaderSupported = true;
  6079. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  6080. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  6081. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  6082. this._caps.textureFloatRender = this._canRenderToFloatTexture();
  6083. this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
  6084. this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
  6085. this._caps.textureHalfFloatRender = this._canRenderToHalfFloatTexture();
  6086. if (this._gl.getShaderPrecisionFormat) {
  6087. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6088. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6089. }
  6090. // Depth buffer
  6091. this.setDepthBuffer(true);
  6092. this.setDepthFunctionToLessOrEqual();
  6093. this.setDepthWrite(true);
  6094. // Fullscreen
  6095. this._onFullscreenChange = function () {
  6096. if (document.fullscreen !== undefined) {
  6097. _this.isFullscreen = document.fullscreen;
  6098. }
  6099. else if (document.mozFullScreen !== undefined) {
  6100. _this.isFullscreen = document.mozFullScreen;
  6101. }
  6102. else if (document.webkitIsFullScreen !== undefined) {
  6103. _this.isFullscreen = document.webkitIsFullScreen;
  6104. }
  6105. else if (document.msIsFullScreen !== undefined) {
  6106. _this.isFullscreen = document.msIsFullScreen;
  6107. }
  6108. // Pointer lock
  6109. if (_this.isFullscreen && _this._pointerLockRequested) {
  6110. canvas.requestPointerLock = canvas.requestPointerLock ||
  6111. canvas.msRequestPointerLock ||
  6112. canvas.mozRequestPointerLock ||
  6113. canvas.webkitRequestPointerLock;
  6114. if (canvas.requestPointerLock) {
  6115. canvas.requestPointerLock();
  6116. }
  6117. }
  6118. };
  6119. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6120. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6121. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6122. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6123. // Pointer lock
  6124. this._onPointerLockChange = function () {
  6125. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6126. document.webkitPointerLockElement === canvas ||
  6127. document.msPointerLockElement === canvas ||
  6128. document.pointerLockElement === canvas);
  6129. };
  6130. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6131. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6132. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6133. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6134. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6135. Engine.audioEngine = new BABYLON.AudioEngine();
  6136. }
  6137. //default loading screen
  6138. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6139. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6140. }
  6141. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6142. get: function () {
  6143. return Engine._ALPHA_DISABLE;
  6144. },
  6145. enumerable: true,
  6146. configurable: true
  6147. });
  6148. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6149. get: function () {
  6150. return Engine._ALPHA_ONEONE;
  6151. },
  6152. enumerable: true,
  6153. configurable: true
  6154. });
  6155. Object.defineProperty(Engine, "ALPHA_ADD", {
  6156. get: function () {
  6157. return Engine._ALPHA_ADD;
  6158. },
  6159. enumerable: true,
  6160. configurable: true
  6161. });
  6162. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6163. get: function () {
  6164. return Engine._ALPHA_COMBINE;
  6165. },
  6166. enumerable: true,
  6167. configurable: true
  6168. });
  6169. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6170. get: function () {
  6171. return Engine._ALPHA_SUBTRACT;
  6172. },
  6173. enumerable: true,
  6174. configurable: true
  6175. });
  6176. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6177. get: function () {
  6178. return Engine._ALPHA_MULTIPLY;
  6179. },
  6180. enumerable: true,
  6181. configurable: true
  6182. });
  6183. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6184. get: function () {
  6185. return Engine._ALPHA_MAXIMIZED;
  6186. },
  6187. enumerable: true,
  6188. configurable: true
  6189. });
  6190. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6191. get: function () {
  6192. return Engine._DELAYLOADSTATE_NONE;
  6193. },
  6194. enumerable: true,
  6195. configurable: true
  6196. });
  6197. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6198. get: function () {
  6199. return Engine._DELAYLOADSTATE_LOADED;
  6200. },
  6201. enumerable: true,
  6202. configurable: true
  6203. });
  6204. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6205. get: function () {
  6206. return Engine._DELAYLOADSTATE_LOADING;
  6207. },
  6208. enumerable: true,
  6209. configurable: true
  6210. });
  6211. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6212. get: function () {
  6213. return Engine._DELAYLOADSTATE_NOTLOADED;
  6214. },
  6215. enumerable: true,
  6216. configurable: true
  6217. });
  6218. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6219. get: function () {
  6220. return Engine._TEXTUREFORMAT_ALPHA;
  6221. },
  6222. enumerable: true,
  6223. configurable: true
  6224. });
  6225. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6226. get: function () {
  6227. return Engine._TEXTUREFORMAT_LUMINANCE;
  6228. },
  6229. enumerable: true,
  6230. configurable: true
  6231. });
  6232. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6233. get: function () {
  6234. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6235. },
  6236. enumerable: true,
  6237. configurable: true
  6238. });
  6239. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6240. get: function () {
  6241. return Engine._TEXTUREFORMAT_RGB;
  6242. },
  6243. enumerable: true,
  6244. configurable: true
  6245. });
  6246. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6247. get: function () {
  6248. return Engine._TEXTUREFORMAT_RGBA;
  6249. },
  6250. enumerable: true,
  6251. configurable: true
  6252. });
  6253. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6254. get: function () {
  6255. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6256. },
  6257. enumerable: true,
  6258. configurable: true
  6259. });
  6260. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6261. get: function () {
  6262. return Engine._TEXTURETYPE_FLOAT;
  6263. },
  6264. enumerable: true,
  6265. configurable: true
  6266. });
  6267. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  6268. get: function () {
  6269. return Engine._TEXTURETYPE_HALF_FLOAT;
  6270. },
  6271. enumerable: true,
  6272. configurable: true
  6273. });
  6274. Object.defineProperty(Engine, "Version", {
  6275. get: function () {
  6276. return "2.5-alpha";
  6277. },
  6278. enumerable: true,
  6279. configurable: true
  6280. });
  6281. Object.defineProperty(Engine.prototype, "webGLVersion", {
  6282. get: function () {
  6283. return this._webGLVersion;
  6284. },
  6285. enumerable: true,
  6286. configurable: true
  6287. });
  6288. Engine.prototype._prepareWorkingCanvas = function () {
  6289. if (this._workingCanvas) {
  6290. return;
  6291. }
  6292. this._workingCanvas = document.createElement("canvas");
  6293. this._workingContext = this._workingCanvas.getContext("2d");
  6294. };
  6295. Engine.prototype.resetTextureCache = function () {
  6296. for (var index = 0; index < this._maxTextureChannels; index++) {
  6297. this._activeTexturesCache[index] = null;
  6298. }
  6299. };
  6300. Engine.prototype.getGlInfo = function () {
  6301. return {
  6302. vendor: this._glVendor,
  6303. renderer: this._glRenderer,
  6304. version: this._glVersion
  6305. };
  6306. };
  6307. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  6308. if (useScreen === void 0) { useScreen = false; }
  6309. var viewport = camera.viewport;
  6310. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  6311. };
  6312. Engine.prototype.getRenderWidth = function (useScreen) {
  6313. if (useScreen === void 0) { useScreen = false; }
  6314. if (!useScreen && this._currentRenderTarget) {
  6315. return this._currentRenderTarget._width;
  6316. }
  6317. return this._renderingCanvas.width;
  6318. };
  6319. Engine.prototype.getRenderHeight = function (useScreen) {
  6320. if (useScreen === void 0) { useScreen = false; }
  6321. if (!useScreen && this._currentRenderTarget) {
  6322. return this._currentRenderTarget._height;
  6323. }
  6324. return this._renderingCanvas.height;
  6325. };
  6326. Engine.prototype.getRenderingCanvas = function () {
  6327. return this._renderingCanvas;
  6328. };
  6329. Engine.prototype.getRenderingCanvasClientRect = function () {
  6330. return this._renderingCanvas.getBoundingClientRect();
  6331. };
  6332. Engine.prototype.setHardwareScalingLevel = function (level) {
  6333. this._hardwareScalingLevel = level;
  6334. this.resize();
  6335. };
  6336. Engine.prototype.getHardwareScalingLevel = function () {
  6337. return this._hardwareScalingLevel;
  6338. };
  6339. Engine.prototype.getLoadedTexturesCache = function () {
  6340. return this._loadedTexturesCache;
  6341. };
  6342. Engine.prototype.getCaps = function () {
  6343. return this._caps;
  6344. };
  6345. Object.defineProperty(Engine.prototype, "drawCalls", {
  6346. get: function () {
  6347. return this._drawCalls.current;
  6348. },
  6349. enumerable: true,
  6350. configurable: true
  6351. });
  6352. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  6353. get: function () {
  6354. return this._drawCalls;
  6355. },
  6356. enumerable: true,
  6357. configurable: true
  6358. });
  6359. Engine.prototype.getDepthFunction = function () {
  6360. return this._depthCullingState.depthFunc;
  6361. };
  6362. Engine.prototype.setDepthFunction = function (depthFunc) {
  6363. this._depthCullingState.depthFunc = depthFunc;
  6364. };
  6365. Engine.prototype.setDepthFunctionToGreater = function () {
  6366. this._depthCullingState.depthFunc = this._gl.GREATER;
  6367. };
  6368. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  6369. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  6370. };
  6371. Engine.prototype.setDepthFunctionToLess = function () {
  6372. this._depthCullingState.depthFunc = this._gl.LESS;
  6373. };
  6374. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  6375. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  6376. };
  6377. /**
  6378. * stop executing a render loop function and remove it from the execution array
  6379. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  6380. */
  6381. Engine.prototype.stopRenderLoop = function (renderFunction) {
  6382. if (!renderFunction) {
  6383. this._activeRenderLoops = [];
  6384. return;
  6385. }
  6386. var index = this._activeRenderLoops.indexOf(renderFunction);
  6387. if (index >= 0) {
  6388. this._activeRenderLoops.splice(index, 1);
  6389. }
  6390. };
  6391. Engine.prototype._renderLoop = function () {
  6392. var shouldRender = true;
  6393. if (!this.renderEvenInBackground && this._windowIsBackground) {
  6394. shouldRender = false;
  6395. }
  6396. if (shouldRender) {
  6397. // Start new frame
  6398. this.beginFrame();
  6399. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  6400. var renderFunction = this._activeRenderLoops[index];
  6401. renderFunction();
  6402. }
  6403. // Present
  6404. this.endFrame();
  6405. }
  6406. if (this._activeRenderLoops.length > 0) {
  6407. // Register new frame
  6408. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6409. }
  6410. else {
  6411. this._renderingQueueLaunched = false;
  6412. }
  6413. };
  6414. /**
  6415. * Register and execute a render loop. The engine can have more than one render function.
  6416. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  6417. * @example
  6418. * engine.runRenderLoop(function () {
  6419. * scene.render()
  6420. * })
  6421. */
  6422. Engine.prototype.runRenderLoop = function (renderFunction) {
  6423. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  6424. return;
  6425. }
  6426. this._activeRenderLoops.push(renderFunction);
  6427. if (!this._renderingQueueLaunched) {
  6428. this._renderingQueueLaunched = true;
  6429. this._bindedRenderFunction = this._renderLoop.bind(this);
  6430. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6431. }
  6432. };
  6433. /**
  6434. * Toggle full screen mode.
  6435. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  6436. * @param {any} options - an options object to be sent to the requestFullscreen function
  6437. */
  6438. Engine.prototype.switchFullscreen = function (requestPointerLock, options) {
  6439. if (this.isFullscreen) {
  6440. BABYLON.Tools.ExitFullscreen();
  6441. }
  6442. else {
  6443. this._pointerLockRequested = requestPointerLock;
  6444. BABYLON.Tools.RequestFullscreen(this._renderingCanvas, options);
  6445. }
  6446. };
  6447. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  6448. this.applyStates();
  6449. if (backBuffer) {
  6450. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  6451. }
  6452. if (depthStencil && this._depthCullingState.depthMask) {
  6453. this._gl.clearDepth(1.0);
  6454. }
  6455. var mode = 0;
  6456. if (backBuffer) {
  6457. mode |= this._gl.COLOR_BUFFER_BIT;
  6458. }
  6459. if (depthStencil && this._depthCullingState.depthMask) {
  6460. mode |= this._gl.DEPTH_BUFFER_BIT;
  6461. }
  6462. this._gl.clear(mode);
  6463. };
  6464. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  6465. var gl = this._gl;
  6466. // Save state
  6467. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  6468. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  6469. // Change state
  6470. gl.enable(gl.SCISSOR_TEST);
  6471. gl.scissor(x, y, width, height);
  6472. // Clear
  6473. this.clear(clearColor, true, true);
  6474. // Restore state
  6475. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  6476. if (curScissor === true) {
  6477. gl.enable(gl.SCISSOR_TEST);
  6478. }
  6479. else {
  6480. gl.disable(gl.SCISSOR_TEST);
  6481. }
  6482. };
  6483. /**
  6484. * Set the WebGL's viewport
  6485. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  6486. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  6487. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  6488. */
  6489. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  6490. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  6491. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  6492. var x = viewport.x || 0;
  6493. var y = viewport.y || 0;
  6494. this._cachedViewport = viewport;
  6495. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  6496. };
  6497. /**
  6498. * Directly set the WebGL Viewport
  6499. * The x, y, width & height are directly passed to the WebGL call
  6500. * @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.
  6501. */
  6502. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  6503. var currentViewport = this._cachedViewport;
  6504. this._cachedViewport = null;
  6505. this._gl.viewport(x, y, width, height);
  6506. return currentViewport;
  6507. };
  6508. Engine.prototype.beginFrame = function () {
  6509. this._measureFps();
  6510. };
  6511. Engine.prototype.endFrame = function () {
  6512. //this.flushFramebuffer();
  6513. };
  6514. /**
  6515. * resize the view according to the canvas' size.
  6516. * @example
  6517. * window.addEventListener("resize", function () {
  6518. * engine.resize();
  6519. * });
  6520. */
  6521. Engine.prototype.resize = function () {
  6522. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  6523. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  6524. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  6525. for (var index = 0; index < this.scenes.length; index++) {
  6526. var scene = this.scenes[index];
  6527. if (scene.debugLayer.isVisible()) {
  6528. scene.debugLayer._syncPositions();
  6529. }
  6530. }
  6531. };
  6532. /**
  6533. * force a specific size of the canvas
  6534. * @param {number} width - the new canvas' width
  6535. * @param {number} height - the new canvas' height
  6536. */
  6537. Engine.prototype.setSize = function (width, height) {
  6538. this._renderingCanvas.width = width;
  6539. this._renderingCanvas.height = height;
  6540. for (var index = 0; index < this.scenes.length; index++) {
  6541. var scene = this.scenes[index];
  6542. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  6543. var cam = scene.cameras[camIndex];
  6544. cam._currentRenderId = 0;
  6545. }
  6546. }
  6547. };
  6548. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  6549. this._currentRenderTarget = texture;
  6550. var gl = this._gl;
  6551. this.bindUnboundFramebuffer(texture._framebuffer);
  6552. if (texture.isCube) {
  6553. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  6554. }
  6555. else {
  6556. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6557. }
  6558. this._gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  6559. this.wipeCaches();
  6560. };
  6561. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  6562. if (this._currentFramebuffer !== framebuffer) {
  6563. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  6564. this._currentFramebuffer = framebuffer;
  6565. }
  6566. };
  6567. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  6568. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  6569. this._currentRenderTarget = null;
  6570. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  6571. var gl = this._gl;
  6572. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6573. gl.generateMipmap(gl.TEXTURE_2D);
  6574. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  6575. }
  6576. this.bindUnboundFramebuffer(null);
  6577. };
  6578. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  6579. if (texture.generateMipMaps) {
  6580. var gl = this._gl;
  6581. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  6582. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6583. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  6584. }
  6585. };
  6586. Engine.prototype.flushFramebuffer = function () {
  6587. this._gl.flush();
  6588. };
  6589. Engine.prototype.restoreDefaultFramebuffer = function () {
  6590. this._currentRenderTarget = null;
  6591. this.bindUnboundFramebuffer(null);
  6592. this.setViewport(this._cachedViewport);
  6593. this.wipeCaches();
  6594. };
  6595. // VBOs
  6596. Engine.prototype._resetVertexBufferBinding = function () {
  6597. this.bindArrayBuffer(null);
  6598. this._cachedVertexBuffers = null;
  6599. };
  6600. Engine.prototype.createVertexBuffer = function (vertices) {
  6601. var vbo = this._gl.createBuffer();
  6602. this.bindArrayBuffer(vbo);
  6603. if (vertices instanceof Float32Array) {
  6604. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  6605. }
  6606. else {
  6607. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  6608. }
  6609. this._resetVertexBufferBinding();
  6610. vbo.references = 1;
  6611. return vbo;
  6612. };
  6613. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  6614. var vbo = this._gl.createBuffer();
  6615. this.bindArrayBuffer(vbo);
  6616. if (vertices instanceof Float32Array) {
  6617. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  6618. }
  6619. else {
  6620. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  6621. }
  6622. this._resetVertexBufferBinding();
  6623. vbo.references = 1;
  6624. return vbo;
  6625. };
  6626. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  6627. this.bindArrayBuffer(vertexBuffer);
  6628. if (offset === undefined) {
  6629. offset = 0;
  6630. }
  6631. if (count === undefined) {
  6632. if (vertices instanceof Float32Array) {
  6633. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6634. }
  6635. else {
  6636. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6637. }
  6638. }
  6639. else {
  6640. if (vertices instanceof Float32Array) {
  6641. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  6642. }
  6643. else {
  6644. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  6645. }
  6646. }
  6647. this._resetVertexBufferBinding();
  6648. };
  6649. Engine.prototype._resetIndexBufferBinding = function () {
  6650. this.bindIndexBuffer(null);
  6651. this._cachedIndexBuffer = null;
  6652. };
  6653. Engine.prototype.createIndexBuffer = function (indices) {
  6654. var vbo = this._gl.createBuffer();
  6655. this.bindIndexBuffer(vbo);
  6656. // Check for 32 bits indices
  6657. var arrayBuffer;
  6658. var need32Bits = false;
  6659. if (this._caps.uintIndices) {
  6660. for (var index = 0; index < indices.length; index++) {
  6661. if (indices[index] > 65535) {
  6662. need32Bits = true;
  6663. break;
  6664. }
  6665. }
  6666. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6667. }
  6668. else {
  6669. arrayBuffer = new Uint16Array(indices);
  6670. }
  6671. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6672. this._resetIndexBufferBinding();
  6673. vbo.references = 1;
  6674. vbo.is32Bits = need32Bits;
  6675. return vbo;
  6676. };
  6677. Engine.prototype.bindArrayBuffer = function (buffer) {
  6678. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  6679. };
  6680. Engine.prototype.bindIndexBuffer = function (buffer) {
  6681. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  6682. };
  6683. Engine.prototype.bindBuffer = function (buffer, target) {
  6684. if (this._currentBoundBuffer[target] !== buffer) {
  6685. this._gl.bindBuffer(target, buffer);
  6686. this._currentBoundBuffer[target] = buffer;
  6687. }
  6688. };
  6689. Engine.prototype.updateArrayBuffer = function (data) {
  6690. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6691. };
  6692. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  6693. var pointer = this._currentBufferPointers[indx];
  6694. var changed = false;
  6695. if (!pointer) {
  6696. changed = true;
  6697. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  6698. }
  6699. else {
  6700. if (pointer.buffer !== buffer) {
  6701. pointer.buffer = buffer;
  6702. changed = true;
  6703. }
  6704. if (pointer.size !== size) {
  6705. pointer.size = size;
  6706. changed = true;
  6707. }
  6708. if (pointer.type !== type) {
  6709. pointer.type = type;
  6710. changed = true;
  6711. }
  6712. if (pointer.normalized !== normalized) {
  6713. pointer.normalized = normalized;
  6714. changed = true;
  6715. }
  6716. if (pointer.stride !== stride) {
  6717. pointer.stride = stride;
  6718. changed = true;
  6719. }
  6720. if (pointer.offset !== offset) {
  6721. pointer.offset = offset;
  6722. changed = true;
  6723. }
  6724. }
  6725. if (changed) {
  6726. this.bindArrayBuffer(buffer);
  6727. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  6728. }
  6729. };
  6730. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6731. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6732. this._cachedVertexBuffers = vertexBuffer;
  6733. this._cachedEffectForVertexBuffers = effect;
  6734. var offset = 0;
  6735. for (var index = 0; index < vertexDeclaration.length; index++) {
  6736. var order = effect.getAttributeLocation(index);
  6737. if (order >= 0) {
  6738. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6739. }
  6740. offset += vertexDeclaration[index] * 4;
  6741. }
  6742. }
  6743. if (this._cachedIndexBuffer !== indexBuffer) {
  6744. this._cachedIndexBuffer = indexBuffer;
  6745. this.bindIndexBuffer(indexBuffer);
  6746. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6747. }
  6748. };
  6749. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  6750. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6751. this._cachedVertexBuffers = vertexBuffers;
  6752. this._cachedEffectForVertexBuffers = effect;
  6753. var attributes = effect.getAttributesNames();
  6754. for (var index = 0; index < attributes.length; index++) {
  6755. var order = effect.getAttributeLocation(index);
  6756. if (order >= 0) {
  6757. var vertexBuffer = vertexBuffers[attributes[index]];
  6758. if (!vertexBuffer) {
  6759. continue;
  6760. }
  6761. var buffer = vertexBuffer.getBuffer();
  6762. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  6763. if (vertexBuffer.getIsInstanced()) {
  6764. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  6765. this._currentInstanceLocations.push(order);
  6766. this._currentInstanceBuffers.push(buffer);
  6767. }
  6768. }
  6769. }
  6770. }
  6771. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6772. this._cachedIndexBuffer = indexBuffer;
  6773. this.bindIndexBuffer(indexBuffer);
  6774. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6775. }
  6776. };
  6777. Engine.prototype.unbindInstanceAttributes = function () {
  6778. var boundBuffer;
  6779. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  6780. var instancesBuffer = this._currentInstanceBuffers[i];
  6781. if (boundBuffer != instancesBuffer) {
  6782. boundBuffer = instancesBuffer;
  6783. this.bindArrayBuffer(instancesBuffer);
  6784. }
  6785. var offsetLocation = this._currentInstanceLocations[i];
  6786. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6787. }
  6788. this._currentInstanceBuffers.length = 0;
  6789. this._currentInstanceLocations.length = 0;
  6790. };
  6791. Engine.prototype._releaseBuffer = function (buffer) {
  6792. buffer.references--;
  6793. if (buffer.references === 0) {
  6794. this._gl.deleteBuffer(buffer);
  6795. return true;
  6796. }
  6797. return false;
  6798. };
  6799. Engine.prototype.createInstancesBuffer = function (capacity) {
  6800. var buffer = this._gl.createBuffer();
  6801. buffer.capacity = capacity;
  6802. this.bindArrayBuffer(buffer);
  6803. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6804. return buffer;
  6805. };
  6806. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6807. this._gl.deleteBuffer(buffer);
  6808. };
  6809. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6810. this.bindArrayBuffer(instancesBuffer);
  6811. if (data) {
  6812. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6813. }
  6814. if (offsetLocations[0].index !== undefined) {
  6815. var stride = 0;
  6816. for (var i = 0; i < offsetLocations.length; i++) {
  6817. var ai = offsetLocations[i];
  6818. stride += ai.attributeSize * 4;
  6819. }
  6820. for (var i = 0; i < offsetLocations.length; i++) {
  6821. var ai = offsetLocations[i];
  6822. this._gl.enableVertexAttribArray(ai.index);
  6823. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  6824. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  6825. this._currentInstanceLocations.push(ai.index);
  6826. this._currentInstanceBuffers.push(instancesBuffer);
  6827. }
  6828. }
  6829. else {
  6830. for (var index = 0; index < 4; index++) {
  6831. var offsetLocation = offsetLocations[index];
  6832. this._gl.enableVertexAttribArray(offsetLocation);
  6833. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6834. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6835. this._currentInstanceLocations.push(offsetLocation);
  6836. this._currentInstanceBuffers.push(instancesBuffer);
  6837. }
  6838. }
  6839. };
  6840. Engine.prototype.applyStates = function () {
  6841. this._depthCullingState.apply(this._gl);
  6842. this._alphaState.apply(this._gl);
  6843. };
  6844. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6845. // Apply states
  6846. this.applyStates();
  6847. this._drawCalls.addCount(1, false);
  6848. // Render
  6849. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6850. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6851. if (instancesCount) {
  6852. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6853. return;
  6854. }
  6855. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6856. };
  6857. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6858. // Apply states
  6859. this.applyStates();
  6860. this._drawCalls.addCount(1, false);
  6861. if (instancesCount) {
  6862. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6863. return;
  6864. }
  6865. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6866. };
  6867. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6868. // Apply states
  6869. this.applyStates();
  6870. this._drawCalls.addCount(1, false);
  6871. if (instancesCount) {
  6872. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6873. return;
  6874. }
  6875. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6876. };
  6877. // Shaders
  6878. Engine.prototype._releaseEffect = function (effect) {
  6879. if (this._compiledEffects[effect._key]) {
  6880. delete this._compiledEffects[effect._key];
  6881. if (effect.getProgram()) {
  6882. this._gl.deleteProgram(effect.getProgram());
  6883. }
  6884. }
  6885. };
  6886. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  6887. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6888. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6889. var name = vertex + "+" + fragment + "@" + defines;
  6890. if (this._compiledEffects[name]) {
  6891. return this._compiledEffects[name];
  6892. }
  6893. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  6894. effect._key = name;
  6895. this._compiledEffects[name] = effect;
  6896. return effect;
  6897. };
  6898. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6899. if (uniformsNames === void 0) { uniformsNames = []; }
  6900. if (samplers === void 0) { samplers = []; }
  6901. if (defines === void 0) { defines = ""; }
  6902. return this.createEffect({
  6903. vertex: "particles",
  6904. fragmentElement: fragmentName
  6905. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6906. };
  6907. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  6908. context = context || this._gl;
  6909. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  6910. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  6911. var shaderProgram = context.createProgram();
  6912. context.attachShader(shaderProgram, vertexShader);
  6913. context.attachShader(shaderProgram, fragmentShader);
  6914. context.linkProgram(shaderProgram);
  6915. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  6916. if (!linked) {
  6917. var error = context.getProgramInfoLog(shaderProgram);
  6918. if (error) {
  6919. throw new Error(error);
  6920. }
  6921. }
  6922. context.deleteShader(vertexShader);
  6923. context.deleteShader(fragmentShader);
  6924. return shaderProgram;
  6925. };
  6926. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6927. var results = [];
  6928. for (var index = 0; index < uniformsNames.length; index++) {
  6929. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6930. }
  6931. return results;
  6932. };
  6933. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6934. var results = [];
  6935. for (var index = 0; index < attributesNames.length; index++) {
  6936. try {
  6937. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6938. }
  6939. catch (e) {
  6940. results.push(-1);
  6941. }
  6942. }
  6943. return results;
  6944. };
  6945. Engine.prototype.enableEffect = function (effect) {
  6946. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6947. if (effect && effect.onBind) {
  6948. effect.onBind(effect);
  6949. }
  6950. return;
  6951. }
  6952. this._vertexAttribArraysToUse = this._vertexAttribArraysToUse || [];
  6953. this._vertexAttribArraysEnabled = this._vertexAttribArraysEnabled || [];
  6954. // Use program
  6955. this.setProgram(effect.getProgram());
  6956. var i, ul;
  6957. for (i = 0, ul = this._vertexAttribArraysToUse.length; i < ul; i++) {
  6958. this._vertexAttribArraysToUse[i] = false;
  6959. }
  6960. var attributesCount = effect.getAttributesCount();
  6961. for (i = 0; i < attributesCount; i++) {
  6962. // Attributes
  6963. var order = effect.getAttributeLocation(i);
  6964. if (order >= 0) {
  6965. this._vertexAttribArraysToUse[order] = true;
  6966. }
  6967. }
  6968. for (i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  6969. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArraysEnabled[i] || this._vertexAttribArraysToUse[i]) {
  6970. continue;
  6971. }
  6972. this._vertexAttribArraysEnabled[i] = false;
  6973. this._gl.disableVertexAttribArray(i);
  6974. }
  6975. for (i = 0, ul = this._vertexAttribArraysToUse.length; i < ul; i++) {
  6976. if (this._vertexAttribArraysToUse[i] && !this._vertexAttribArraysEnabled[i]) {
  6977. this._vertexAttribArraysEnabled[i] = true;
  6978. this._gl.enableVertexAttribArray(i);
  6979. }
  6980. }
  6981. this._currentEffect = effect;
  6982. if (effect.onBind) {
  6983. effect.onBind(effect);
  6984. }
  6985. };
  6986. Engine.prototype.setArray = function (uniform, array) {
  6987. if (!uniform)
  6988. return;
  6989. this._gl.uniform1fv(uniform, array);
  6990. };
  6991. Engine.prototype.setArray2 = function (uniform, array) {
  6992. if (!uniform || array.length % 2 !== 0)
  6993. return;
  6994. this._gl.uniform2fv(uniform, array);
  6995. };
  6996. Engine.prototype.setArray3 = function (uniform, array) {
  6997. if (!uniform || array.length % 3 !== 0)
  6998. return;
  6999. this._gl.uniform3fv(uniform, array);
  7000. };
  7001. Engine.prototype.setArray4 = function (uniform, array) {
  7002. if (!uniform || array.length % 4 !== 0)
  7003. return;
  7004. this._gl.uniform4fv(uniform, array);
  7005. };
  7006. Engine.prototype.setMatrices = function (uniform, matrices) {
  7007. if (!uniform)
  7008. return;
  7009. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7010. };
  7011. Engine.prototype.setMatrix = function (uniform, matrix) {
  7012. if (!uniform)
  7013. return;
  7014. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7015. };
  7016. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7017. if (!uniform)
  7018. return;
  7019. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7020. };
  7021. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7022. if (!uniform)
  7023. return;
  7024. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7025. };
  7026. Engine.prototype.setFloat = function (uniform, value) {
  7027. if (!uniform)
  7028. return;
  7029. this._gl.uniform1f(uniform, value);
  7030. };
  7031. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7032. if (!uniform)
  7033. return;
  7034. this._gl.uniform2f(uniform, x, y);
  7035. };
  7036. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7037. if (!uniform)
  7038. return;
  7039. this._gl.uniform3f(uniform, x, y, z);
  7040. };
  7041. Engine.prototype.setBool = function (uniform, bool) {
  7042. if (!uniform)
  7043. return;
  7044. this._gl.uniform1i(uniform, bool);
  7045. };
  7046. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7047. if (!uniform)
  7048. return;
  7049. this._gl.uniform4f(uniform, x, y, z, w);
  7050. };
  7051. Engine.prototype.setColor3 = function (uniform, color3) {
  7052. if (!uniform)
  7053. return;
  7054. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7055. };
  7056. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7057. if (!uniform)
  7058. return;
  7059. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7060. };
  7061. // States
  7062. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7063. if (zOffset === void 0) { zOffset = 0; }
  7064. if (reverseSide === void 0) { reverseSide = false; }
  7065. // Culling
  7066. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7067. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7068. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7069. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7070. if (culling) {
  7071. this._depthCullingState.cullFace = cullFace;
  7072. this._depthCullingState.cull = true;
  7073. }
  7074. else {
  7075. this._depthCullingState.cull = false;
  7076. }
  7077. }
  7078. // Z offset
  7079. this._depthCullingState.zOffset = zOffset;
  7080. };
  7081. Engine.prototype.setDepthBuffer = function (enable) {
  7082. this._depthCullingState.depthTest = enable;
  7083. };
  7084. Engine.prototype.getDepthWrite = function () {
  7085. return this._depthCullingState.depthMask;
  7086. };
  7087. Engine.prototype.setDepthWrite = function (enable) {
  7088. this._depthCullingState.depthMask = enable;
  7089. };
  7090. Engine.prototype.setColorWrite = function (enable) {
  7091. this._gl.colorMask(enable, enable, enable, enable);
  7092. };
  7093. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7094. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7095. if (this._alphaMode === mode) {
  7096. return;
  7097. }
  7098. switch (mode) {
  7099. case Engine.ALPHA_DISABLE:
  7100. this._alphaState.alphaBlend = false;
  7101. break;
  7102. case Engine.ALPHA_COMBINE:
  7103. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7104. this._alphaState.alphaBlend = true;
  7105. break;
  7106. case Engine.ALPHA_ONEONE:
  7107. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7108. this._alphaState.alphaBlend = true;
  7109. break;
  7110. case Engine.ALPHA_ADD:
  7111. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7112. this._alphaState.alphaBlend = true;
  7113. break;
  7114. case Engine.ALPHA_SUBTRACT:
  7115. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7116. this._alphaState.alphaBlend = true;
  7117. break;
  7118. case Engine.ALPHA_MULTIPLY:
  7119. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7120. this._alphaState.alphaBlend = true;
  7121. break;
  7122. case Engine.ALPHA_MAXIMIZED:
  7123. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7124. this._alphaState.alphaBlend = true;
  7125. break;
  7126. }
  7127. if (!noDepthWriteChange) {
  7128. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7129. }
  7130. this._alphaMode = mode;
  7131. };
  7132. Engine.prototype.getAlphaMode = function () {
  7133. return this._alphaMode;
  7134. };
  7135. Engine.prototype.setAlphaTesting = function (enable) {
  7136. this._alphaTest = enable;
  7137. };
  7138. Engine.prototype.getAlphaTesting = function () {
  7139. return this._alphaTest;
  7140. };
  7141. // Textures
  7142. Engine.prototype.wipeCaches = function () {
  7143. this.resetTextureCache();
  7144. this._currentEffect = null;
  7145. this._depthCullingState.reset();
  7146. this.setDepthFunctionToLessOrEqual();
  7147. this._alphaState.reset();
  7148. this._cachedVertexBuffers = null;
  7149. this._cachedIndexBuffer = null;
  7150. this._cachedEffectForVertexBuffers = null;
  7151. };
  7152. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  7153. var gl = this._gl;
  7154. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7155. var magFilter = gl.NEAREST;
  7156. var minFilter = gl.NEAREST;
  7157. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7158. magFilter = gl.LINEAR;
  7159. minFilter = gl.LINEAR;
  7160. }
  7161. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7162. magFilter = gl.LINEAR;
  7163. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7164. }
  7165. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  7166. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  7167. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7168. texture.samplingMode = samplingMode;
  7169. };
  7170. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  7171. var _this = this;
  7172. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7173. if (onLoad === void 0) { onLoad = null; }
  7174. if (onError === void 0) { onError = null; }
  7175. if (buffer === void 0) { buffer = null; }
  7176. var texture = this._gl.createTexture();
  7177. var extension;
  7178. var fromData = false;
  7179. if (url.substr(0, 5) === "data:") {
  7180. fromData = true;
  7181. }
  7182. if (!fromData)
  7183. extension = url.substr(url.length - 4, 4).toLowerCase();
  7184. else {
  7185. var oldUrl = url;
  7186. fromData = oldUrl.split(':');
  7187. url = oldUrl;
  7188. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  7189. }
  7190. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7191. var isTGA = (extension === ".tga");
  7192. scene._addPendingData(texture);
  7193. texture.url = url;
  7194. texture.noMipmap = noMipmap;
  7195. texture.references = 1;
  7196. texture.samplingMode = samplingMode;
  7197. this._loadedTexturesCache.push(texture);
  7198. var onerror = function () {
  7199. scene._removePendingData(texture);
  7200. if (onError) {
  7201. onError();
  7202. }
  7203. };
  7204. var callback;
  7205. if (isTGA) {
  7206. callback = function (arrayBuffer) {
  7207. var data = new Uint8Array(arrayBuffer);
  7208. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  7209. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  7210. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  7211. }, onLoad, samplingMode);
  7212. };
  7213. if (!(fromData instanceof Array))
  7214. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  7215. callback(arrayBuffer);
  7216. }, onerror, scene.database, true);
  7217. else
  7218. callback(buffer);
  7219. }
  7220. else if (isDDS) {
  7221. callback = function (data) {
  7222. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7223. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  7224. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  7225. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  7226. }, onLoad, samplingMode);
  7227. };
  7228. if (!(fromData instanceof Array))
  7229. BABYLON.Tools.LoadFile(url, function (data) {
  7230. callback(data);
  7231. }, onerror, scene.database, true);
  7232. else
  7233. callback(buffer);
  7234. }
  7235. else {
  7236. var onload = function (img) {
  7237. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  7238. var isPot = (img.width === potWidth && img.height === potHeight);
  7239. if (!isPot) {
  7240. _this._prepareWorkingCanvas();
  7241. _this._workingCanvas.width = potWidth;
  7242. _this._workingCanvas.height = potHeight;
  7243. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7244. _this._workingContext.imageSmoothingEnabled = false;
  7245. _this._workingContext.mozImageSmoothingEnabled = false;
  7246. _this._workingContext.oImageSmoothingEnabled = false;
  7247. _this._workingContext.webkitImageSmoothingEnabled = false;
  7248. _this._workingContext.msImageSmoothingEnabled = false;
  7249. }
  7250. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  7251. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7252. _this._workingContext.imageSmoothingEnabled = true;
  7253. _this._workingContext.mozImageSmoothingEnabled = true;
  7254. _this._workingContext.oImageSmoothingEnabled = true;
  7255. _this._workingContext.webkitImageSmoothingEnabled = true;
  7256. _this._workingContext.msImageSmoothingEnabled = true;
  7257. }
  7258. }
  7259. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  7260. }, onLoad, samplingMode);
  7261. };
  7262. if (!(fromData instanceof Array))
  7263. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7264. else
  7265. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  7266. }
  7267. return texture;
  7268. };
  7269. Engine.prototype._getInternalFormat = function (format) {
  7270. var internalFormat = this._gl.RGBA;
  7271. switch (format) {
  7272. case Engine.TEXTUREFORMAT_ALPHA:
  7273. internalFormat = this._gl.ALPHA;
  7274. break;
  7275. case Engine.TEXTUREFORMAT_LUMINANCE:
  7276. internalFormat = this._gl.LUMINANCE;
  7277. break;
  7278. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  7279. internalFormat = this._gl.LUMINANCE_ALPHA;
  7280. break;
  7281. case Engine.TEXTUREFORMAT_RGB:
  7282. internalFormat = this._gl.RGB;
  7283. break;
  7284. case Engine.TEXTUREFORMAT_RGBA:
  7285. internalFormat = this._gl.RGBA;
  7286. break;
  7287. }
  7288. return internalFormat;
  7289. };
  7290. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  7291. if (compression === void 0) { compression = null; }
  7292. var internalFormat = this._getInternalFormat(format);
  7293. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7294. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7295. if (texture._width % 4 !== 0) {
  7296. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  7297. }
  7298. if (compression) {
  7299. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  7300. }
  7301. else {
  7302. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  7303. }
  7304. if (texture.generateMipMaps) {
  7305. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7306. }
  7307. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7308. this.resetTextureCache();
  7309. texture.isReady = true;
  7310. };
  7311. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  7312. if (compression === void 0) { compression = null; }
  7313. var texture = this._gl.createTexture();
  7314. texture._baseWidth = width;
  7315. texture._baseHeight = height;
  7316. texture._width = width;
  7317. texture._height = height;
  7318. texture.references = 1;
  7319. this.updateRawTexture(texture, data, format, invertY, compression);
  7320. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7321. // Filters
  7322. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  7323. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7324. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7325. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7326. texture.samplingMode = samplingMode;
  7327. this._loadedTexturesCache.push(texture);
  7328. return texture;
  7329. };
  7330. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  7331. var texture = this._gl.createTexture();
  7332. texture._baseWidth = width;
  7333. texture._baseHeight = height;
  7334. if (generateMipMaps) {
  7335. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  7336. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  7337. }
  7338. this.resetTextureCache();
  7339. texture._width = width;
  7340. texture._height = height;
  7341. texture.isReady = false;
  7342. texture.generateMipMaps = generateMipMaps;
  7343. texture.references = 1;
  7344. texture.samplingMode = samplingMode;
  7345. this.updateTextureSamplingMode(samplingMode, texture);
  7346. this._loadedTexturesCache.push(texture);
  7347. return texture;
  7348. };
  7349. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  7350. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  7351. if (texture.isCube) {
  7352. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  7353. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7354. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7355. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  7356. }
  7357. else {
  7358. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7359. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7360. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7361. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7362. }
  7363. };
  7364. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  7365. if (premulAlpha === void 0) { premulAlpha = false; }
  7366. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7367. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  7368. if (premulAlpha) {
  7369. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  7370. }
  7371. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  7372. if (texture.generateMipMaps) {
  7373. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7374. }
  7375. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7376. this.resetTextureCache();
  7377. texture.isReady = true;
  7378. };
  7379. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  7380. if (texture._isDisabled) {
  7381. return;
  7382. }
  7383. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7384. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  7385. try {
  7386. // Testing video texture support
  7387. if (this._videoTextureSupported === undefined) {
  7388. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7389. if (this._gl.getError() !== 0) {
  7390. this._videoTextureSupported = false;
  7391. }
  7392. else {
  7393. this._videoTextureSupported = true;
  7394. }
  7395. }
  7396. // Copy video through the current working canvas if video texture is not supported
  7397. if (!this._videoTextureSupported) {
  7398. if (!texture._workingCanvas) {
  7399. texture._workingCanvas = document.createElement("canvas");
  7400. texture._workingContext = texture._workingCanvas.getContext("2d");
  7401. texture._workingCanvas.width = texture._width;
  7402. texture._workingCanvas.height = texture._height;
  7403. }
  7404. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  7405. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  7406. }
  7407. else {
  7408. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7409. }
  7410. if (texture.generateMipMaps) {
  7411. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7412. }
  7413. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7414. this.resetTextureCache();
  7415. texture.isReady = true;
  7416. }
  7417. catch (ex) {
  7418. // Something unexpected
  7419. // Let's disable the texture
  7420. texture._isDisabled = true;
  7421. }
  7422. };
  7423. Engine.prototype.createRenderTargetTexture = function (size, options) {
  7424. // old version had a "generateMipMaps" arg instead of options.
  7425. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  7426. // in the same way, generateDepthBuffer is defaulted to true
  7427. var generateMipMaps = false;
  7428. var generateDepthBuffer = true;
  7429. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7430. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7431. if (options !== undefined) {
  7432. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7433. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  7434. type = options.type === undefined ? type : options.type;
  7435. if (options.samplingMode !== undefined) {
  7436. samplingMode = options.samplingMode;
  7437. }
  7438. if (type === BABYLON.Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  7439. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  7440. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  7441. }
  7442. else if (type === BABYLON.Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  7443. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  7444. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  7445. }
  7446. }
  7447. var gl = this._gl;
  7448. var texture = gl.createTexture();
  7449. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7450. var width = size.width || size;
  7451. var height = size.height || size;
  7452. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7453. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  7454. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7455. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  7456. }
  7457. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7458. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7459. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7460. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7461. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  7462. var depthBuffer;
  7463. // Create the depth buffer
  7464. if (generateDepthBuffer) {
  7465. depthBuffer = gl.createRenderbuffer();
  7466. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  7467. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  7468. }
  7469. // Create the framebuffer
  7470. var framebuffer = gl.createFramebuffer();
  7471. this.bindUnboundFramebuffer(framebuffer);
  7472. if (generateDepthBuffer) {
  7473. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  7474. }
  7475. if (generateMipMaps) {
  7476. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7477. }
  7478. // Unbind
  7479. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7480. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7481. this.bindUnboundFramebuffer(null);
  7482. texture._framebuffer = framebuffer;
  7483. if (generateDepthBuffer) {
  7484. texture._depthBuffer = depthBuffer;
  7485. }
  7486. texture._baseWidth = width;
  7487. texture._baseHeight = height;
  7488. texture._width = width;
  7489. texture._height = height;
  7490. texture.isReady = true;
  7491. texture.generateMipMaps = generateMipMaps;
  7492. texture.references = 1;
  7493. texture.samplingMode = samplingMode;
  7494. texture.type = type;
  7495. this.resetTextureCache();
  7496. this._loadedTexturesCache.push(texture);
  7497. return texture;
  7498. };
  7499. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  7500. var gl = this._gl;
  7501. var texture = gl.createTexture();
  7502. var generateMipMaps = true;
  7503. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7504. if (options !== undefined) {
  7505. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7506. if (options.samplingMode !== undefined) {
  7507. samplingMode = options.samplingMode;
  7508. }
  7509. }
  7510. texture.isCube = true;
  7511. texture.references = 1;
  7512. texture.generateMipMaps = generateMipMaps;
  7513. texture.references = 1;
  7514. texture.samplingMode = samplingMode;
  7515. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7516. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7517. for (var face = 0; face < 6; face++) {
  7518. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  7519. }
  7520. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  7521. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  7522. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7523. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7524. // Create the depth buffer
  7525. var depthBuffer = gl.createRenderbuffer();
  7526. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  7527. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  7528. // Create the framebuffer
  7529. var framebuffer = gl.createFramebuffer();
  7530. this.bindUnboundFramebuffer(framebuffer);
  7531. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  7532. // Mipmaps
  7533. if (texture.generateMipMaps) {
  7534. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7535. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7536. }
  7537. // Unbind
  7538. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7539. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7540. this.bindUnboundFramebuffer(null);
  7541. texture._framebuffer = framebuffer;
  7542. texture._depthBuffer = depthBuffer;
  7543. this.resetTextureCache();
  7544. texture._width = size;
  7545. texture._height = size;
  7546. texture.isReady = true;
  7547. return texture;
  7548. };
  7549. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  7550. var _this = this;
  7551. var gl = this._gl;
  7552. var texture = gl.createTexture();
  7553. texture.isCube = true;
  7554. texture.url = rootUrl;
  7555. texture.references = 1;
  7556. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  7557. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7558. if (isDDS) {
  7559. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  7560. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7561. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  7562. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7563. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  7564. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  7565. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  7566. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7567. }
  7568. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7569. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  7570. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7571. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7572. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7573. _this.resetTextureCache();
  7574. texture._width = info.width;
  7575. texture._height = info.height;
  7576. texture.isReady = true;
  7577. }, null, null, true);
  7578. }
  7579. else {
  7580. cascadeLoad(rootUrl, scene, function (imgs) {
  7581. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  7582. var height = width;
  7583. _this._prepareWorkingCanvas();
  7584. _this._workingCanvas.width = width;
  7585. _this._workingCanvas.height = height;
  7586. var faces = [
  7587. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  7588. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  7589. ];
  7590. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7591. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  7592. for (var index = 0; index < faces.length; index++) {
  7593. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  7594. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  7595. }
  7596. if (!noMipmap) {
  7597. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7598. }
  7599. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7600. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  7601. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7602. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7603. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7604. _this.resetTextureCache();
  7605. texture._width = width;
  7606. texture._height = height;
  7607. texture.isReady = true;
  7608. }, files);
  7609. }
  7610. return texture;
  7611. };
  7612. Engine.prototype.updateTextureSize = function (texture, width, height) {
  7613. texture._width = width;
  7614. texture._height = height;
  7615. texture._size = width * height;
  7616. texture._baseWidth = width;
  7617. texture._baseHeight = height;
  7618. };
  7619. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  7620. var _this = this;
  7621. var gl = this._gl;
  7622. var texture = gl.createTexture();
  7623. scene._addPendingData(texture);
  7624. texture.isCube = true;
  7625. texture.references = 1;
  7626. texture.url = url;
  7627. var internalFormat = this._getInternalFormat(format);
  7628. var textureType = gl.UNSIGNED_BYTE;
  7629. if (type === Engine.TEXTURETYPE_FLOAT) {
  7630. textureType = gl.FLOAT;
  7631. }
  7632. var width = size;
  7633. var height = width;
  7634. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  7635. texture._width = width;
  7636. texture._height = height;
  7637. var onerror = function () {
  7638. scene._removePendingData(texture);
  7639. };
  7640. var internalCallback = function (data) {
  7641. var rgbeDataArrays = callback(data);
  7642. var facesIndex = [
  7643. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  7644. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  7645. ];
  7646. width = texture._width;
  7647. height = texture._height;
  7648. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  7649. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7650. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  7651. if (!noMipmap && isPot) {
  7652. if (mipmmapGenerator) {
  7653. var arrayTemp = [];
  7654. // Data are known to be in +X +Y +Z -X -Y -Z
  7655. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  7656. arrayTemp.push(rgbeDataArrays[0]); // +X
  7657. arrayTemp.push(rgbeDataArrays[3]); // -X
  7658. arrayTemp.push(rgbeDataArrays[1]); // +Y
  7659. arrayTemp.push(rgbeDataArrays[4]); // -Y
  7660. arrayTemp.push(rgbeDataArrays[2]); // +Z
  7661. arrayTemp.push(rgbeDataArrays[5]); // -Z
  7662. var mipData = mipmmapGenerator(arrayTemp);
  7663. for (var level = 0; level < mipData.length; level++) {
  7664. var mipSize = width >> level;
  7665. // mipData is order in +X -X +Y -Y +Z -Z
  7666. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  7667. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  7668. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  7669. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  7670. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  7671. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  7672. }
  7673. }
  7674. else {
  7675. // Data are known to be in +X +Y +Z -X -Y -Z
  7676. for (var index = 0; index < facesIndex.length; index++) {
  7677. var faceData = rgbeDataArrays[index];
  7678. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  7679. }
  7680. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7681. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  7682. // By following the webgl standard changes from Revision 7, 2014/11/24
  7683. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  7684. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  7685. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  7686. // Data are known to be in +X +Y +Z -X -Y -Z
  7687. for (var index = 0; index < facesIndex.length; index++) {
  7688. var faceData = rgbeDataArrays[index];
  7689. // Create a new RGBA Face.
  7690. var newFaceData = new Float32Array(width * height * 4);
  7691. for (var x = 0; x < width; x++) {
  7692. for (var y = 0; y < height; y++) {
  7693. var index_1 = (y * width + x) * 3;
  7694. var newIndex = (y * width + x) * 4;
  7695. // Map Old Value to new value.
  7696. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  7697. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  7698. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  7699. // Add fully opaque alpha channel.
  7700. newFaceData[newIndex + 3] = 1;
  7701. }
  7702. }
  7703. // Reupload the face.
  7704. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  7705. }
  7706. // Try to generate mipmap again.
  7707. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7708. }
  7709. }
  7710. }
  7711. else {
  7712. noMipmap = true;
  7713. }
  7714. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  7715. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  7716. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  7717. }
  7718. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  7719. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  7720. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  7721. }
  7722. else {
  7723. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7724. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  7725. }
  7726. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7727. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7728. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7729. texture.isReady = true;
  7730. _this.resetTextureCache();
  7731. scene._removePendingData(texture);
  7732. };
  7733. BABYLON.Tools.LoadFile(url, function (data) {
  7734. internalCallback(data);
  7735. }, onerror, scene.database, true);
  7736. return texture;
  7737. };
  7738. ;
  7739. Engine.prototype._releaseTexture = function (texture) {
  7740. var gl = this._gl;
  7741. if (texture._framebuffer) {
  7742. gl.deleteFramebuffer(texture._framebuffer);
  7743. }
  7744. if (texture._depthBuffer) {
  7745. gl.deleteRenderbuffer(texture._depthBuffer);
  7746. }
  7747. gl.deleteTexture(texture);
  7748. // Unbind channels
  7749. this.unbindAllTextures();
  7750. var index = this._loadedTexturesCache.indexOf(texture);
  7751. if (index !== -1) {
  7752. this._loadedTexturesCache.splice(index, 1);
  7753. }
  7754. };
  7755. Engine.prototype.setProgram = function (program) {
  7756. if (this._currentProgram !== program) {
  7757. this._gl.useProgram(program);
  7758. this._currentProgram = program;
  7759. }
  7760. };
  7761. Engine.prototype.bindSamplers = function (effect) {
  7762. this.setProgram(effect.getProgram());
  7763. var samplers = effect.getSamplers();
  7764. for (var index = 0; index < samplers.length; index++) {
  7765. var uniform = effect.getUniform(samplers[index]);
  7766. this._gl.uniform1i(uniform, index);
  7767. }
  7768. this._currentEffect = null;
  7769. };
  7770. Engine.prototype.activateTexture = function (texture) {
  7771. if (this._activeTexture !== texture) {
  7772. this._gl.activeTexture(texture);
  7773. this._activeTexture = texture;
  7774. }
  7775. };
  7776. Engine.prototype._bindTextureDirectly = function (target, texture) {
  7777. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  7778. this._gl.bindTexture(target, texture);
  7779. this._activeTexturesCache[this._activeTexture] = texture;
  7780. }
  7781. };
  7782. Engine.prototype._bindTexture = function (channel, texture) {
  7783. if (channel < 0) {
  7784. return;
  7785. }
  7786. this.activateTexture(this._gl["TEXTURE" + channel]);
  7787. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7788. };
  7789. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  7790. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  7791. };
  7792. Engine.prototype.unbindAllTextures = function () {
  7793. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  7794. this.activateTexture(this._gl["TEXTURE" + channel]);
  7795. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7796. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  7797. }
  7798. };
  7799. Engine.prototype.setTexture = function (channel, uniform, texture) {
  7800. if (channel < 0) {
  7801. return;
  7802. }
  7803. this._gl.uniform1i(uniform, channel);
  7804. this._setTexture(channel, texture);
  7805. };
  7806. Engine.prototype._setTexture = function (channel, texture) {
  7807. // Not ready?
  7808. if (!texture || !texture.isReady()) {
  7809. if (this._activeTexturesCache[channel] != null) {
  7810. this.activateTexture(this._gl["TEXTURE" + channel]);
  7811. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7812. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  7813. }
  7814. return;
  7815. }
  7816. // Video
  7817. var alreadyActivated = false;
  7818. if (texture instanceof BABYLON.VideoTexture) {
  7819. this.activateTexture(this._gl["TEXTURE" + channel]);
  7820. alreadyActivated = true;
  7821. texture.update();
  7822. }
  7823. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  7824. texture.delayLoad();
  7825. return;
  7826. }
  7827. var internalTexture = texture.getInternalTexture();
  7828. if (this._activeTexturesCache[channel] === internalTexture) {
  7829. return;
  7830. }
  7831. if (!alreadyActivated) {
  7832. this.activateTexture(this._gl["TEXTURE" + channel]);
  7833. }
  7834. if (internalTexture.isCube) {
  7835. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  7836. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  7837. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  7838. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  7839. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  7840. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  7841. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  7842. }
  7843. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  7844. }
  7845. else {
  7846. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  7847. if (internalTexture._cachedWrapU !== texture.wrapU) {
  7848. internalTexture._cachedWrapU = texture.wrapU;
  7849. switch (texture.wrapU) {
  7850. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7851. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  7852. break;
  7853. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7854. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  7855. break;
  7856. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7857. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  7858. break;
  7859. }
  7860. }
  7861. if (internalTexture._cachedWrapV !== texture.wrapV) {
  7862. internalTexture._cachedWrapV = texture.wrapV;
  7863. switch (texture.wrapV) {
  7864. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7865. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  7866. break;
  7867. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7868. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  7869. break;
  7870. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7871. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  7872. break;
  7873. }
  7874. }
  7875. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  7876. }
  7877. };
  7878. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  7879. if (channel < 0) {
  7880. return;
  7881. }
  7882. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  7883. this._textureUnits = new Int32Array(textures.length);
  7884. }
  7885. for (var i = 0; i < textures.length; i++) {
  7886. this._textureUnits[i] = channel + i;
  7887. }
  7888. this._gl.uniform1iv(uniform, this._textureUnits);
  7889. for (var index = 0; index < textures.length; index++) {
  7890. this._setTexture(channel + index, textures[index]);
  7891. }
  7892. };
  7893. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  7894. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  7895. var value = texture.anisotropicFilteringLevel;
  7896. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7897. value = 1;
  7898. }
  7899. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  7900. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  7901. texture._cachedAnisotropicFilteringLevel = value;
  7902. }
  7903. };
  7904. Engine.prototype.readPixels = function (x, y, width, height) {
  7905. var data = new Uint8Array(height * width * 4);
  7906. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  7907. return data;
  7908. };
  7909. /**
  7910. * Add an externaly attached data from its key.
  7911. * This method call will fail and return false, if such key already exists.
  7912. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  7913. * @param key the unique key that identifies the data
  7914. * @param data the data object to associate to the key for this Engine instance
  7915. * @return true if no such key were already present and the data was added successfully, false otherwise
  7916. */
  7917. Engine.prototype.addExternalData = function (key, data) {
  7918. return this._externalData.add(key, data);
  7919. };
  7920. /**
  7921. * Get an externaly attached data from its key
  7922. * @param key the unique key that identifies the data
  7923. * @return the associated data, if present (can be null), or undefined if not present
  7924. */
  7925. Engine.prototype.getExternalData = function (key) {
  7926. return this._externalData.get(key);
  7927. };
  7928. /**
  7929. * Get an externaly attached data from its key, create it using a factory if it's not already present
  7930. * @param key the unique key that identifies the data
  7931. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  7932. * @return the associated data, can be null if the factory returned null.
  7933. */
  7934. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  7935. return this._externalData.getOrAddWithFactory(key, factory);
  7936. };
  7937. /**
  7938. * Remove an externaly attached data from the Engine instance
  7939. * @param key the unique key that identifies the data
  7940. * @return true if the data was successfully removed, false if it doesn't exist
  7941. */
  7942. Engine.prototype.removeExternalData = function (key) {
  7943. return this._externalData.remove(key);
  7944. };
  7945. Engine.prototype.releaseInternalTexture = function (texture) {
  7946. if (!texture) {
  7947. return;
  7948. }
  7949. texture.references--;
  7950. // Final reference ?
  7951. if (texture.references === 0) {
  7952. var texturesCache = this.getLoadedTexturesCache();
  7953. var index = texturesCache.indexOf(texture);
  7954. if (index > -1) {
  7955. texturesCache.splice(index, 1);
  7956. }
  7957. this._releaseTexture(texture);
  7958. }
  7959. };
  7960. // Dispose
  7961. Engine.prototype.dispose = function () {
  7962. this.hideLoadingUI();
  7963. this.stopRenderLoop();
  7964. // Release scenes
  7965. while (this.scenes.length) {
  7966. this.scenes[0].dispose();
  7967. }
  7968. // Release audio engine
  7969. Engine.audioEngine.dispose();
  7970. // Release effects
  7971. for (var name in this._compiledEffects) {
  7972. this._gl.deleteProgram(this._compiledEffects[name]._program);
  7973. }
  7974. // Unbind
  7975. if (this._vertexAttribArraysEnabled) {
  7976. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  7977. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArraysEnabled[i]) {
  7978. continue;
  7979. }
  7980. this._gl.disableVertexAttribArray(i);
  7981. }
  7982. }
  7983. this._gl = null;
  7984. // Events
  7985. window.removeEventListener("blur", this._onBlur);
  7986. window.removeEventListener("focus", this._onFocus);
  7987. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  7988. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  7989. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  7990. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  7991. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  7992. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  7993. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  7994. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  7995. };
  7996. // Loading screen
  7997. Engine.prototype.displayLoadingUI = function () {
  7998. this._loadingScreen.displayLoadingUI();
  7999. };
  8000. Engine.prototype.hideLoadingUI = function () {
  8001. this._loadingScreen.hideLoadingUI();
  8002. };
  8003. Object.defineProperty(Engine.prototype, "loadingScreen", {
  8004. get: function () {
  8005. return this._loadingScreen;
  8006. },
  8007. set: function (loadingScreen) {
  8008. this._loadingScreen = loadingScreen;
  8009. },
  8010. enumerable: true,
  8011. configurable: true
  8012. });
  8013. Object.defineProperty(Engine.prototype, "loadingUIText", {
  8014. set: function (text) {
  8015. this._loadingScreen.loadingUIText = text;
  8016. },
  8017. enumerable: true,
  8018. configurable: true
  8019. });
  8020. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  8021. set: function (color) {
  8022. this._loadingScreen.loadingUIBackgroundColor = color;
  8023. },
  8024. enumerable: true,
  8025. configurable: true
  8026. });
  8027. // FPS
  8028. Engine.prototype.getFps = function () {
  8029. return this.fps;
  8030. };
  8031. Engine.prototype.getDeltaTime = function () {
  8032. return this.deltaTime;
  8033. };
  8034. Engine.prototype._measureFps = function () {
  8035. this.previousFramesDuration.push(BABYLON.Tools.Now);
  8036. var length = this.previousFramesDuration.length;
  8037. if (length >= 2) {
  8038. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  8039. }
  8040. if (length >= this.fpsRange) {
  8041. if (length > this.fpsRange) {
  8042. this.previousFramesDuration.splice(0, 1);
  8043. length = this.previousFramesDuration.length;
  8044. }
  8045. var sum = 0;
  8046. for (var id = 0; id < length - 1; id++) {
  8047. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  8048. }
  8049. this.fps = 1000.0 / (sum / (length - 1));
  8050. }
  8051. };
  8052. Engine.prototype._canRenderToFloatTexture = function () {
  8053. if (!this.getCaps().textureFloat) {
  8054. return false;
  8055. }
  8056. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  8057. };
  8058. Engine.prototype._canRenderToHalfFloatTexture = function () {
  8059. if (!this.getCaps().textureHalfFloat) {
  8060. return false;
  8061. }
  8062. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  8063. };
  8064. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  8065. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  8066. var tempcanvas = document.createElement("canvas");
  8067. tempcanvas.height = 16;
  8068. tempcanvas.width = 16;
  8069. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  8070. // extension.
  8071. var ext = gl.getExtension(extension);
  8072. // setup GLSL program
  8073. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  8074. 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 }";
  8075. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  8076. gl.useProgram(program);
  8077. // look up where the vertex data needs to go.
  8078. var positionLocation = gl.getAttribLocation(program, "a_position");
  8079. var colorLoc = gl.getUniformLocation(program, "u_color");
  8080. // provide texture coordinates for the rectangle.
  8081. var positionBuffer = gl.createBuffer();
  8082. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  8083. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  8084. -1.0, -1.0,
  8085. 1.0, -1.0,
  8086. -1.0, 1.0,
  8087. -1.0, 1.0,
  8088. 1.0, -1.0,
  8089. 1.0, 1.0]), gl.STATIC_DRAW);
  8090. gl.enableVertexAttribArray(positionLocation);
  8091. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  8092. var whiteTex = gl.createTexture();
  8093. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8094. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  8095. var tex = gl.createTexture();
  8096. gl.bindTexture(gl.TEXTURE_2D, tex);
  8097. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  8098. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8099. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8100. var fb = gl.createFramebuffer();
  8101. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  8102. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  8103. var cleanup = function () {
  8104. gl.deleteProgram(program);
  8105. gl.disableVertexAttribArray(positionLocation);
  8106. gl.deleteBuffer(positionBuffer);
  8107. gl.deleteFramebuffer(fb);
  8108. gl.deleteTexture(whiteTex);
  8109. gl.deleteTexture(tex);
  8110. };
  8111. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  8112. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  8113. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  8114. cleanup();
  8115. return false;
  8116. }
  8117. // Draw the rectangle.
  8118. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8119. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  8120. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8121. gl.bindTexture(gl.TEXTURE_2D, tex);
  8122. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  8123. gl.clearColor(1, 0, 0, 1);
  8124. gl.clear(gl.COLOR_BUFFER_BIT);
  8125. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  8126. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8127. var pixel = new Uint8Array(4);
  8128. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  8129. if (pixel[0] !== 0 ||
  8130. pixel[1] < 248 ||
  8131. pixel[2] < 248 ||
  8132. pixel[3] < 254) {
  8133. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  8134. cleanup();
  8135. return false;
  8136. }
  8137. // Succesfully rendered to "format" texture.
  8138. cleanup();
  8139. return true;
  8140. };
  8141. // Statics
  8142. Engine.isSupported = function () {
  8143. try {
  8144. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  8145. if (navigator.isCocoonJS) {
  8146. return true;
  8147. }
  8148. var tempcanvas = document.createElement("canvas");
  8149. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  8150. return gl != null && !!window.WebGLRenderingContext;
  8151. }
  8152. catch (e) {
  8153. return false;
  8154. }
  8155. };
  8156. // Const statics
  8157. Engine._ALPHA_DISABLE = 0;
  8158. Engine._ALPHA_ADD = 1;
  8159. Engine._ALPHA_COMBINE = 2;
  8160. Engine._ALPHA_SUBTRACT = 3;
  8161. Engine._ALPHA_MULTIPLY = 4;
  8162. Engine._ALPHA_MAXIMIZED = 5;
  8163. Engine._ALPHA_ONEONE = 6;
  8164. Engine._DELAYLOADSTATE_NONE = 0;
  8165. Engine._DELAYLOADSTATE_LOADED = 1;
  8166. Engine._DELAYLOADSTATE_LOADING = 2;
  8167. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  8168. Engine._TEXTUREFORMAT_ALPHA = 0;
  8169. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  8170. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  8171. Engine._TEXTUREFORMAT_RGB = 4;
  8172. Engine._TEXTUREFORMAT_RGBA = 5;
  8173. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  8174. Engine._TEXTURETYPE_FLOAT = 1;
  8175. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  8176. // Updatable statics so stick with vars here
  8177. Engine.CollisionsEpsilon = 0.001;
  8178. Engine.CodeRepository = "src/";
  8179. Engine.ShadersRepository = "src/Shaders/";
  8180. return Engine;
  8181. }());
  8182. BABYLON.Engine = Engine;
  8183. })(BABYLON || (BABYLON = {}));
  8184. var BABYLON;
  8185. (function (BABYLON) {
  8186. /**
  8187. * Node is the basic class for all scene objects (Mesh, Light Camera).
  8188. */
  8189. var Node = (function () {
  8190. /**
  8191. * @constructor
  8192. * @param {string} name - the name and id to be given to this node
  8193. * @param {BABYLON.Scene} the scene this node will be added to
  8194. */
  8195. function Node(name, scene) {
  8196. this.state = "";
  8197. this.animations = new Array();
  8198. this._ranges = {};
  8199. this._childrenFlag = -1;
  8200. this._isEnabled = true;
  8201. this._isReady = true;
  8202. this._currentRenderId = -1;
  8203. this._parentRenderId = -1;
  8204. this.name = name;
  8205. this.id = name;
  8206. this._scene = scene;
  8207. this._initCache();
  8208. }
  8209. Object.defineProperty(Node.prototype, "parent", {
  8210. get: function () {
  8211. return this._parentNode;
  8212. },
  8213. set: function (parent) {
  8214. if (this._parentNode === parent) {
  8215. return;
  8216. }
  8217. if (this._parentNode) {
  8218. var index = this._parentNode._children.indexOf(this);
  8219. if (index !== -1) {
  8220. this._parentNode._children.splice(index, 1);
  8221. }
  8222. }
  8223. this._parentNode = parent;
  8224. if (this._parentNode) {
  8225. if (!this._parentNode._children) {
  8226. this._parentNode._children = new Array();
  8227. }
  8228. this._parentNode._children.push(this);
  8229. }
  8230. },
  8231. enumerable: true,
  8232. configurable: true
  8233. });
  8234. Node.prototype.getScene = function () {
  8235. return this._scene;
  8236. };
  8237. Node.prototype.getEngine = function () {
  8238. return this._scene.getEngine();
  8239. };
  8240. // override it in derived class
  8241. Node.prototype.getWorldMatrix = function () {
  8242. return BABYLON.Matrix.Identity();
  8243. };
  8244. // override it in derived class if you add new variables to the cache
  8245. // and call the parent class method
  8246. Node.prototype._initCache = function () {
  8247. this._cache = {};
  8248. this._cache.parent = undefined;
  8249. };
  8250. Node.prototype.updateCache = function (force) {
  8251. if (!force && this.isSynchronized())
  8252. return;
  8253. this._cache.parent = this.parent;
  8254. this._updateCache();
  8255. };
  8256. // override it in derived class if you add new variables to the cache
  8257. // and call the parent class method if !ignoreParentClass
  8258. Node.prototype._updateCache = function (ignoreParentClass) {
  8259. };
  8260. // override it in derived class if you add new variables to the cache
  8261. Node.prototype._isSynchronized = function () {
  8262. return true;
  8263. };
  8264. Node.prototype._markSyncedWithParent = function () {
  8265. this._parentRenderId = this.parent._currentRenderId;
  8266. };
  8267. Node.prototype.isSynchronizedWithParent = function () {
  8268. if (!this.parent) {
  8269. return true;
  8270. }
  8271. if (this._parentRenderId !== this.parent._currentRenderId) {
  8272. return false;
  8273. }
  8274. return this.parent.isSynchronized();
  8275. };
  8276. Node.prototype.isSynchronized = function (updateCache) {
  8277. var check = this.hasNewParent();
  8278. check = check || !this.isSynchronizedWithParent();
  8279. check = check || !this._isSynchronized();
  8280. if (updateCache)
  8281. this.updateCache(true);
  8282. return !check;
  8283. };
  8284. Node.prototype.hasNewParent = function (update) {
  8285. if (this._cache.parent === this.parent)
  8286. return false;
  8287. if (update)
  8288. this._cache.parent = this.parent;
  8289. return true;
  8290. };
  8291. /**
  8292. * Is this node ready to be used/rendered
  8293. * @return {boolean} is it ready
  8294. */
  8295. Node.prototype.isReady = function () {
  8296. return this._isReady;
  8297. };
  8298. /**
  8299. * Is this node enabled.
  8300. * If the node has a parent and is enabled, the parent will be inspected as well.
  8301. * @return {boolean} whether this node (and its parent) is enabled.
  8302. * @see setEnabled
  8303. */
  8304. Node.prototype.isEnabled = function () {
  8305. if (!this._isEnabled) {
  8306. return false;
  8307. }
  8308. if (this.parent) {
  8309. return this.parent.isEnabled();
  8310. }
  8311. return true;
  8312. };
  8313. /**
  8314. * Set the enabled state of this node.
  8315. * @param {boolean} value - the new enabled state
  8316. * @see isEnabled
  8317. */
  8318. Node.prototype.setEnabled = function (value) {
  8319. this._isEnabled = value;
  8320. };
  8321. /**
  8322. * Is this node a descendant of the given node.
  8323. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  8324. * @param {BABYLON.Node} ancestor - The parent node to inspect
  8325. * @see parent
  8326. */
  8327. Node.prototype.isDescendantOf = function (ancestor) {
  8328. if (this.parent) {
  8329. if (this.parent === ancestor) {
  8330. return true;
  8331. }
  8332. return this.parent.isDescendantOf(ancestor);
  8333. }
  8334. return false;
  8335. };
  8336. /**
  8337. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  8338. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  8339. * @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.
  8340. * @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.
  8341. */
  8342. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  8343. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  8344. if (!this._children) {
  8345. return;
  8346. }
  8347. for (var index = 0; index < this._children.length; index++) {
  8348. var item = this._children[index];
  8349. if (!predicate || predicate(item)) {
  8350. results.push(item);
  8351. }
  8352. if (!directDescendantsOnly) {
  8353. item._getDescendants(results, false, predicate);
  8354. }
  8355. }
  8356. };
  8357. /**
  8358. * Will return all nodes that have this node as ascendant.
  8359. * @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.
  8360. * @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.
  8361. * @return {BABYLON.Node[]} all children nodes of all types.
  8362. */
  8363. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  8364. var results = [];
  8365. this._getDescendants(results, directDescendantsOnly, predicate);
  8366. return results;
  8367. };
  8368. /**
  8369. * @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.
  8370. * @Deprecated, legacy support.
  8371. * use getDecendants instead.
  8372. */
  8373. Node.prototype.getChildren = function (predicate) {
  8374. return this.getDescendants(true, predicate);
  8375. };
  8376. /**
  8377. * Get all child-meshes of this node.
  8378. */
  8379. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  8380. var results = [];
  8381. this._getDescendants(results, directDecendantsOnly, function (node) {
  8382. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  8383. });
  8384. return results;
  8385. };
  8386. Node.prototype._setReady = function (state) {
  8387. if (state === this._isReady) {
  8388. return;
  8389. }
  8390. if (!state) {
  8391. this._isReady = false;
  8392. return;
  8393. }
  8394. this._isReady = true;
  8395. if (this.onReady) {
  8396. this.onReady(this);
  8397. }
  8398. };
  8399. Node.prototype.getAnimationByName = function (name) {
  8400. for (var i = 0; i < this.animations.length; i++) {
  8401. var animation = this.animations[i];
  8402. if (animation.name === name) {
  8403. return animation;
  8404. }
  8405. }
  8406. return null;
  8407. };
  8408. Node.prototype.createAnimationRange = function (name, from, to) {
  8409. // check name not already in use
  8410. if (!this._ranges[name]) {
  8411. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  8412. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8413. if (this.animations[i]) {
  8414. this.animations[i].createRange(name, from, to);
  8415. }
  8416. }
  8417. }
  8418. };
  8419. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  8420. if (deleteFrames === void 0) { deleteFrames = true; }
  8421. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8422. if (this.animations[i]) {
  8423. this.animations[i].deleteRange(name, deleteFrames);
  8424. }
  8425. }
  8426. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  8427. };
  8428. Node.prototype.getAnimationRange = function (name) {
  8429. return this._ranges[name];
  8430. };
  8431. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  8432. var range = this.getAnimationRange(name);
  8433. if (!range) {
  8434. return null;
  8435. }
  8436. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  8437. };
  8438. Node.prototype.serializeAnimationRanges = function () {
  8439. var serializationRanges = [];
  8440. for (var name in this._ranges) {
  8441. var range = {};
  8442. range.name = name;
  8443. range.from = this._ranges[name].from;
  8444. range.to = this._ranges[name].to;
  8445. serializationRanges.push(range);
  8446. }
  8447. return serializationRanges;
  8448. };
  8449. Node.prototype.dispose = function () {
  8450. this.parent = null;
  8451. };
  8452. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  8453. if (parsedNode.ranges) {
  8454. for (var index = 0; index < parsedNode.ranges.length; index++) {
  8455. var data = parsedNode.ranges[index];
  8456. node.createAnimationRange(data.name, data.from, data.to);
  8457. }
  8458. }
  8459. };
  8460. __decorate([
  8461. BABYLON.serialize()
  8462. ], Node.prototype, "name", void 0);
  8463. __decorate([
  8464. BABYLON.serialize()
  8465. ], Node.prototype, "id", void 0);
  8466. __decorate([
  8467. BABYLON.serialize()
  8468. ], Node.prototype, "uniqueId", void 0);
  8469. __decorate([
  8470. BABYLON.serialize()
  8471. ], Node.prototype, "state", void 0);
  8472. return Node;
  8473. }());
  8474. BABYLON.Node = Node;
  8475. })(BABYLON || (BABYLON = {}));
  8476. var BABYLON;
  8477. (function (BABYLON) {
  8478. var FilesInput = (function () {
  8479. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  8480. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  8481. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  8482. this._engine = p_engine;
  8483. this._canvas = p_canvas;
  8484. this._currentScene = p_scene;
  8485. this._sceneLoadedCallback = p_sceneLoadedCallback;
  8486. this._progressCallback = p_progressCallback;
  8487. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  8488. this._textureLoadingCallback = p_textureLoadingCallback;
  8489. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  8490. }
  8491. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  8492. var _this = this;
  8493. if (p_elementToMonitor) {
  8494. this._elementToMonitor = p_elementToMonitor;
  8495. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  8496. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  8497. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  8498. }
  8499. };
  8500. FilesInput.prototype.renderFunction = function () {
  8501. if (this._additionnalRenderLoopLogicCallback) {
  8502. this._additionnalRenderLoopLogicCallback();
  8503. }
  8504. if (this._currentScene) {
  8505. if (this._textureLoadingCallback) {
  8506. var remaining = this._currentScene.getWaitingItemsCount();
  8507. if (remaining > 0) {
  8508. this._textureLoadingCallback(remaining);
  8509. }
  8510. }
  8511. this._currentScene.render();
  8512. }
  8513. };
  8514. FilesInput.prototype.drag = function (e) {
  8515. e.stopPropagation();
  8516. e.preventDefault();
  8517. };
  8518. FilesInput.prototype.drop = function (eventDrop) {
  8519. eventDrop.stopPropagation();
  8520. eventDrop.preventDefault();
  8521. this.loadFiles(eventDrop);
  8522. };
  8523. FilesInput.prototype.loadFiles = function (event) {
  8524. if (this._startingProcessingFilesCallback)
  8525. this._startingProcessingFilesCallback();
  8526. // Handling data transfer via drag'n'drop
  8527. if (event && event.dataTransfer && event.dataTransfer.files) {
  8528. this._filesToLoad = event.dataTransfer.files;
  8529. }
  8530. // Handling files from input files
  8531. if (event && event.target && event.target.files) {
  8532. this._filesToLoad = event.target.files;
  8533. }
  8534. if (this._filesToLoad && this._filesToLoad.length > 0) {
  8535. for (var i = 0; i < this._filesToLoad.length; i++) {
  8536. switch (this._filesToLoad[i].type) {
  8537. case "image/jpeg":
  8538. case "image/png":
  8539. case "image/bmp":
  8540. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8541. break;
  8542. case "image/targa":
  8543. case "image/vnd.ms-dds":
  8544. case "audio/wav":
  8545. case "audio/x-wav":
  8546. case "audio/mp3":
  8547. case "audio/mpeg":
  8548. case "audio/mpeg3":
  8549. case "audio/x-mpeg-3":
  8550. case "audio/ogg":
  8551. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8552. break;
  8553. default:
  8554. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  8555. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8556. }
  8557. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  8558. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  8559. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  8560. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  8561. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  8562. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  8563. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  8564. this._sceneFileToLoad = this._filesToLoad[i];
  8565. }
  8566. break;
  8567. }
  8568. }
  8569. this.reload();
  8570. }
  8571. };
  8572. FilesInput.prototype.reload = function () {
  8573. var _this = this;
  8574. var that = this;
  8575. // If a ".babylon" file has been provided
  8576. if (this._sceneFileToLoad) {
  8577. if (this._currentScene) {
  8578. if (BABYLON.Tools.errorsCount > 0) {
  8579. BABYLON.Tools.ClearLogCache();
  8580. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  8581. }
  8582. this._engine.stopRenderLoop();
  8583. this._currentScene.dispose();
  8584. }
  8585. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  8586. that._currentScene = newScene;
  8587. // Wait for textures and shaders to be ready
  8588. that._currentScene.executeWhenReady(function () {
  8589. // Attach camera to canvas inputs
  8590. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  8591. that._currentScene.createDefaultCameraOrLight();
  8592. }
  8593. that._currentScene.activeCamera.attachControl(that._canvas);
  8594. if (that._sceneLoadedCallback) {
  8595. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  8596. }
  8597. that._engine.runRenderLoop(function () { that.renderFunction(); });
  8598. });
  8599. }, function (progress) {
  8600. if (_this._progressCallback) {
  8601. _this._progressCallback(progress);
  8602. }
  8603. });
  8604. }
  8605. else {
  8606. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  8607. }
  8608. };
  8609. FilesInput.FilesTextures = new Array();
  8610. FilesInput.FilesToLoad = new Array();
  8611. return FilesInput;
  8612. }());
  8613. BABYLON.FilesInput = FilesInput;
  8614. })(BABYLON || (BABYLON = {}));
  8615. var BABYLON;
  8616. (function (BABYLON) {
  8617. var IntersectionInfo = (function () {
  8618. function IntersectionInfo(bu, bv, distance) {
  8619. this.bu = bu;
  8620. this.bv = bv;
  8621. this.distance = distance;
  8622. this.faceId = 0;
  8623. this.subMeshId = 0;
  8624. }
  8625. return IntersectionInfo;
  8626. }());
  8627. BABYLON.IntersectionInfo = IntersectionInfo;
  8628. var PickingInfo = (function () {
  8629. function PickingInfo() {
  8630. this.hit = false;
  8631. this.distance = 0;
  8632. this.pickedPoint = null;
  8633. this.pickedMesh = null;
  8634. this.bu = 0;
  8635. this.bv = 0;
  8636. this.faceId = -1;
  8637. this.subMeshId = 0;
  8638. this.pickedSprite = null;
  8639. }
  8640. // Methods
  8641. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  8642. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  8643. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  8644. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8645. return null;
  8646. }
  8647. var indices = this.pickedMesh.getIndices();
  8648. var result;
  8649. if (useVerticesNormals) {
  8650. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8651. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  8652. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  8653. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  8654. normal0 = normal0.scale(this.bu);
  8655. normal1 = normal1.scale(this.bv);
  8656. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  8657. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  8658. }
  8659. else {
  8660. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8661. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  8662. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  8663. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  8664. var p1p2 = vertex1.subtract(vertex2);
  8665. var p3p2 = vertex3.subtract(vertex2);
  8666. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  8667. }
  8668. if (useWorldCoordinates) {
  8669. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  8670. }
  8671. return BABYLON.Vector3.Normalize(result);
  8672. };
  8673. PickingInfo.prototype.getTextureCoordinates = function () {
  8674. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8675. return null;
  8676. }
  8677. var indices = this.pickedMesh.getIndices();
  8678. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8679. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  8680. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  8681. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  8682. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  8683. uv1 = uv1.scale(this.bu);
  8684. uv2 = uv2.scale(this.bv);
  8685. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  8686. };
  8687. return PickingInfo;
  8688. }());
  8689. BABYLON.PickingInfo = PickingInfo;
  8690. })(BABYLON || (BABYLON = {}));
  8691. var BABYLON;
  8692. (function (BABYLON) {
  8693. var BoundingSphere = (function () {
  8694. function BoundingSphere(minimum, maximum) {
  8695. this.minimum = minimum;
  8696. this.maximum = maximum;
  8697. this._tempRadiusVector = BABYLON.Vector3.Zero();
  8698. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  8699. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  8700. this.radius = distance * 0.5;
  8701. this.centerWorld = BABYLON.Vector3.Zero();
  8702. this._update(BABYLON.Matrix.Identity());
  8703. }
  8704. // Methods
  8705. BoundingSphere.prototype._update = function (world) {
  8706. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  8707. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  8708. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  8709. };
  8710. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  8711. for (var i = 0; i < 6; i++) {
  8712. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  8713. return false;
  8714. }
  8715. return true;
  8716. };
  8717. BoundingSphere.prototype.intersectsPoint = function (point) {
  8718. var x = this.centerWorld.x - point.x;
  8719. var y = this.centerWorld.y - point.y;
  8720. var z = this.centerWorld.z - point.z;
  8721. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  8722. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  8723. return false;
  8724. return true;
  8725. };
  8726. // Statics
  8727. BoundingSphere.Intersects = function (sphere0, sphere1) {
  8728. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  8729. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  8730. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  8731. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  8732. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  8733. return false;
  8734. return true;
  8735. };
  8736. return BoundingSphere;
  8737. }());
  8738. BABYLON.BoundingSphere = BoundingSphere;
  8739. })(BABYLON || (BABYLON = {}));
  8740. var BABYLON;
  8741. (function (BABYLON) {
  8742. var BoundingBox = (function () {
  8743. function BoundingBox(minimum, maximum) {
  8744. this.minimum = minimum;
  8745. this.maximum = maximum;
  8746. this.vectors = new Array();
  8747. this.vectorsWorld = new Array();
  8748. // Bounding vectors
  8749. this.vectors.push(this.minimum.clone());
  8750. this.vectors.push(this.maximum.clone());
  8751. this.vectors.push(this.minimum.clone());
  8752. this.vectors[2].x = this.maximum.x;
  8753. this.vectors.push(this.minimum.clone());
  8754. this.vectors[3].y = this.maximum.y;
  8755. this.vectors.push(this.minimum.clone());
  8756. this.vectors[4].z = this.maximum.z;
  8757. this.vectors.push(this.maximum.clone());
  8758. this.vectors[5].z = this.minimum.z;
  8759. this.vectors.push(this.maximum.clone());
  8760. this.vectors[6].x = this.minimum.x;
  8761. this.vectors.push(this.maximum.clone());
  8762. this.vectors[7].y = this.minimum.y;
  8763. // OBB
  8764. this.center = this.maximum.add(this.minimum).scale(0.5);
  8765. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  8766. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  8767. // World
  8768. for (var index = 0; index < this.vectors.length; index++) {
  8769. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  8770. }
  8771. this.minimumWorld = BABYLON.Vector3.Zero();
  8772. this.maximumWorld = BABYLON.Vector3.Zero();
  8773. this._update(BABYLON.Matrix.Identity());
  8774. }
  8775. // Methods
  8776. BoundingBox.prototype.getWorldMatrix = function () {
  8777. return this._worldMatrix;
  8778. };
  8779. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  8780. this._worldMatrix.copyFrom(matrix);
  8781. return this;
  8782. };
  8783. BoundingBox.prototype._update = function (world) {
  8784. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  8785. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  8786. for (var index = 0; index < this.vectors.length; index++) {
  8787. var v = this.vectorsWorld[index];
  8788. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  8789. if (v.x < this.minimumWorld.x)
  8790. this.minimumWorld.x = v.x;
  8791. if (v.y < this.minimumWorld.y)
  8792. this.minimumWorld.y = v.y;
  8793. if (v.z < this.minimumWorld.z)
  8794. this.minimumWorld.z = v.z;
  8795. if (v.x > this.maximumWorld.x)
  8796. this.maximumWorld.x = v.x;
  8797. if (v.y > this.maximumWorld.y)
  8798. this.maximumWorld.y = v.y;
  8799. if (v.z > this.maximumWorld.z)
  8800. this.maximumWorld.z = v.z;
  8801. }
  8802. // OBB
  8803. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  8804. this.center.scaleInPlace(0.5);
  8805. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  8806. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  8807. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  8808. this._worldMatrix = world;
  8809. };
  8810. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  8811. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  8812. };
  8813. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  8814. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  8815. };
  8816. BoundingBox.prototype.intersectsPoint = function (point) {
  8817. var delta = -BABYLON.Epsilon;
  8818. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  8819. return false;
  8820. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  8821. return false;
  8822. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  8823. return false;
  8824. return true;
  8825. };
  8826. BoundingBox.prototype.intersectsSphere = function (sphere) {
  8827. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  8828. };
  8829. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  8830. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  8831. return false;
  8832. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  8833. return false;
  8834. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  8835. return false;
  8836. return true;
  8837. };
  8838. // Statics
  8839. BoundingBox.Intersects = function (box0, box1) {
  8840. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  8841. return false;
  8842. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  8843. return false;
  8844. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  8845. return false;
  8846. return true;
  8847. };
  8848. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  8849. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  8850. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  8851. return (num <= (sphereRadius * sphereRadius));
  8852. };
  8853. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  8854. for (var p = 0; p < 6; p++) {
  8855. for (var i = 0; i < 8; i++) {
  8856. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  8857. return false;
  8858. }
  8859. }
  8860. }
  8861. return true;
  8862. };
  8863. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  8864. for (var p = 0; p < 6; p++) {
  8865. var inCount = 8;
  8866. for (var i = 0; i < 8; i++) {
  8867. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  8868. --inCount;
  8869. }
  8870. else {
  8871. break;
  8872. }
  8873. }
  8874. if (inCount === 0)
  8875. return false;
  8876. }
  8877. return true;
  8878. };
  8879. return BoundingBox;
  8880. }());
  8881. BABYLON.BoundingBox = BoundingBox;
  8882. })(BABYLON || (BABYLON = {}));
  8883. var BABYLON;
  8884. (function (BABYLON) {
  8885. var computeBoxExtents = function (axis, box) {
  8886. var p = BABYLON.Vector3.Dot(box.center, axis);
  8887. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  8888. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  8889. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  8890. var r = r0 + r1 + r2;
  8891. return {
  8892. min: p - r,
  8893. max: p + r
  8894. };
  8895. };
  8896. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  8897. var axisOverlap = function (axis, box0, box1) {
  8898. var result0 = computeBoxExtents(axis, box0);
  8899. var result1 = computeBoxExtents(axis, box1);
  8900. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  8901. };
  8902. var BoundingInfo = (function () {
  8903. function BoundingInfo(minimum, maximum) {
  8904. this.minimum = minimum;
  8905. this.maximum = maximum;
  8906. this._isLocked = false;
  8907. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  8908. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  8909. }
  8910. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  8911. get: function () {
  8912. return this._isLocked;
  8913. },
  8914. set: function (value) {
  8915. this._isLocked = value;
  8916. },
  8917. enumerable: true,
  8918. configurable: true
  8919. });
  8920. // Methods
  8921. BoundingInfo.prototype.update = function (world) {
  8922. if (this._isLocked) {
  8923. return;
  8924. }
  8925. this.boundingBox._update(world);
  8926. this.boundingSphere._update(world);
  8927. };
  8928. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  8929. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  8930. return false;
  8931. return this.boundingBox.isInFrustum(frustumPlanes);
  8932. };
  8933. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  8934. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  8935. };
  8936. BoundingInfo.prototype._checkCollision = function (collider) {
  8937. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  8938. };
  8939. BoundingInfo.prototype.intersectsPoint = function (point) {
  8940. if (!this.boundingSphere.centerWorld) {
  8941. return false;
  8942. }
  8943. if (!this.boundingSphere.intersectsPoint(point)) {
  8944. return false;
  8945. }
  8946. if (!this.boundingBox.intersectsPoint(point)) {
  8947. return false;
  8948. }
  8949. return true;
  8950. };
  8951. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  8952. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  8953. return false;
  8954. }
  8955. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  8956. return false;
  8957. }
  8958. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  8959. return false;
  8960. }
  8961. if (!precise) {
  8962. return true;
  8963. }
  8964. var box0 = this.boundingBox;
  8965. var box1 = boundingInfo.boundingBox;
  8966. if (!axisOverlap(box0.directions[0], box0, box1))
  8967. return false;
  8968. if (!axisOverlap(box0.directions[1], box0, box1))
  8969. return false;
  8970. if (!axisOverlap(box0.directions[2], box0, box1))
  8971. return false;
  8972. if (!axisOverlap(box1.directions[0], box0, box1))
  8973. return false;
  8974. if (!axisOverlap(box1.directions[1], box0, box1))
  8975. return false;
  8976. if (!axisOverlap(box1.directions[2], box0, box1))
  8977. return false;
  8978. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  8979. return false;
  8980. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  8981. return false;
  8982. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  8983. return false;
  8984. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  8985. return false;
  8986. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  8987. return false;
  8988. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  8989. return false;
  8990. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  8991. return false;
  8992. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  8993. return false;
  8994. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  8995. return false;
  8996. return true;
  8997. };
  8998. return BoundingInfo;
  8999. }());
  9000. BABYLON.BoundingInfo = BoundingInfo;
  9001. })(BABYLON || (BABYLON = {}));
  9002. var BABYLON;
  9003. (function (BABYLON) {
  9004. var Ray = (function () {
  9005. function Ray(origin, direction, length) {
  9006. if (length === void 0) { length = Number.MAX_VALUE; }
  9007. this.origin = origin;
  9008. this.direction = direction;
  9009. this.length = length;
  9010. }
  9011. // Methods
  9012. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  9013. var d = 0.0;
  9014. var maxValue = Number.MAX_VALUE;
  9015. var inv;
  9016. var min;
  9017. var max;
  9018. var temp;
  9019. if (Math.abs(this.direction.x) < 0.0000001) {
  9020. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  9021. return false;
  9022. }
  9023. }
  9024. else {
  9025. inv = 1.0 / this.direction.x;
  9026. min = (minimum.x - this.origin.x) * inv;
  9027. max = (maximum.x - this.origin.x) * inv;
  9028. if (max === -Infinity) {
  9029. max = Infinity;
  9030. }
  9031. if (min > max) {
  9032. temp = min;
  9033. min = max;
  9034. max = temp;
  9035. }
  9036. d = Math.max(min, d);
  9037. maxValue = Math.min(max, maxValue);
  9038. if (d > maxValue) {
  9039. return false;
  9040. }
  9041. }
  9042. if (Math.abs(this.direction.y) < 0.0000001) {
  9043. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  9044. return false;
  9045. }
  9046. }
  9047. else {
  9048. inv = 1.0 / this.direction.y;
  9049. min = (minimum.y - this.origin.y) * inv;
  9050. max = (maximum.y - this.origin.y) * inv;
  9051. if (max === -Infinity) {
  9052. max = Infinity;
  9053. }
  9054. if (min > max) {
  9055. temp = min;
  9056. min = max;
  9057. max = temp;
  9058. }
  9059. d = Math.max(min, d);
  9060. maxValue = Math.min(max, maxValue);
  9061. if (d > maxValue) {
  9062. return false;
  9063. }
  9064. }
  9065. if (Math.abs(this.direction.z) < 0.0000001) {
  9066. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  9067. return false;
  9068. }
  9069. }
  9070. else {
  9071. inv = 1.0 / this.direction.z;
  9072. min = (minimum.z - this.origin.z) * inv;
  9073. max = (maximum.z - this.origin.z) * inv;
  9074. if (max === -Infinity) {
  9075. max = Infinity;
  9076. }
  9077. if (min > max) {
  9078. temp = min;
  9079. min = max;
  9080. max = temp;
  9081. }
  9082. d = Math.max(min, d);
  9083. maxValue = Math.min(max, maxValue);
  9084. if (d > maxValue) {
  9085. return false;
  9086. }
  9087. }
  9088. return true;
  9089. };
  9090. Ray.prototype.intersectsBox = function (box) {
  9091. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  9092. };
  9093. Ray.prototype.intersectsSphere = function (sphere) {
  9094. var x = sphere.center.x - this.origin.x;
  9095. var y = sphere.center.y - this.origin.y;
  9096. var z = sphere.center.z - this.origin.z;
  9097. var pyth = (x * x) + (y * y) + (z * z);
  9098. var rr = sphere.radius * sphere.radius;
  9099. if (pyth <= rr) {
  9100. return true;
  9101. }
  9102. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  9103. if (dot < 0.0) {
  9104. return false;
  9105. }
  9106. var temp = pyth - (dot * dot);
  9107. return temp <= rr;
  9108. };
  9109. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  9110. if (!this._edge1) {
  9111. this._edge1 = BABYLON.Vector3.Zero();
  9112. this._edge2 = BABYLON.Vector3.Zero();
  9113. this._pvec = BABYLON.Vector3.Zero();
  9114. this._tvec = BABYLON.Vector3.Zero();
  9115. this._qvec = BABYLON.Vector3.Zero();
  9116. }
  9117. vertex1.subtractToRef(vertex0, this._edge1);
  9118. vertex2.subtractToRef(vertex0, this._edge2);
  9119. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  9120. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  9121. if (det === 0) {
  9122. return null;
  9123. }
  9124. var invdet = 1 / det;
  9125. this.origin.subtractToRef(vertex0, this._tvec);
  9126. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  9127. if (bu < 0 || bu > 1.0) {
  9128. return null;
  9129. }
  9130. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  9131. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  9132. if (bv < 0 || bu + bv > 1.0) {
  9133. return null;
  9134. }
  9135. //check if the distance is longer than the predefined length.
  9136. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  9137. if (distance > this.length) {
  9138. return null;
  9139. }
  9140. return new BABYLON.IntersectionInfo(bu, bv, distance);
  9141. };
  9142. Ray.prototype.intersectsPlane = function (plane) {
  9143. var distance;
  9144. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  9145. if (Math.abs(result1) < 9.99999997475243E-07) {
  9146. return null;
  9147. }
  9148. else {
  9149. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  9150. distance = (-plane.d - result2) / result1;
  9151. if (distance < 0.0) {
  9152. if (distance < -9.99999997475243E-07) {
  9153. return null;
  9154. }
  9155. else {
  9156. return 0;
  9157. }
  9158. }
  9159. return distance;
  9160. }
  9161. };
  9162. /**
  9163. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  9164. * @param sega the first point of the segment to test the intersection against
  9165. * @param segb the second point of the segment to test the intersection against
  9166. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  9167. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  9168. */
  9169. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  9170. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  9171. var u = segb.subtract(sega);
  9172. var v = rsegb.subtract(this.origin);
  9173. var w = sega.subtract(this.origin);
  9174. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  9175. var b = BABYLON.Vector3.Dot(u, v);
  9176. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  9177. var d = BABYLON.Vector3.Dot(u, w);
  9178. var e = BABYLON.Vector3.Dot(v, w);
  9179. var D = a * c - b * b; // always >= 0
  9180. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  9181. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  9182. // compute the line parameters of the two closest points
  9183. if (D < Ray.smallnum) {
  9184. sN = 0.0; // force using point P0 on segment S1
  9185. sD = 1.0; // to prevent possible division by 0.0 later
  9186. tN = e;
  9187. tD = c;
  9188. }
  9189. else {
  9190. sN = (b * e - c * d);
  9191. tN = (a * e - b * d);
  9192. if (sN < 0.0) {
  9193. sN = 0.0;
  9194. tN = e;
  9195. tD = c;
  9196. }
  9197. else if (sN > sD) {
  9198. sN = sD;
  9199. tN = e + b;
  9200. tD = c;
  9201. }
  9202. }
  9203. if (tN < 0.0) {
  9204. tN = 0.0;
  9205. // recompute sc for this edge
  9206. if (-d < 0.0) {
  9207. sN = 0.0;
  9208. }
  9209. else if (-d > a)
  9210. sN = sD;
  9211. else {
  9212. sN = -d;
  9213. sD = a;
  9214. }
  9215. }
  9216. else if (tN > tD) {
  9217. tN = tD;
  9218. // recompute sc for this edge
  9219. if ((-d + b) < 0.0) {
  9220. sN = 0;
  9221. }
  9222. else if ((-d + b) > a) {
  9223. sN = sD;
  9224. }
  9225. else {
  9226. sN = (-d + b);
  9227. sD = a;
  9228. }
  9229. }
  9230. // finally do the division to get sc and tc
  9231. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  9232. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  9233. // get the difference of the two closest points
  9234. var qtc = v.multiplyByFloats(tc, tc, tc);
  9235. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  9236. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  9237. if (isIntersected) {
  9238. return qtc.length();
  9239. }
  9240. return -1;
  9241. };
  9242. // Statics
  9243. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  9244. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  9245. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  9246. var direction = end.subtract(start);
  9247. direction.normalize();
  9248. return new Ray(start, direction);
  9249. };
  9250. /**
  9251. * 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
  9252. * transformed to the given world matrix.
  9253. * @param origin The origin point
  9254. * @param end The end point
  9255. * @param world a matrix to transform the ray to. Default is the identity matrix.
  9256. */
  9257. Ray.CreateNewFromTo = function (origin, end, world) {
  9258. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  9259. var direction = end.subtract(origin);
  9260. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  9261. direction.normalize();
  9262. return Ray.Transform(new Ray(origin, direction, length), world);
  9263. };
  9264. Ray.Transform = function (ray, matrix) {
  9265. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  9266. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  9267. newDirection.normalize();
  9268. return new Ray(newOrigin, newDirection, ray.length);
  9269. };
  9270. Ray.smallnum = 0.00000001;
  9271. Ray.rayl = 10e8;
  9272. return Ray;
  9273. }());
  9274. BABYLON.Ray = Ray;
  9275. })(BABYLON || (BABYLON = {}));
  9276. var BABYLON;
  9277. (function (BABYLON) {
  9278. var AbstractMesh = (function (_super) {
  9279. __extends(AbstractMesh, _super);
  9280. // Constructor
  9281. function AbstractMesh(name, scene) {
  9282. var _this = this;
  9283. _super.call(this, name, scene);
  9284. // Events
  9285. /**
  9286. * An event triggered when the mesh is disposed.
  9287. * @type {BABYLON.Observable}
  9288. */
  9289. this.onDisposeObservable = new BABYLON.Observable();
  9290. /**
  9291. * An event triggered when this mesh collides with another one
  9292. * @type {BABYLON.Observable}
  9293. */
  9294. this.onCollideObservable = new BABYLON.Observable();
  9295. /**
  9296. * An event triggered when the collision's position changes
  9297. * @type {BABYLON.Observable}
  9298. */
  9299. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  9300. /**
  9301. * An event triggered after the world matrix is updated
  9302. * @type {BABYLON.Observable}
  9303. */
  9304. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  9305. // Properties
  9306. this.definedFacingForward = true; // orientation for POV movement & rotation
  9307. this.position = new BABYLON.Vector3(0, 0, 0);
  9308. this._rotation = new BABYLON.Vector3(0, 0, 0);
  9309. this._scaling = new BABYLON.Vector3(1, 1, 1);
  9310. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9311. this.visibility = 1.0;
  9312. this.alphaIndex = Number.MAX_VALUE;
  9313. this.infiniteDistance = false;
  9314. this.isVisible = true;
  9315. this.isPickable = true;
  9316. this.showBoundingBox = false;
  9317. this.showSubMeshesBoundingBox = false;
  9318. this.isBlocker = false;
  9319. this.renderingGroupId = 0;
  9320. this.receiveShadows = false;
  9321. this.renderOutline = false;
  9322. this.outlineColor = BABYLON.Color3.Red();
  9323. this.outlineWidth = 0.02;
  9324. this.renderOverlay = false;
  9325. this.overlayColor = BABYLON.Color3.Red();
  9326. this.overlayAlpha = 0.5;
  9327. this.hasVertexAlpha = false;
  9328. this.useVertexColors = true;
  9329. this.applyFog = true;
  9330. this.computeBonesUsingShaders = true;
  9331. this.scalingDeterminant = 1;
  9332. this.numBoneInfluencers = 4;
  9333. this.useOctreeForRenderingSelection = true;
  9334. this.useOctreeForPicking = true;
  9335. this.useOctreeForCollisions = true;
  9336. this.layerMask = 0x0FFFFFFF;
  9337. this.alwaysSelectAsActiveMesh = false;
  9338. // Collisions
  9339. this._checkCollisions = false;
  9340. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9341. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9342. this._collider = new BABYLON.Collider();
  9343. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9344. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9345. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9346. // Edges
  9347. this.edgesWidth = 1;
  9348. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  9349. // Cache
  9350. this._localWorld = BABYLON.Matrix.Zero();
  9351. this._worldMatrix = BABYLON.Matrix.Zero();
  9352. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9353. this._absolutePosition = BABYLON.Vector3.Zero();
  9354. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9355. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9356. this._isDirty = false;
  9357. this._pivotMatrix = BABYLON.Matrix.Identity();
  9358. this._isDisposed = false;
  9359. this._renderId = 0;
  9360. this._intersectionsInProgress = new Array();
  9361. this._isWorldMatrixFrozen = false;
  9362. this._unIndexed = false;
  9363. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  9364. if (collidedMesh === void 0) { collidedMesh = null; }
  9365. //TODO move this to the collision coordinator!
  9366. if (_this.getScene().workerCollisions)
  9367. newPosition.multiplyInPlace(_this._collider.radius);
  9368. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  9369. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9370. _this.position.addInPlace(_this._diffPositionForCollisions);
  9371. }
  9372. if (collidedMesh) {
  9373. _this.onCollideObservable.notifyObservers(collidedMesh);
  9374. }
  9375. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  9376. };
  9377. scene.addMesh(this);
  9378. }
  9379. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9380. get: function () {
  9381. return AbstractMesh._BILLBOARDMODE_NONE;
  9382. },
  9383. enumerable: true,
  9384. configurable: true
  9385. });
  9386. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9387. get: function () {
  9388. return AbstractMesh._BILLBOARDMODE_X;
  9389. },
  9390. enumerable: true,
  9391. configurable: true
  9392. });
  9393. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9394. get: function () {
  9395. return AbstractMesh._BILLBOARDMODE_Y;
  9396. },
  9397. enumerable: true,
  9398. configurable: true
  9399. });
  9400. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9401. get: function () {
  9402. return AbstractMesh._BILLBOARDMODE_Z;
  9403. },
  9404. enumerable: true,
  9405. configurable: true
  9406. });
  9407. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9408. get: function () {
  9409. return AbstractMesh._BILLBOARDMODE_ALL;
  9410. },
  9411. enumerable: true,
  9412. configurable: true
  9413. });
  9414. Object.defineProperty(AbstractMesh.prototype, "onDispose", {
  9415. set: function (callback) {
  9416. if (this._onDisposeObserver) {
  9417. this.onDisposeObservable.remove(this._onDisposeObserver);
  9418. }
  9419. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9420. },
  9421. enumerable: true,
  9422. configurable: true
  9423. });
  9424. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  9425. set: function (callback) {
  9426. if (this._onCollideObserver) {
  9427. this.onCollideObservable.remove(this._onCollideObserver);
  9428. }
  9429. this._onCollideObserver = this.onCollideObservable.add(callback);
  9430. },
  9431. enumerable: true,
  9432. configurable: true
  9433. });
  9434. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  9435. set: function (callback) {
  9436. if (this._onCollisionPositionChangeObserver) {
  9437. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  9438. }
  9439. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  9440. },
  9441. enumerable: true,
  9442. configurable: true
  9443. });
  9444. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  9445. get: function () {
  9446. return this._skeleton;
  9447. },
  9448. set: function (value) {
  9449. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  9450. this._skeleton._unregisterMeshWithPoseMatrix(this);
  9451. }
  9452. if (value && value.needInitialSkinMatrix) {
  9453. value._registerMeshWithPoseMatrix(this);
  9454. }
  9455. this._skeleton = value;
  9456. if (!this._skeleton) {
  9457. this._bonesTransformMatrices = null;
  9458. }
  9459. },
  9460. enumerable: true,
  9461. configurable: true
  9462. });
  9463. /**
  9464. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9465. */
  9466. AbstractMesh.prototype.toString = function (fullDetails) {
  9467. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  9468. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  9469. if (this._skeleton) {
  9470. ret += ", skeleton: " + this._skeleton.name;
  9471. }
  9472. if (fullDetails) {
  9473. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  9474. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  9475. }
  9476. return ret;
  9477. };
  9478. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  9479. /**
  9480. * Getting the rotation object.
  9481. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  9482. */
  9483. get: function () {
  9484. return this._rotation;
  9485. },
  9486. set: function (newRotation) {
  9487. this._rotation = newRotation;
  9488. },
  9489. enumerable: true,
  9490. configurable: true
  9491. });
  9492. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  9493. get: function () {
  9494. return this._scaling;
  9495. },
  9496. set: function (newScaling) {
  9497. this._scaling = newScaling;
  9498. if (this.physicsImpostor) {
  9499. this.physicsImpostor.forceUpdate();
  9500. }
  9501. },
  9502. enumerable: true,
  9503. configurable: true
  9504. });
  9505. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  9506. get: function () {
  9507. return this._rotationQuaternion;
  9508. },
  9509. set: function (quaternion) {
  9510. this._rotationQuaternion = quaternion;
  9511. //reset the rotation vector.
  9512. if (quaternion && this.rotation.length()) {
  9513. this.rotation.copyFromFloats(0, 0, 0);
  9514. }
  9515. },
  9516. enumerable: true,
  9517. configurable: true
  9518. });
  9519. // Methods
  9520. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  9521. this._poseMatrix.copyFrom(matrix);
  9522. };
  9523. AbstractMesh.prototype.getPoseMatrix = function () {
  9524. return this._poseMatrix;
  9525. };
  9526. AbstractMesh.prototype.disableEdgesRendering = function () {
  9527. if (this._edgesRenderer !== undefined) {
  9528. this._edgesRenderer.dispose();
  9529. this._edgesRenderer = undefined;
  9530. }
  9531. };
  9532. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  9533. if (epsilon === void 0) { epsilon = 0.95; }
  9534. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  9535. this.disableEdgesRendering();
  9536. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  9537. };
  9538. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9539. get: function () {
  9540. return false;
  9541. },
  9542. enumerable: true,
  9543. configurable: true
  9544. });
  9545. AbstractMesh.prototype.getLOD = function (camera) {
  9546. return this;
  9547. };
  9548. AbstractMesh.prototype.getTotalVertices = function () {
  9549. return 0;
  9550. };
  9551. AbstractMesh.prototype.getIndices = function () {
  9552. return null;
  9553. };
  9554. AbstractMesh.prototype.getVerticesData = function (kind) {
  9555. return null;
  9556. };
  9557. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9558. return false;
  9559. };
  9560. AbstractMesh.prototype.getBoundingInfo = function () {
  9561. if (this._masterMesh) {
  9562. return this._masterMesh.getBoundingInfo();
  9563. }
  9564. if (!this._boundingInfo) {
  9565. this._updateBoundingInfo();
  9566. }
  9567. return this._boundingInfo;
  9568. };
  9569. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  9570. this._boundingInfo = boundingInfo;
  9571. };
  9572. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9573. get: function () {
  9574. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9575. },
  9576. enumerable: true,
  9577. configurable: true
  9578. });
  9579. AbstractMesh.prototype._preActivate = function () {
  9580. };
  9581. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  9582. };
  9583. AbstractMesh.prototype._activate = function (renderId) {
  9584. this._renderId = renderId;
  9585. };
  9586. AbstractMesh.prototype.getWorldMatrix = function () {
  9587. if (this._masterMesh) {
  9588. return this._masterMesh.getWorldMatrix();
  9589. }
  9590. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9591. this.computeWorldMatrix();
  9592. }
  9593. return this._worldMatrix;
  9594. };
  9595. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9596. get: function () {
  9597. return this._worldMatrix;
  9598. },
  9599. enumerable: true,
  9600. configurable: true
  9601. });
  9602. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9603. get: function () {
  9604. return this._absolutePosition;
  9605. },
  9606. enumerable: true,
  9607. configurable: true
  9608. });
  9609. AbstractMesh.prototype.freezeWorldMatrix = function () {
  9610. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  9611. this.computeWorldMatrix(true);
  9612. this._isWorldMatrixFrozen = true;
  9613. };
  9614. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  9615. this._isWorldMatrixFrozen = false;
  9616. this.computeWorldMatrix(true);
  9617. };
  9618. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  9619. get: function () {
  9620. return this._isWorldMatrixFrozen;
  9621. },
  9622. enumerable: true,
  9623. configurable: true
  9624. });
  9625. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9626. axis.normalize();
  9627. if (!this.rotationQuaternion) {
  9628. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9629. this.rotation = BABYLON.Vector3.Zero();
  9630. }
  9631. var rotationQuaternion;
  9632. if (!space || space === BABYLON.Space.LOCAL) {
  9633. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  9634. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  9635. }
  9636. else {
  9637. if (this.parent) {
  9638. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9639. invertParentWorldMatrix.invert();
  9640. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9641. }
  9642. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  9643. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  9644. }
  9645. };
  9646. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9647. var displacementVector = axis.scale(distance);
  9648. if (!space || space === BABYLON.Space.LOCAL) {
  9649. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9650. this.setPositionWithLocalVector(tempV3);
  9651. }
  9652. else {
  9653. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9654. }
  9655. };
  9656. AbstractMesh.prototype.getAbsolutePosition = function () {
  9657. this.computeWorldMatrix();
  9658. return this._absolutePosition;
  9659. };
  9660. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9661. if (!absolutePosition) {
  9662. return;
  9663. }
  9664. var absolutePositionX;
  9665. var absolutePositionY;
  9666. var absolutePositionZ;
  9667. if (absolutePosition.x === undefined) {
  9668. if (arguments.length < 3) {
  9669. return;
  9670. }
  9671. absolutePositionX = arguments[0];
  9672. absolutePositionY = arguments[1];
  9673. absolutePositionZ = arguments[2];
  9674. }
  9675. else {
  9676. absolutePositionX = absolutePosition.x;
  9677. absolutePositionY = absolutePosition.y;
  9678. absolutePositionZ = absolutePosition.z;
  9679. }
  9680. if (this.parent) {
  9681. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9682. invertParentWorldMatrix.invert();
  9683. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9684. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9685. }
  9686. else {
  9687. this.position.x = absolutePositionX;
  9688. this.position.y = absolutePositionY;
  9689. this.position.z = absolutePositionZ;
  9690. }
  9691. };
  9692. // ================================== Point of View Movement =================================
  9693. /**
  9694. * Perform relative position change from the point of view of behind the front of the mesh.
  9695. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9696. * Supports definition of mesh facing forward or backward.
  9697. * @param {number} amountRight
  9698. * @param {number} amountUp
  9699. * @param {number} amountForward
  9700. */
  9701. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9702. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9703. };
  9704. /**
  9705. * Calculate relative position change from the point of view of behind the front of the mesh.
  9706. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9707. * Supports definition of mesh facing forward or backward.
  9708. * @param {number} amountRight
  9709. * @param {number} amountUp
  9710. * @param {number} amountForward
  9711. */
  9712. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9713. var rotMatrix = new BABYLON.Matrix();
  9714. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9715. rotQuaternion.toRotationMatrix(rotMatrix);
  9716. var translationDelta = BABYLON.Vector3.Zero();
  9717. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9718. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9719. return translationDelta;
  9720. };
  9721. // ================================== Point of View Rotation =================================
  9722. /**
  9723. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9724. * Supports definition of mesh facing forward or backward.
  9725. * @param {number} flipBack
  9726. * @param {number} twirlClockwise
  9727. * @param {number} tiltRight
  9728. */
  9729. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9730. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9731. };
  9732. /**
  9733. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9734. * Supports definition of mesh facing forward or backward.
  9735. * @param {number} flipBack
  9736. * @param {number} twirlClockwise
  9737. * @param {number} tiltRight
  9738. */
  9739. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9740. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9741. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9742. };
  9743. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9744. this._pivotMatrix = matrix;
  9745. this._cache.pivotMatrixUpdated = true;
  9746. };
  9747. AbstractMesh.prototype.getPivotMatrix = function () {
  9748. return this._pivotMatrix;
  9749. };
  9750. AbstractMesh.prototype._isSynchronized = function () {
  9751. if (this._isDirty) {
  9752. return false;
  9753. }
  9754. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9755. return false;
  9756. if (this._cache.pivotMatrixUpdated) {
  9757. return false;
  9758. }
  9759. if (this.infiniteDistance) {
  9760. return false;
  9761. }
  9762. if (!this._cache.position.equals(this.position))
  9763. return false;
  9764. if (this.rotationQuaternion) {
  9765. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9766. return false;
  9767. }
  9768. else {
  9769. if (!this._cache.rotation.equals(this.rotation))
  9770. return false;
  9771. }
  9772. if (!this._cache.scaling.equals(this.scaling))
  9773. return false;
  9774. return true;
  9775. };
  9776. AbstractMesh.prototype._initCache = function () {
  9777. _super.prototype._initCache.call(this);
  9778. this._cache.localMatrixUpdated = false;
  9779. this._cache.position = BABYLON.Vector3.Zero();
  9780. this._cache.scaling = BABYLON.Vector3.Zero();
  9781. this._cache.rotation = BABYLON.Vector3.Zero();
  9782. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9783. this._cache.billboardMode = -1;
  9784. };
  9785. AbstractMesh.prototype.markAsDirty = function (property) {
  9786. if (property === "rotation") {
  9787. this.rotationQuaternion = null;
  9788. }
  9789. this._currentRenderId = Number.MAX_VALUE;
  9790. this._isDirty = true;
  9791. };
  9792. AbstractMesh.prototype._updateBoundingInfo = function () {
  9793. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9794. this._boundingInfo.update(this.worldMatrixFromCache);
  9795. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9796. };
  9797. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9798. if (!this.subMeshes) {
  9799. return;
  9800. }
  9801. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9802. var subMesh = this.subMeshes[subIndex];
  9803. if (!subMesh.IsGlobal) {
  9804. subMesh.updateBoundingInfo(matrix);
  9805. }
  9806. }
  9807. };
  9808. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9809. if (this._isWorldMatrixFrozen) {
  9810. return this._worldMatrix;
  9811. }
  9812. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  9813. this._currentRenderId = this.getScene().getRenderId();
  9814. return this._worldMatrix;
  9815. }
  9816. this._cache.position.copyFrom(this.position);
  9817. this._cache.scaling.copyFrom(this.scaling);
  9818. this._cache.pivotMatrixUpdated = false;
  9819. this._cache.billboardMode = this.billboardMode;
  9820. this._currentRenderId = this.getScene().getRenderId();
  9821. this._isDirty = false;
  9822. // Scaling
  9823. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  9824. // Rotation
  9825. //rotate, if quaternion is set and rotation was used
  9826. if (this.rotationQuaternion) {
  9827. var len = this.rotation.length();
  9828. if (len) {
  9829. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  9830. this.rotation.copyFromFloats(0, 0, 0);
  9831. }
  9832. }
  9833. if (this.rotationQuaternion) {
  9834. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  9835. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9836. }
  9837. else {
  9838. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  9839. this._cache.rotation.copyFrom(this.rotation);
  9840. }
  9841. // Translation
  9842. if (this.infiniteDistance && !this.parent) {
  9843. var camera = this.getScene().activeCamera;
  9844. if (camera) {
  9845. var cameraWorldMatrix = camera.getWorldMatrix();
  9846. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9847. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  9848. }
  9849. }
  9850. else {
  9851. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  9852. }
  9853. // Composing transformations
  9854. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  9855. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  9856. // Billboarding
  9857. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9858. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  9859. var localPosition = BABYLON.Tmp.Vector3[0];
  9860. if (this.parent && this.parent.getWorldMatrix) {
  9861. this._markSyncedWithParent();
  9862. var parentMatrix;
  9863. if (this._meshToBoneReferal) {
  9864. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  9865. parentMatrix = BABYLON.Tmp.Matrix[6];
  9866. }
  9867. else {
  9868. parentMatrix = this.parent.getWorldMatrix();
  9869. }
  9870. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  9871. localPosition = BABYLON.Tmp.Vector3[1];
  9872. }
  9873. var zero = this.getScene().activeCamera.globalPosition.clone();
  9874. if (this.parent && this.parent.position) {
  9875. localPosition.addInPlace(this.parent.position);
  9876. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  9877. }
  9878. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  9879. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  9880. zero.x = localPosition.x + BABYLON.Epsilon;
  9881. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  9882. zero.y = localPosition.y + BABYLON.Epsilon;
  9883. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  9884. zero.z = localPosition.z + BABYLON.Epsilon;
  9885. }
  9886. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  9887. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  9888. BABYLON.Tmp.Matrix[3].invert();
  9889. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  9890. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  9891. }
  9892. // Local world
  9893. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  9894. // Parent
  9895. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  9896. this._markSyncedWithParent();
  9897. if (this._meshToBoneReferal) {
  9898. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  9899. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  9900. }
  9901. else {
  9902. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9903. }
  9904. }
  9905. else {
  9906. this._worldMatrix.copyFrom(this._localWorld);
  9907. }
  9908. // Bounding info
  9909. this._updateBoundingInfo();
  9910. // Absolute position
  9911. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9912. // Callbacks
  9913. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  9914. if (!this._poseMatrix) {
  9915. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  9916. }
  9917. return this._worldMatrix;
  9918. };
  9919. /**
  9920. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9921. * @param func: callback function to add
  9922. */
  9923. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9924. this.onAfterWorldMatrixUpdateObservable.add(func);
  9925. };
  9926. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9927. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  9928. };
  9929. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9930. this.computeWorldMatrix();
  9931. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9932. };
  9933. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9934. this.computeWorldMatrix();
  9935. var invLocalWorldMatrix = this._localWorld.clone();
  9936. invLocalWorldMatrix.invert();
  9937. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9938. };
  9939. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9940. this.computeWorldMatrix(true);
  9941. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9942. };
  9943. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  9944. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9945. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  9946. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9947. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9948. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9949. /// <returns>Mesh oriented towards targetMesh</returns>
  9950. if (yawCor === void 0) { yawCor = 0; }
  9951. if (pitchCor === void 0) { pitchCor = 0; }
  9952. if (rollCor === void 0) { rollCor = 0; }
  9953. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  9954. var dv = AbstractMesh._lookAtVectorCache;
  9955. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  9956. targetPoint.subtractToRef(pos, dv);
  9957. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9958. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9959. var pitch = Math.atan2(dv.y, len);
  9960. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  9961. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  9962. };
  9963. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  9964. this._meshToBoneReferal = affectedMesh;
  9965. this.parent = bone;
  9966. if (bone.getWorldMatrix().determinant() < 0) {
  9967. this.scalingDeterminant *= -1;
  9968. }
  9969. };
  9970. AbstractMesh.prototype.detachFromBone = function () {
  9971. if (this.parent.getWorldMatrix().determinant() < 0) {
  9972. this.scalingDeterminant *= -1;
  9973. }
  9974. this._meshToBoneReferal = null;
  9975. this.parent = null;
  9976. };
  9977. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9978. return this._boundingInfo.isInFrustum(frustumPlanes);
  9979. };
  9980. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9981. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  9982. ;
  9983. };
  9984. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9985. if (!this._boundingInfo || !mesh._boundingInfo) {
  9986. return false;
  9987. }
  9988. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9989. };
  9990. AbstractMesh.prototype.intersectsPoint = function (point) {
  9991. if (!this._boundingInfo) {
  9992. return false;
  9993. }
  9994. return this._boundingInfo.intersectsPoint(point);
  9995. };
  9996. // Physics
  9997. /**
  9998. * @Deprecated. Use new PhysicsImpostor instead.
  9999. * */
  10000. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10001. //legacy support
  10002. if (impostor.impostor) {
  10003. options = impostor;
  10004. impostor = impostor.impostor;
  10005. }
  10006. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  10007. return this.physicsImpostor.physicsBody;
  10008. };
  10009. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10010. return this.physicsImpostor;
  10011. };
  10012. /**
  10013. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  10014. */
  10015. AbstractMesh.prototype.getPhysicsMass = function () {
  10016. return this.physicsImpostor.getParam("mass");
  10017. };
  10018. /**
  10019. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  10020. */
  10021. AbstractMesh.prototype.getPhysicsFriction = function () {
  10022. return this.physicsImpostor.getParam("friction");
  10023. };
  10024. /**
  10025. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  10026. */
  10027. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10028. return this.physicsImpostor.getParam("restitution");
  10029. };
  10030. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10031. if (!camera) {
  10032. camera = this.getScene().activeCamera;
  10033. }
  10034. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10035. };
  10036. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10037. if (!camera) {
  10038. camera = this.getScene().activeCamera;
  10039. }
  10040. return this.absolutePosition.subtract(camera.position).length();
  10041. };
  10042. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10043. if (!this.physicsImpostor) {
  10044. return;
  10045. }
  10046. this.physicsImpostor.applyImpulse(force, contactPoint);
  10047. };
  10048. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10049. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  10050. return;
  10051. }
  10052. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  10053. mainPivot: pivot1,
  10054. connectedPivot: pivot2,
  10055. nativeParams: options
  10056. });
  10057. };
  10058. /**
  10059. * @Deprecated
  10060. */
  10061. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10062. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  10063. this.updatePhysicsBody();
  10064. };
  10065. /**
  10066. * @Deprecated
  10067. * Calling this function is not needed anymore.
  10068. * The physics engine takes care of transofmration automatically.
  10069. */
  10070. AbstractMesh.prototype.updatePhysicsBody = function () {
  10071. //Unneeded
  10072. };
  10073. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  10074. // Collisions
  10075. get: function () {
  10076. return this._checkCollisions;
  10077. },
  10078. set: function (collisionEnabled) {
  10079. this._checkCollisions = collisionEnabled;
  10080. if (this.getScene().workerCollisions) {
  10081. this.getScene().collisionCoordinator.onMeshUpdated(this);
  10082. }
  10083. },
  10084. enumerable: true,
  10085. configurable: true
  10086. });
  10087. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10088. var globalPosition = this.getAbsolutePosition();
  10089. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10090. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10091. this._collider.radius = this.ellipsoid;
  10092. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  10093. };
  10094. // Submeshes octree
  10095. /**
  10096. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10097. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10098. */
  10099. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10100. if (maxCapacity === void 0) { maxCapacity = 64; }
  10101. if (maxDepth === void 0) { maxDepth = 2; }
  10102. if (!this._submeshesOctree) {
  10103. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10104. }
  10105. this.computeWorldMatrix(true);
  10106. // Update octree
  10107. var bbox = this.getBoundingInfo().boundingBox;
  10108. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10109. return this._submeshesOctree;
  10110. };
  10111. // Collisions
  10112. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10113. this._generatePointsArray();
  10114. // Transformation
  10115. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10116. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10117. subMesh._lastColliderWorldVertices = [];
  10118. subMesh._trianglePlanes = [];
  10119. var start = subMesh.verticesStart;
  10120. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10121. for (var i = start; i < end; i++) {
  10122. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10123. }
  10124. }
  10125. // Collide
  10126. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  10127. if (collider.collisionFound) {
  10128. collider.collidedMesh = this;
  10129. }
  10130. };
  10131. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10132. var subMeshes;
  10133. var len;
  10134. // Octrees
  10135. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10136. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10137. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10138. len = intersections.length;
  10139. subMeshes = intersections.data;
  10140. }
  10141. else {
  10142. subMeshes = this.subMeshes;
  10143. len = subMeshes.length;
  10144. }
  10145. for (var index = 0; index < len; index++) {
  10146. var subMesh = subMeshes[index];
  10147. // Bounding test
  10148. if (len > 1 && !subMesh._checkCollision(collider))
  10149. continue;
  10150. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10151. }
  10152. };
  10153. AbstractMesh.prototype._checkCollision = function (collider) {
  10154. // Bounding box test
  10155. if (!this._boundingInfo._checkCollision(collider))
  10156. return;
  10157. // Transformation matrix
  10158. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10159. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10160. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10161. };
  10162. // Picking
  10163. AbstractMesh.prototype._generatePointsArray = function () {
  10164. return false;
  10165. };
  10166. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10167. var pickingInfo = new BABYLON.PickingInfo();
  10168. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10169. return pickingInfo;
  10170. }
  10171. if (!this._generatePointsArray()) {
  10172. return pickingInfo;
  10173. }
  10174. var intersectInfo = null;
  10175. // Octrees
  10176. var subMeshes;
  10177. var len;
  10178. if (this._submeshesOctree && this.useOctreeForPicking) {
  10179. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10180. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10181. len = intersections.length;
  10182. subMeshes = intersections.data;
  10183. }
  10184. else {
  10185. subMeshes = this.subMeshes;
  10186. len = subMeshes.length;
  10187. }
  10188. for (var index = 0; index < len; index++) {
  10189. var subMesh = subMeshes[index];
  10190. // Bounding test
  10191. if (len > 1 && !subMesh.canIntersects(ray))
  10192. continue;
  10193. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10194. if (currentIntersectInfo) {
  10195. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10196. intersectInfo = currentIntersectInfo;
  10197. intersectInfo.subMeshId = index;
  10198. if (fastCheck) {
  10199. break;
  10200. }
  10201. }
  10202. }
  10203. }
  10204. if (intersectInfo) {
  10205. // Get picked point
  10206. var world = this.getWorldMatrix();
  10207. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10208. var direction = ray.direction.clone();
  10209. direction = direction.scale(intersectInfo.distance);
  10210. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10211. var pickedPoint = worldOrigin.add(worldDirection);
  10212. // Return result
  10213. pickingInfo.hit = true;
  10214. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10215. pickingInfo.pickedPoint = pickedPoint;
  10216. pickingInfo.pickedMesh = this;
  10217. pickingInfo.bu = intersectInfo.bu;
  10218. pickingInfo.bv = intersectInfo.bv;
  10219. pickingInfo.faceId = intersectInfo.faceId;
  10220. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10221. return pickingInfo;
  10222. }
  10223. return pickingInfo;
  10224. };
  10225. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10226. return null;
  10227. };
  10228. AbstractMesh.prototype.releaseSubMeshes = function () {
  10229. if (this.subMeshes) {
  10230. while (this.subMeshes.length) {
  10231. this.subMeshes[0].dispose();
  10232. }
  10233. }
  10234. else {
  10235. this.subMeshes = new Array();
  10236. }
  10237. };
  10238. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10239. var _this = this;
  10240. var index;
  10241. // Action manager
  10242. if (this.actionManager) {
  10243. this.actionManager.dispose();
  10244. this.actionManager = null;
  10245. }
  10246. // Skeleton
  10247. this.skeleton = null;
  10248. // Animations
  10249. this.getScene().stopAnimation(this);
  10250. // Physics
  10251. if (this.physicsImpostor) {
  10252. this.physicsImpostor.dispose();
  10253. }
  10254. // Intersections in progress
  10255. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10256. var other = this._intersectionsInProgress[index];
  10257. var pos = other._intersectionsInProgress.indexOf(this);
  10258. other._intersectionsInProgress.splice(pos, 1);
  10259. }
  10260. this._intersectionsInProgress = [];
  10261. // Lights
  10262. var lights = this.getScene().lights;
  10263. lights.forEach(function (light) {
  10264. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  10265. if (meshIndex !== -1) {
  10266. light.includedOnlyMeshes.splice(meshIndex, 1);
  10267. }
  10268. meshIndex = light.excludedMeshes.indexOf(_this);
  10269. if (meshIndex !== -1) {
  10270. light.excludedMeshes.splice(meshIndex, 1);
  10271. }
  10272. });
  10273. // Edges
  10274. if (this._edgesRenderer) {
  10275. this._edgesRenderer.dispose();
  10276. this._edgesRenderer = null;
  10277. }
  10278. // SubMeshes
  10279. this.releaseSubMeshes();
  10280. // Remove from scene
  10281. this.getScene().removeMesh(this);
  10282. if (!doNotRecurse) {
  10283. // Particles
  10284. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10285. if (this.getScene().particleSystems[index].emitter === this) {
  10286. this.getScene().particleSystems[index].dispose();
  10287. index--;
  10288. }
  10289. }
  10290. // Children
  10291. var objects = this.getDescendants(true);
  10292. for (index = 0; index < objects.length; index++) {
  10293. objects[index].dispose();
  10294. }
  10295. }
  10296. else {
  10297. var childMeshes = this.getChildMeshes(true);
  10298. for (index = 0; index < childMeshes.length; index++) {
  10299. var child = childMeshes[index];
  10300. child.parent = null;
  10301. child.computeWorldMatrix(true);
  10302. }
  10303. }
  10304. _super.prototype.dispose.call(this);
  10305. this.onAfterWorldMatrixUpdateObservable.clear();
  10306. this.onCollideObservable.clear();
  10307. this.onCollisionPositionChangeObservable.clear();
  10308. this._isDisposed = true;
  10309. // Callback
  10310. this.onDisposeObservable.notifyObservers(this);
  10311. this.onDisposeObservable.clear();
  10312. };
  10313. // Statics
  10314. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10315. AbstractMesh._BILLBOARDMODE_X = 1;
  10316. AbstractMesh._BILLBOARDMODE_Y = 2;
  10317. AbstractMesh._BILLBOARDMODE_Z = 4;
  10318. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10319. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  10320. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  10321. return AbstractMesh;
  10322. }(BABYLON.Node));
  10323. BABYLON.AbstractMesh = AbstractMesh;
  10324. })(BABYLON || (BABYLON = {}));
  10325. var BABYLON;
  10326. (function (BABYLON) {
  10327. var Light = (function (_super) {
  10328. __extends(Light, _super);
  10329. function Light(name, scene) {
  10330. _super.call(this, name, scene);
  10331. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  10332. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  10333. this.intensity = 1.0;
  10334. this.range = Number.MAX_VALUE;
  10335. this.includeOnlyWithLayerMask = 0;
  10336. this.includedOnlyMeshes = new Array();
  10337. this.excludedMeshes = new Array();
  10338. this.excludeWithLayerMask = 0;
  10339. // PBR Properties.
  10340. this.radius = 0.00001;
  10341. this._excludedMeshesIds = new Array();
  10342. this._includedOnlyMeshesIds = new Array();
  10343. scene.addLight(this);
  10344. }
  10345. /**
  10346. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10347. */
  10348. Light.prototype.toString = function (fullDetails) {
  10349. var ret = "Name: " + this.name;
  10350. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  10351. if (this.animations) {
  10352. for (var i = 0; i < this.animations.length; i++) {
  10353. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  10354. }
  10355. }
  10356. if (fullDetails) {
  10357. }
  10358. return ret;
  10359. };
  10360. Light.prototype.getShadowGenerator = function () {
  10361. return this._shadowGenerator;
  10362. };
  10363. Light.prototype.getAbsolutePosition = function () {
  10364. return BABYLON.Vector3.Zero();
  10365. };
  10366. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  10367. };
  10368. Light.prototype._getWorldMatrix = function () {
  10369. return BABYLON.Matrix.Identity();
  10370. };
  10371. Light.prototype.canAffectMesh = function (mesh) {
  10372. if (!mesh) {
  10373. return true;
  10374. }
  10375. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  10376. return false;
  10377. }
  10378. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  10379. return false;
  10380. }
  10381. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  10382. return false;
  10383. }
  10384. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  10385. return false;
  10386. }
  10387. return true;
  10388. };
  10389. Light.prototype.getWorldMatrix = function () {
  10390. this._currentRenderId = this.getScene().getRenderId();
  10391. var worldMatrix = this._getWorldMatrix();
  10392. if (this.parent && this.parent.getWorldMatrix) {
  10393. if (!this._parentedWorldMatrix) {
  10394. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  10395. }
  10396. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  10397. this._markSyncedWithParent();
  10398. return this._parentedWorldMatrix;
  10399. }
  10400. return worldMatrix;
  10401. };
  10402. Light.prototype.dispose = function () {
  10403. if (this._shadowGenerator) {
  10404. this._shadowGenerator.dispose();
  10405. this._shadowGenerator = null;
  10406. }
  10407. // Animations
  10408. this.getScene().stopAnimation(this);
  10409. // Remove from scene
  10410. this.getScene().removeLight(this);
  10411. _super.prototype.dispose.call(this);
  10412. };
  10413. Light.prototype.getTypeID = function () {
  10414. return 0;
  10415. };
  10416. Light.prototype.clone = function (name) {
  10417. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  10418. };
  10419. Light.prototype.serialize = function () {
  10420. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  10421. // Type
  10422. serializationObject.type = this.getTypeID();
  10423. // Parent
  10424. if (this.parent) {
  10425. serializationObject.parentId = this.parent.id;
  10426. }
  10427. // Inclusion / exclusions
  10428. if (this.excludedMeshes.length > 0) {
  10429. serializationObject.excludedMeshesIds = [];
  10430. this.excludedMeshes.forEach(function (mesh) {
  10431. serializationObject.excludedMeshesIds.push(mesh.id);
  10432. });
  10433. }
  10434. if (this.includedOnlyMeshes.length > 0) {
  10435. serializationObject.includedOnlyMeshesIds = [];
  10436. this.includedOnlyMeshes.forEach(function (mesh) {
  10437. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  10438. });
  10439. }
  10440. // Animations
  10441. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10442. serializationObject.ranges = this.serializeAnimationRanges();
  10443. return serializationObject;
  10444. };
  10445. Light.GetConstructorFromName = function (type, name, scene) {
  10446. switch (type) {
  10447. case 0:
  10448. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  10449. case 1:
  10450. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  10451. case 2:
  10452. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  10453. case 3:
  10454. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  10455. }
  10456. };
  10457. Light.Parse = function (parsedLight, scene) {
  10458. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  10459. // Inclusion / exclusions
  10460. if (parsedLight.excludedMeshesIds) {
  10461. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  10462. }
  10463. if (parsedLight.includedOnlyMeshesIds) {
  10464. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  10465. }
  10466. // Parent
  10467. if (parsedLight.parentId) {
  10468. light._waitingParentId = parsedLight.parentId;
  10469. }
  10470. // Animations
  10471. if (parsedLight.animations) {
  10472. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  10473. var parsedAnimation = parsedLight.animations[animationIndex];
  10474. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10475. }
  10476. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  10477. }
  10478. if (parsedLight.autoAnimate) {
  10479. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  10480. }
  10481. return light;
  10482. };
  10483. __decorate([
  10484. BABYLON.serializeAsColor3()
  10485. ], Light.prototype, "diffuse", void 0);
  10486. __decorate([
  10487. BABYLON.serializeAsColor3()
  10488. ], Light.prototype, "specular", void 0);
  10489. __decorate([
  10490. BABYLON.serialize()
  10491. ], Light.prototype, "intensity", void 0);
  10492. __decorate([
  10493. BABYLON.serialize()
  10494. ], Light.prototype, "range", void 0);
  10495. __decorate([
  10496. BABYLON.serialize()
  10497. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  10498. __decorate([
  10499. BABYLON.serialize()
  10500. ], Light.prototype, "excludeWithLayerMask", void 0);
  10501. __decorate([
  10502. BABYLON.serialize()
  10503. ], Light.prototype, "radius", void 0);
  10504. return Light;
  10505. }(BABYLON.Node));
  10506. BABYLON.Light = Light;
  10507. })(BABYLON || (BABYLON = {}));
  10508. var BABYLON;
  10509. (function (BABYLON) {
  10510. var PointLight = (function (_super) {
  10511. __extends(PointLight, _super);
  10512. function PointLight(name, position, scene) {
  10513. _super.call(this, name, scene);
  10514. this.position = position;
  10515. }
  10516. PointLight.prototype.getAbsolutePosition = function () {
  10517. return this.transformedPosition ? this.transformedPosition : this.position;
  10518. };
  10519. PointLight.prototype.computeTransformedPosition = function () {
  10520. if (this.parent && this.parent.getWorldMatrix) {
  10521. if (!this.transformedPosition) {
  10522. this.transformedPosition = BABYLON.Vector3.Zero();
  10523. }
  10524. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10525. return true;
  10526. }
  10527. return false;
  10528. };
  10529. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  10530. if (this.parent && this.parent.getWorldMatrix) {
  10531. this.computeTransformedPosition();
  10532. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  10533. return;
  10534. }
  10535. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  10536. };
  10537. PointLight.prototype.needCube = function () {
  10538. return true;
  10539. };
  10540. PointLight.prototype.supportsVSM = function () {
  10541. return false;
  10542. };
  10543. PointLight.prototype.needRefreshPerFrame = function () {
  10544. return false;
  10545. };
  10546. PointLight.prototype.getShadowDirection = function (faceIndex) {
  10547. switch (faceIndex) {
  10548. case 0:
  10549. return new BABYLON.Vector3(1, 0, 0);
  10550. case 1:
  10551. return new BABYLON.Vector3(-1, 0, 0);
  10552. case 2:
  10553. return new BABYLON.Vector3(0, -1, 0);
  10554. case 3:
  10555. return new BABYLON.Vector3(0, 1, 0);
  10556. case 4:
  10557. return new BABYLON.Vector3(0, 0, 1);
  10558. case 5:
  10559. return new BABYLON.Vector3(0, 0, -1);
  10560. }
  10561. return BABYLON.Vector3.Zero();
  10562. };
  10563. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10564. var activeCamera = this.getScene().activeCamera;
  10565. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  10566. };
  10567. PointLight.prototype._getWorldMatrix = function () {
  10568. if (!this._worldMatrix) {
  10569. this._worldMatrix = BABYLON.Matrix.Identity();
  10570. }
  10571. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10572. return this._worldMatrix;
  10573. };
  10574. PointLight.prototype.getTypeID = function () {
  10575. return 0;
  10576. };
  10577. __decorate([
  10578. BABYLON.serializeAsVector3()
  10579. ], PointLight.prototype, "position", void 0);
  10580. return PointLight;
  10581. }(BABYLON.Light));
  10582. BABYLON.PointLight = PointLight;
  10583. })(BABYLON || (BABYLON = {}));
  10584. var BABYLON;
  10585. (function (BABYLON) {
  10586. var SpotLight = (function (_super) {
  10587. __extends(SpotLight, _super);
  10588. function SpotLight(name, position, direction, angle, exponent, scene) {
  10589. _super.call(this, name, scene);
  10590. this.position = position;
  10591. this.direction = direction;
  10592. this.angle = angle;
  10593. this.exponent = exponent;
  10594. }
  10595. SpotLight.prototype.getAbsolutePosition = function () {
  10596. return this.transformedPosition ? this.transformedPosition : this.position;
  10597. };
  10598. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10599. var activeCamera = this.getScene().activeCamera;
  10600. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  10601. };
  10602. SpotLight.prototype.needCube = function () {
  10603. return false;
  10604. };
  10605. SpotLight.prototype.supportsVSM = function () {
  10606. return true;
  10607. };
  10608. SpotLight.prototype.needRefreshPerFrame = function () {
  10609. return false;
  10610. };
  10611. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  10612. return this.direction;
  10613. };
  10614. SpotLight.prototype.setDirectionToTarget = function (target) {
  10615. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  10616. return this.direction;
  10617. };
  10618. SpotLight.prototype.computeTransformedPosition = function () {
  10619. if (this.parent && this.parent.getWorldMatrix) {
  10620. if (!this.transformedPosition) {
  10621. this.transformedPosition = BABYLON.Vector3.Zero();
  10622. }
  10623. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10624. return true;
  10625. }
  10626. return false;
  10627. };
  10628. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  10629. var normalizeDirection;
  10630. if (this.parent && this.parent.getWorldMatrix) {
  10631. if (!this._transformedDirection) {
  10632. this._transformedDirection = BABYLON.Vector3.Zero();
  10633. }
  10634. this.computeTransformedPosition();
  10635. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  10636. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  10637. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  10638. }
  10639. else {
  10640. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  10641. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  10642. }
  10643. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  10644. };
  10645. SpotLight.prototype._getWorldMatrix = function () {
  10646. if (!this._worldMatrix) {
  10647. this._worldMatrix = BABYLON.Matrix.Identity();
  10648. }
  10649. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10650. return this._worldMatrix;
  10651. };
  10652. SpotLight.prototype.getTypeID = function () {
  10653. return 2;
  10654. };
  10655. __decorate([
  10656. BABYLON.serializeAsVector3()
  10657. ], SpotLight.prototype, "position", void 0);
  10658. __decorate([
  10659. BABYLON.serializeAsVector3()
  10660. ], SpotLight.prototype, "direction", void 0);
  10661. __decorate([
  10662. BABYLON.serialize()
  10663. ], SpotLight.prototype, "angle", void 0);
  10664. __decorate([
  10665. BABYLON.serialize()
  10666. ], SpotLight.prototype, "exponent", void 0);
  10667. return SpotLight;
  10668. }(BABYLON.Light));
  10669. BABYLON.SpotLight = SpotLight;
  10670. })(BABYLON || (BABYLON = {}));
  10671. var BABYLON;
  10672. (function (BABYLON) {
  10673. var HemisphericLight = (function (_super) {
  10674. __extends(HemisphericLight, _super);
  10675. function HemisphericLight(name, direction, scene) {
  10676. _super.call(this, name, scene);
  10677. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  10678. this.direction = direction;
  10679. }
  10680. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  10681. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  10682. return this.direction;
  10683. };
  10684. HemisphericLight.prototype.getShadowGenerator = function () {
  10685. return null;
  10686. };
  10687. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  10688. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  10689. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  10690. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  10691. };
  10692. HemisphericLight.prototype._getWorldMatrix = function () {
  10693. if (!this._worldMatrix) {
  10694. this._worldMatrix = BABYLON.Matrix.Identity();
  10695. }
  10696. return this._worldMatrix;
  10697. };
  10698. HemisphericLight.prototype.getTypeID = function () {
  10699. return 3;
  10700. };
  10701. __decorate([
  10702. BABYLON.serializeAsColor3()
  10703. ], HemisphericLight.prototype, "groundColor", void 0);
  10704. __decorate([
  10705. BABYLON.serializeAsVector3()
  10706. ], HemisphericLight.prototype, "direction", void 0);
  10707. return HemisphericLight;
  10708. }(BABYLON.Light));
  10709. BABYLON.HemisphericLight = HemisphericLight;
  10710. })(BABYLON || (BABYLON = {}));
  10711. var BABYLON;
  10712. (function (BABYLON) {
  10713. var DirectionalLight = (function (_super) {
  10714. __extends(DirectionalLight, _super);
  10715. function DirectionalLight(name, direction, scene) {
  10716. _super.call(this, name, scene);
  10717. this.shadowOrthoScale = 0.5;
  10718. this.autoUpdateExtends = true;
  10719. // Cache
  10720. this._orthoLeft = Number.MAX_VALUE;
  10721. this._orthoRight = Number.MIN_VALUE;
  10722. this._orthoTop = Number.MIN_VALUE;
  10723. this._orthoBottom = Number.MAX_VALUE;
  10724. this.position = direction.scale(-1);
  10725. this.direction = direction;
  10726. }
  10727. DirectionalLight.prototype.getAbsolutePosition = function () {
  10728. return this.transformedPosition ? this.transformedPosition : this.position;
  10729. };
  10730. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  10731. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  10732. return this.direction;
  10733. };
  10734. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10735. var activeCamera = this.getScene().activeCamera;
  10736. // Check extends
  10737. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  10738. var tempVector3 = BABYLON.Vector3.Zero();
  10739. this._orthoLeft = Number.MAX_VALUE;
  10740. this._orthoRight = Number.MIN_VALUE;
  10741. this._orthoTop = Number.MIN_VALUE;
  10742. this._orthoBottom = Number.MAX_VALUE;
  10743. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  10744. var mesh = renderList[meshIndex];
  10745. if (!mesh) {
  10746. continue;
  10747. }
  10748. var boundingInfo = mesh.getBoundingInfo();
  10749. if (!boundingInfo) {
  10750. continue;
  10751. }
  10752. var boundingBox = boundingInfo.boundingBox;
  10753. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  10754. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  10755. if (tempVector3.x < this._orthoLeft)
  10756. this._orthoLeft = tempVector3.x;
  10757. if (tempVector3.y < this._orthoBottom)
  10758. this._orthoBottom = tempVector3.y;
  10759. if (tempVector3.x > this._orthoRight)
  10760. this._orthoRight = tempVector3.x;
  10761. if (tempVector3.y > this._orthoTop)
  10762. this._orthoTop = tempVector3.y;
  10763. }
  10764. }
  10765. }
  10766. var xOffset = this._orthoRight - this._orthoLeft;
  10767. var yOffset = this._orthoTop - this._orthoBottom;
  10768. 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);
  10769. };
  10770. DirectionalLight.prototype.supportsVSM = function () {
  10771. return true;
  10772. };
  10773. DirectionalLight.prototype.needRefreshPerFrame = function () {
  10774. return true;
  10775. };
  10776. DirectionalLight.prototype.needCube = function () {
  10777. return false;
  10778. };
  10779. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  10780. return this.direction;
  10781. };
  10782. DirectionalLight.prototype.computeTransformedPosition = function () {
  10783. if (this.parent && this.parent.getWorldMatrix) {
  10784. if (!this.transformedPosition) {
  10785. this.transformedPosition = BABYLON.Vector3.Zero();
  10786. }
  10787. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10788. return true;
  10789. }
  10790. return false;
  10791. };
  10792. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  10793. if (this.parent && this.parent.getWorldMatrix) {
  10794. if (!this._transformedDirection) {
  10795. this._transformedDirection = BABYLON.Vector3.Zero();
  10796. }
  10797. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  10798. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  10799. return;
  10800. }
  10801. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  10802. };
  10803. DirectionalLight.prototype._getWorldMatrix = function () {
  10804. if (!this._worldMatrix) {
  10805. this._worldMatrix = BABYLON.Matrix.Identity();
  10806. }
  10807. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10808. return this._worldMatrix;
  10809. };
  10810. DirectionalLight.prototype.getTypeID = function () {
  10811. return 1;
  10812. };
  10813. __decorate([
  10814. BABYLON.serializeAsVector3()
  10815. ], DirectionalLight.prototype, "position", void 0);
  10816. __decorate([
  10817. BABYLON.serializeAsVector3()
  10818. ], DirectionalLight.prototype, "direction", void 0);
  10819. __decorate([
  10820. BABYLON.serialize()
  10821. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  10822. __decorate([
  10823. BABYLON.serialize()
  10824. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  10825. return DirectionalLight;
  10826. }(BABYLON.Light));
  10827. BABYLON.DirectionalLight = DirectionalLight;
  10828. })(BABYLON || (BABYLON = {}));
  10829. var BABYLON;
  10830. (function (BABYLON) {
  10831. var ShadowGenerator = (function () {
  10832. function ShadowGenerator(mapSize, light) {
  10833. var _this = this;
  10834. // Members
  10835. this._filter = ShadowGenerator.FILTER_NONE;
  10836. this.blurScale = 2;
  10837. this._blurBoxOffset = 0;
  10838. this._bias = 0.00005;
  10839. this._lightDirection = BABYLON.Vector3.Zero();
  10840. this.forceBackFacesOnly = false;
  10841. this._darkness = 0;
  10842. this._transparencyShadow = false;
  10843. this._viewMatrix = BABYLON.Matrix.Zero();
  10844. this._projectionMatrix = BABYLON.Matrix.Zero();
  10845. this._transformMatrix = BABYLON.Matrix.Zero();
  10846. this._worldViewProjection = BABYLON.Matrix.Zero();
  10847. this._currentFaceIndex = 0;
  10848. this._currentFaceIndexCache = 0;
  10849. this._useFullFloat = true;
  10850. this._light = light;
  10851. this._scene = light.getScene();
  10852. this._mapSize = mapSize;
  10853. light._shadowGenerator = this;
  10854. // Texture type fallback from float to int if not supported.
  10855. var textureType;
  10856. var caps = this._scene.getEngine().getCaps();
  10857. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  10858. this._useFullFloat = true;
  10859. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  10860. }
  10861. else {
  10862. this._useFullFloat = false;
  10863. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  10864. }
  10865. // Render target
  10866. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  10867. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10868. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10869. this._shadowMap.anisotropicFilteringLevel = 1;
  10870. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10871. this._shadowMap.renderParticles = false;
  10872. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  10873. _this._currentFaceIndex = faceIndex;
  10874. });
  10875. this._shadowMap.onAfterUnbindObservable.add(function () {
  10876. if (!_this.useBlurVarianceShadowMap) {
  10877. return;
  10878. }
  10879. if (!_this._shadowMap2) {
  10880. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  10881. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10882. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10883. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  10884. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  10885. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  10886. effect.setTexture("textureSampler", _this._shadowMap);
  10887. });
  10888. _this.blurBoxOffset = 1;
  10889. }
  10890. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  10891. });
  10892. // Custom render function
  10893. var renderSubMesh = function (subMesh) {
  10894. var mesh = subMesh.getRenderingMesh();
  10895. var scene = _this._scene;
  10896. var engine = scene.getEngine();
  10897. // Culling
  10898. engine.setState(subMesh.getMaterial().backFaceCulling);
  10899. // Managing instances
  10900. var batch = mesh._getInstancesRenderList(subMesh._id);
  10901. if (batch.mustReturn) {
  10902. return;
  10903. }
  10904. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10905. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  10906. engine.enableEffect(_this._effect);
  10907. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  10908. var material = subMesh.getMaterial();
  10909. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  10910. _this._effect.setVector3("lightPosition", _this.getLight().position);
  10911. if (_this.getLight().needCube()) {
  10912. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  10913. }
  10914. // Alpha test
  10915. if (material && material.needAlphaTesting()) {
  10916. var alphaTexture = material.getAlphaTestTexture();
  10917. _this._effect.setTexture("diffuseSampler", alphaTexture);
  10918. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  10919. }
  10920. // Bones
  10921. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10922. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  10923. }
  10924. if (_this.forceBackFacesOnly) {
  10925. engine.setState(true, 0, false, true);
  10926. }
  10927. // Draw
  10928. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  10929. if (_this.forceBackFacesOnly) {
  10930. engine.setState(true, 0, false, false);
  10931. }
  10932. }
  10933. else {
  10934. // Need to reset refresh rate of the shadowMap
  10935. _this._shadowMap.resetRefreshCounter();
  10936. }
  10937. };
  10938. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  10939. var index;
  10940. for (index = 0; index < opaqueSubMeshes.length; index++) {
  10941. renderSubMesh(opaqueSubMeshes.data[index]);
  10942. }
  10943. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  10944. renderSubMesh(alphaTestSubMeshes.data[index]);
  10945. }
  10946. if (_this._transparencyShadow) {
  10947. for (index = 0; index < transparentSubMeshes.length; index++) {
  10948. renderSubMesh(transparentSubMeshes.data[index]);
  10949. }
  10950. }
  10951. };
  10952. this._shadowMap.onClearObservable.add(function (engine) {
  10953. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  10954. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  10955. }
  10956. else {
  10957. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  10958. }
  10959. });
  10960. }
  10961. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  10962. // Static
  10963. get: function () {
  10964. return ShadowGenerator._FILTER_NONE;
  10965. },
  10966. enumerable: true,
  10967. configurable: true
  10968. });
  10969. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  10970. get: function () {
  10971. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  10972. },
  10973. enumerable: true,
  10974. configurable: true
  10975. });
  10976. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  10977. get: function () {
  10978. return ShadowGenerator._FILTER_POISSONSAMPLING;
  10979. },
  10980. enumerable: true,
  10981. configurable: true
  10982. });
  10983. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  10984. get: function () {
  10985. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  10986. },
  10987. enumerable: true,
  10988. configurable: true
  10989. });
  10990. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  10991. get: function () {
  10992. return this._bias;
  10993. },
  10994. set: function (bias) {
  10995. this._bias = bias;
  10996. },
  10997. enumerable: true,
  10998. configurable: true
  10999. });
  11000. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  11001. get: function () {
  11002. return this._blurBoxOffset;
  11003. },
  11004. set: function (value) {
  11005. var _this = this;
  11006. if (this._blurBoxOffset === value) {
  11007. return;
  11008. }
  11009. this._blurBoxOffset = value;
  11010. if (this._boxBlurPostprocess) {
  11011. this._boxBlurPostprocess.dispose();
  11012. }
  11013. 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);
  11014. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  11015. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  11016. });
  11017. },
  11018. enumerable: true,
  11019. configurable: true
  11020. });
  11021. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  11022. get: function () {
  11023. return this._filter;
  11024. },
  11025. set: function (value) {
  11026. if (this._filter === value) {
  11027. return;
  11028. }
  11029. this._filter = value;
  11030. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  11031. this._shadowMap.anisotropicFilteringLevel = 16;
  11032. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  11033. }
  11034. else {
  11035. this._shadowMap.anisotropicFilteringLevel = 1;
  11036. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11037. }
  11038. },
  11039. enumerable: true,
  11040. configurable: true
  11041. });
  11042. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  11043. get: function () {
  11044. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  11045. },
  11046. set: function (value) {
  11047. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11048. },
  11049. enumerable: true,
  11050. configurable: true
  11051. });
  11052. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  11053. get: function () {
  11054. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  11055. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  11056. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  11057. },
  11058. set: function (value) {
  11059. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  11060. },
  11061. enumerable: true,
  11062. configurable: true
  11063. });
  11064. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  11065. get: function () {
  11066. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  11067. },
  11068. set: function (value) {
  11069. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11070. },
  11071. enumerable: true,
  11072. configurable: true
  11073. });
  11074. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  11075. var defines = [];
  11076. if (this._useFullFloat) {
  11077. defines.push("#define FULLFLOAT");
  11078. }
  11079. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  11080. defines.push("#define VSM");
  11081. }
  11082. if (this.getLight().needCube()) {
  11083. defines.push("#define CUBEMAP");
  11084. }
  11085. var attribs = [BABYLON.VertexBuffer.PositionKind];
  11086. var mesh = subMesh.getMesh();
  11087. var material = subMesh.getMaterial();
  11088. // Alpha test
  11089. if (material && material.needAlphaTesting()) {
  11090. defines.push("#define ALPHATEST");
  11091. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11092. attribs.push(BABYLON.VertexBuffer.UVKind);
  11093. defines.push("#define UV1");
  11094. }
  11095. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  11096. var alphaTexture = material.getAlphaTestTexture();
  11097. if (alphaTexture.coordinatesIndex === 1) {
  11098. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  11099. defines.push("#define UV2");
  11100. }
  11101. }
  11102. }
  11103. // Bones
  11104. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11105. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  11106. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  11107. if (mesh.numBoneInfluencers > 4) {
  11108. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  11109. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  11110. }
  11111. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  11112. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  11113. }
  11114. else {
  11115. defines.push("#define NUM_BONE_INFLUENCERS 0");
  11116. }
  11117. // Instances
  11118. if (useInstances) {
  11119. defines.push("#define INSTANCES");
  11120. attribs.push("world0");
  11121. attribs.push("world1");
  11122. attribs.push("world2");
  11123. attribs.push("world3");
  11124. }
  11125. // Get correct effect
  11126. var join = defines.join("\n");
  11127. if (this._cachedDefines !== join) {
  11128. this._cachedDefines = join;
  11129. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  11130. }
  11131. return this._effect.isReady();
  11132. };
  11133. ShadowGenerator.prototype.getShadowMap = function () {
  11134. return this._shadowMap;
  11135. };
  11136. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  11137. if (this._shadowMap2) {
  11138. return this._shadowMap2;
  11139. }
  11140. return this._shadowMap;
  11141. };
  11142. ShadowGenerator.prototype.getLight = function () {
  11143. return this._light;
  11144. };
  11145. // Methods
  11146. ShadowGenerator.prototype.getTransformMatrix = function () {
  11147. var scene = this._scene;
  11148. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  11149. return this._transformMatrix;
  11150. }
  11151. this._currentRenderID = scene.getRenderId();
  11152. this._currentFaceIndexCache = this._currentFaceIndex;
  11153. var lightPosition = this._light.position;
  11154. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  11155. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  11156. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  11157. }
  11158. if (this._light.computeTransformedPosition()) {
  11159. lightPosition = this._light.transformedPosition;
  11160. }
  11161. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  11162. this._cachedPosition = lightPosition.clone();
  11163. this._cachedDirection = this._lightDirection.clone();
  11164. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  11165. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  11166. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  11167. }
  11168. return this._transformMatrix;
  11169. };
  11170. ShadowGenerator.prototype.getDarkness = function () {
  11171. return this._darkness;
  11172. };
  11173. ShadowGenerator.prototype.setDarkness = function (darkness) {
  11174. if (darkness >= 1.0)
  11175. this._darkness = 1.0;
  11176. else if (darkness <= 0.0)
  11177. this._darkness = 0.0;
  11178. else
  11179. this._darkness = darkness;
  11180. };
  11181. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  11182. this._transparencyShadow = hasShadow;
  11183. };
  11184. ShadowGenerator.prototype._packHalf = function (depth) {
  11185. var scale = depth * 255.0;
  11186. var fract = scale - Math.floor(scale);
  11187. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  11188. };
  11189. ShadowGenerator.prototype.dispose = function () {
  11190. this._shadowMap.dispose();
  11191. if (this._shadowMap2) {
  11192. this._shadowMap2.dispose();
  11193. }
  11194. if (this._downSamplePostprocess) {
  11195. this._downSamplePostprocess.dispose();
  11196. }
  11197. if (this._boxBlurPostprocess) {
  11198. this._boxBlurPostprocess.dispose();
  11199. }
  11200. };
  11201. ShadowGenerator.prototype.serialize = function () {
  11202. var serializationObject = {};
  11203. serializationObject.lightId = this._light.id;
  11204. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  11205. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  11206. serializationObject.usePoissonSampling = this.usePoissonSampling;
  11207. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  11208. serializationObject.renderList = [];
  11209. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  11210. var mesh = this.getShadowMap().renderList[meshIndex];
  11211. serializationObject.renderList.push(mesh.id);
  11212. }
  11213. return serializationObject;
  11214. };
  11215. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  11216. //casting to point light, as light is missing the position attr and typescript complains.
  11217. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  11218. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  11219. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  11220. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  11221. meshes.forEach(function (mesh) {
  11222. shadowGenerator.getShadowMap().renderList.push(mesh);
  11223. });
  11224. }
  11225. if (parsedShadowGenerator.usePoissonSampling) {
  11226. shadowGenerator.usePoissonSampling = true;
  11227. }
  11228. else if (parsedShadowGenerator.useVarianceShadowMap) {
  11229. shadowGenerator.useVarianceShadowMap = true;
  11230. }
  11231. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  11232. shadowGenerator.useBlurVarianceShadowMap = true;
  11233. if (parsedShadowGenerator.blurScale) {
  11234. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  11235. }
  11236. if (parsedShadowGenerator.blurBoxOffset) {
  11237. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  11238. }
  11239. }
  11240. if (parsedShadowGenerator.bias !== undefined) {
  11241. shadowGenerator.bias = parsedShadowGenerator.bias;
  11242. }
  11243. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  11244. return shadowGenerator;
  11245. };
  11246. ShadowGenerator._FILTER_NONE = 0;
  11247. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  11248. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  11249. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  11250. return ShadowGenerator;
  11251. }());
  11252. BABYLON.ShadowGenerator = ShadowGenerator;
  11253. })(BABYLON || (BABYLON = {}));
  11254. var BABYLON;
  11255. (function (BABYLON) {
  11256. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  11257. if (boxMin.x > sphereCenter.x + sphereRadius)
  11258. return false;
  11259. if (sphereCenter.x - sphereRadius > boxMax.x)
  11260. return false;
  11261. if (boxMin.y > sphereCenter.y + sphereRadius)
  11262. return false;
  11263. if (sphereCenter.y - sphereRadius > boxMax.y)
  11264. return false;
  11265. if (boxMin.z > sphereCenter.z + sphereRadius)
  11266. return false;
  11267. if (sphereCenter.z - sphereRadius > boxMax.z)
  11268. return false;
  11269. return true;
  11270. };
  11271. var getLowestRoot = (function () {
  11272. var result = { root: 0, found: false };
  11273. return function (a, b, c, maxR) {
  11274. result.root = 0;
  11275. result.found = false;
  11276. var determinant = b * b - 4.0 * a * c;
  11277. if (determinant < 0)
  11278. return result;
  11279. var sqrtD = Math.sqrt(determinant);
  11280. var r1 = (-b - sqrtD) / (2.0 * a);
  11281. var r2 = (-b + sqrtD) / (2.0 * a);
  11282. if (r1 > r2) {
  11283. var temp = r2;
  11284. r2 = r1;
  11285. r1 = temp;
  11286. }
  11287. if (r1 > 0 && r1 < maxR) {
  11288. result.root = r1;
  11289. result.found = true;
  11290. return result;
  11291. }
  11292. if (r2 > 0 && r2 < maxR) {
  11293. result.root = r2;
  11294. result.found = true;
  11295. return result;
  11296. }
  11297. return result;
  11298. };
  11299. })();
  11300. var Collider = (function () {
  11301. function Collider() {
  11302. this.radius = new BABYLON.Vector3(1, 1, 1);
  11303. this.retry = 0;
  11304. this.basePointWorld = BABYLON.Vector3.Zero();
  11305. this.velocityWorld = BABYLON.Vector3.Zero();
  11306. this.normalizedVelocity = BABYLON.Vector3.Zero();
  11307. this._collisionPoint = BABYLON.Vector3.Zero();
  11308. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  11309. this._tempVector = BABYLON.Vector3.Zero();
  11310. this._tempVector2 = BABYLON.Vector3.Zero();
  11311. this._tempVector3 = BABYLON.Vector3.Zero();
  11312. this._tempVector4 = BABYLON.Vector3.Zero();
  11313. this._edge = BABYLON.Vector3.Zero();
  11314. this._baseToVertex = BABYLON.Vector3.Zero();
  11315. this._destinationPoint = BABYLON.Vector3.Zero();
  11316. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  11317. this._displacementVector = BABYLON.Vector3.Zero();
  11318. }
  11319. // Methods
  11320. Collider.prototype._initialize = function (source, dir, e) {
  11321. this.velocity = dir;
  11322. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  11323. this.basePoint = source;
  11324. source.multiplyToRef(this.radius, this.basePointWorld);
  11325. dir.multiplyToRef(this.radius, this.velocityWorld);
  11326. this.velocityWorldLength = this.velocityWorld.length();
  11327. this.epsilon = e;
  11328. this.collisionFound = false;
  11329. };
  11330. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  11331. pa.subtractToRef(point, this._tempVector);
  11332. pb.subtractToRef(point, this._tempVector2);
  11333. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  11334. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11335. if (d < 0)
  11336. return false;
  11337. pc.subtractToRef(point, this._tempVector3);
  11338. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  11339. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11340. if (d < 0)
  11341. return false;
  11342. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  11343. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11344. return d >= 0;
  11345. };
  11346. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  11347. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  11348. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  11349. if (distance > this.velocityWorldLength + max + sphereRadius) {
  11350. return false;
  11351. }
  11352. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  11353. return false;
  11354. return true;
  11355. };
  11356. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  11357. var t0;
  11358. var embeddedInPlane = false;
  11359. //defensive programming, actually not needed.
  11360. if (!trianglePlaneArray) {
  11361. trianglePlaneArray = [];
  11362. }
  11363. if (!trianglePlaneArray[faceIndex]) {
  11364. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  11365. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  11366. }
  11367. var trianglePlane = trianglePlaneArray[faceIndex];
  11368. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  11369. return;
  11370. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  11371. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  11372. if (normalDotVelocity == 0) {
  11373. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  11374. return;
  11375. embeddedInPlane = true;
  11376. t0 = 0;
  11377. }
  11378. else {
  11379. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  11380. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  11381. if (t0 > t1) {
  11382. var temp = t1;
  11383. t1 = t0;
  11384. t0 = temp;
  11385. }
  11386. if (t0 > 1.0 || t1 < 0.0)
  11387. return;
  11388. if (t0 < 0)
  11389. t0 = 0;
  11390. if (t0 > 1.0)
  11391. t0 = 1.0;
  11392. }
  11393. this._collisionPoint.copyFromFloats(0, 0, 0);
  11394. var found = false;
  11395. var t = 1.0;
  11396. if (!embeddedInPlane) {
  11397. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  11398. this.velocity.scaleToRef(t0, this._tempVector);
  11399. this._planeIntersectionPoint.addInPlace(this._tempVector);
  11400. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  11401. found = true;
  11402. t = t0;
  11403. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  11404. }
  11405. }
  11406. if (!found) {
  11407. var velocitySquaredLength = this.velocity.lengthSquared();
  11408. var a = velocitySquaredLength;
  11409. this.basePoint.subtractToRef(p1, this._tempVector);
  11410. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11411. var c = this._tempVector.lengthSquared() - 1.0;
  11412. var lowestRoot = getLowestRoot(a, b, c, t);
  11413. if (lowestRoot.found) {
  11414. t = lowestRoot.root;
  11415. found = true;
  11416. this._collisionPoint.copyFrom(p1);
  11417. }
  11418. this.basePoint.subtractToRef(p2, this._tempVector);
  11419. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11420. c = this._tempVector.lengthSquared() - 1.0;
  11421. lowestRoot = getLowestRoot(a, b, c, t);
  11422. if (lowestRoot.found) {
  11423. t = lowestRoot.root;
  11424. found = true;
  11425. this._collisionPoint.copyFrom(p2);
  11426. }
  11427. this.basePoint.subtractToRef(p3, this._tempVector);
  11428. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11429. c = this._tempVector.lengthSquared() - 1.0;
  11430. lowestRoot = getLowestRoot(a, b, c, t);
  11431. if (lowestRoot.found) {
  11432. t = lowestRoot.root;
  11433. found = true;
  11434. this._collisionPoint.copyFrom(p3);
  11435. }
  11436. p2.subtractToRef(p1, this._edge);
  11437. p1.subtractToRef(this.basePoint, this._baseToVertex);
  11438. var edgeSquaredLength = this._edge.lengthSquared();
  11439. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11440. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11441. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11442. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11443. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11444. lowestRoot = getLowestRoot(a, b, c, t);
  11445. if (lowestRoot.found) {
  11446. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11447. if (f >= 0.0 && f <= 1.0) {
  11448. t = lowestRoot.root;
  11449. found = true;
  11450. this._edge.scaleInPlace(f);
  11451. p1.addToRef(this._edge, this._collisionPoint);
  11452. }
  11453. }
  11454. p3.subtractToRef(p2, this._edge);
  11455. p2.subtractToRef(this.basePoint, this._baseToVertex);
  11456. edgeSquaredLength = this._edge.lengthSquared();
  11457. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11458. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11459. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11460. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11461. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11462. lowestRoot = getLowestRoot(a, b, c, t);
  11463. if (lowestRoot.found) {
  11464. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11465. if (f >= 0.0 && f <= 1.0) {
  11466. t = lowestRoot.root;
  11467. found = true;
  11468. this._edge.scaleInPlace(f);
  11469. p2.addToRef(this._edge, this._collisionPoint);
  11470. }
  11471. }
  11472. p1.subtractToRef(p3, this._edge);
  11473. p3.subtractToRef(this.basePoint, this._baseToVertex);
  11474. edgeSquaredLength = this._edge.lengthSquared();
  11475. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11476. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11477. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11478. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11479. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11480. lowestRoot = getLowestRoot(a, b, c, t);
  11481. if (lowestRoot.found) {
  11482. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11483. if (f >= 0.0 && f <= 1.0) {
  11484. t = lowestRoot.root;
  11485. found = true;
  11486. this._edge.scaleInPlace(f);
  11487. p3.addToRef(this._edge, this._collisionPoint);
  11488. }
  11489. }
  11490. }
  11491. if (found) {
  11492. var distToCollision = t * this.velocity.length();
  11493. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  11494. if (!this.intersectionPoint) {
  11495. this.intersectionPoint = this._collisionPoint.clone();
  11496. }
  11497. else {
  11498. this.intersectionPoint.copyFrom(this._collisionPoint);
  11499. }
  11500. this.nearestDistance = distToCollision;
  11501. this.collisionFound = true;
  11502. }
  11503. }
  11504. };
  11505. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  11506. for (var i = indexStart; i < indexEnd; i += 3) {
  11507. var p1 = pts[indices[i] - decal];
  11508. var p2 = pts[indices[i + 1] - decal];
  11509. var p3 = pts[indices[i + 2] - decal];
  11510. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  11511. }
  11512. };
  11513. Collider.prototype._getResponse = function (pos, vel) {
  11514. pos.addToRef(vel, this._destinationPoint);
  11515. vel.scaleInPlace((this.nearestDistance / vel.length()));
  11516. this.basePoint.addToRef(vel, pos);
  11517. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  11518. this._slidePlaneNormal.normalize();
  11519. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  11520. pos.addInPlace(this._displacementVector);
  11521. this.intersectionPoint.addInPlace(this._displacementVector);
  11522. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  11523. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  11524. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  11525. };
  11526. return Collider;
  11527. }());
  11528. BABYLON.Collider = Collider;
  11529. })(BABYLON || (BABYLON = {}));
  11530. var BABYLON;
  11531. (function (BABYLON) {
  11532. //WebWorker code will be inserted to this variable.
  11533. BABYLON.CollisionWorker = "";
  11534. (function (WorkerTaskType) {
  11535. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  11536. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  11537. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  11538. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  11539. var WorkerTaskType = BABYLON.WorkerTaskType;
  11540. (function (WorkerReplyType) {
  11541. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  11542. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  11543. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  11544. var WorkerReplyType = BABYLON.WorkerReplyType;
  11545. var CollisionCoordinatorWorker = (function () {
  11546. function CollisionCoordinatorWorker() {
  11547. var _this = this;
  11548. this._scaledPosition = BABYLON.Vector3.Zero();
  11549. this._scaledVelocity = BABYLON.Vector3.Zero();
  11550. this.onMeshUpdated = function (mesh) {
  11551. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  11552. };
  11553. this.onGeometryUpdated = function (geometry) {
  11554. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  11555. };
  11556. this._afterRender = function () {
  11557. if (!_this._init)
  11558. return;
  11559. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  11560. return;
  11561. }
  11562. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  11563. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  11564. if (_this._runningUpdated > 4) {
  11565. return;
  11566. }
  11567. ++_this._runningUpdated;
  11568. var payload = {
  11569. updatedMeshes: _this._addUpdateMeshesList,
  11570. updatedGeometries: _this._addUpdateGeometriesList,
  11571. removedGeometries: _this._toRemoveGeometryArray,
  11572. removedMeshes: _this._toRemoveMeshesArray
  11573. };
  11574. var message = {
  11575. payload: payload,
  11576. taskType: WorkerTaskType.UPDATE
  11577. };
  11578. var serializable = [];
  11579. for (var id in payload.updatedGeometries) {
  11580. if (payload.updatedGeometries.hasOwnProperty(id)) {
  11581. //prepare transferables
  11582. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  11583. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  11584. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  11585. }
  11586. }
  11587. _this._worker.postMessage(message, serializable);
  11588. _this._addUpdateMeshesList = {};
  11589. _this._addUpdateGeometriesList = {};
  11590. _this._toRemoveGeometryArray = [];
  11591. _this._toRemoveMeshesArray = [];
  11592. };
  11593. this._onMessageFromWorker = function (e) {
  11594. var returnData = e.data;
  11595. if (returnData.error != WorkerReplyType.SUCCESS) {
  11596. //TODO what errors can be returned from the worker?
  11597. BABYLON.Tools.Warn("error returned from worker!");
  11598. return;
  11599. }
  11600. switch (returnData.taskType) {
  11601. case WorkerTaskType.INIT:
  11602. _this._init = true;
  11603. //Update the worked with ALL of the scene's current state
  11604. _this._scene.meshes.forEach(function (mesh) {
  11605. _this.onMeshAdded(mesh);
  11606. });
  11607. _this._scene.getGeometries().forEach(function (geometry) {
  11608. _this.onGeometryAdded(geometry);
  11609. });
  11610. break;
  11611. case WorkerTaskType.UPDATE:
  11612. _this._runningUpdated--;
  11613. break;
  11614. case WorkerTaskType.COLLIDE:
  11615. _this._runningCollisionTask = false;
  11616. var returnPayload = returnData.payload;
  11617. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  11618. return;
  11619. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  11620. //cleanup
  11621. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  11622. break;
  11623. }
  11624. };
  11625. this._collisionsCallbackArray = [];
  11626. this._init = false;
  11627. this._runningUpdated = 0;
  11628. this._runningCollisionTask = false;
  11629. this._addUpdateMeshesList = {};
  11630. this._addUpdateGeometriesList = {};
  11631. this._toRemoveGeometryArray = [];
  11632. this._toRemoveMeshesArray = [];
  11633. }
  11634. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  11635. if (!this._init)
  11636. return;
  11637. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  11638. return;
  11639. position.divideToRef(collider.radius, this._scaledPosition);
  11640. velocity.divideToRef(collider.radius, this._scaledVelocity);
  11641. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  11642. var payload = {
  11643. collider: {
  11644. position: this._scaledPosition.asArray(),
  11645. velocity: this._scaledVelocity.asArray(),
  11646. radius: collider.radius.asArray()
  11647. },
  11648. collisionId: collisionIndex,
  11649. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  11650. maximumRetry: maximumRetry
  11651. };
  11652. var message = {
  11653. payload: payload,
  11654. taskType: WorkerTaskType.COLLIDE
  11655. };
  11656. this._worker.postMessage(message);
  11657. };
  11658. CollisionCoordinatorWorker.prototype.init = function (scene) {
  11659. this._scene = scene;
  11660. this._scene.registerAfterRender(this._afterRender);
  11661. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  11662. this._worker = new Worker(workerUrl);
  11663. this._worker.onmessage = this._onMessageFromWorker;
  11664. var message = {
  11665. payload: {},
  11666. taskType: WorkerTaskType.INIT
  11667. };
  11668. this._worker.postMessage(message);
  11669. };
  11670. CollisionCoordinatorWorker.prototype.destroy = function () {
  11671. this._scene.unregisterAfterRender(this._afterRender);
  11672. this._worker.terminate();
  11673. };
  11674. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  11675. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  11676. this.onMeshUpdated(mesh);
  11677. };
  11678. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  11679. this._toRemoveMeshesArray.push(mesh.uniqueId);
  11680. };
  11681. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  11682. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  11683. geometry.onGeometryUpdated = this.onGeometryUpdated;
  11684. this.onGeometryUpdated(geometry);
  11685. };
  11686. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  11687. this._toRemoveGeometryArray.push(geometry.id);
  11688. };
  11689. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  11690. var submeshes = [];
  11691. if (mesh.subMeshes) {
  11692. submeshes = mesh.subMeshes.map(function (sm, idx) {
  11693. return {
  11694. position: idx,
  11695. verticesStart: sm.verticesStart,
  11696. verticesCount: sm.verticesCount,
  11697. indexStart: sm.indexStart,
  11698. indexCount: sm.indexCount,
  11699. hasMaterial: !!sm.getMaterial(),
  11700. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  11701. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  11702. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  11703. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  11704. };
  11705. });
  11706. }
  11707. var geometryId = null;
  11708. if (mesh instanceof BABYLON.Mesh) {
  11709. geometryId = mesh.geometry ? mesh.geometry.id : null;
  11710. }
  11711. else if (mesh instanceof BABYLON.InstancedMesh) {
  11712. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  11713. }
  11714. return {
  11715. uniqueId: mesh.uniqueId,
  11716. id: mesh.id,
  11717. name: mesh.name,
  11718. geometryId: geometryId,
  11719. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  11720. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  11721. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  11722. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  11723. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  11724. subMeshes: submeshes,
  11725. checkCollisions: mesh.checkCollisions
  11726. };
  11727. };
  11728. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  11729. return {
  11730. id: geometry.id,
  11731. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  11732. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  11733. indices: new Int32Array(geometry.getIndices() || []),
  11734. };
  11735. };
  11736. return CollisionCoordinatorWorker;
  11737. }());
  11738. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  11739. var CollisionCoordinatorLegacy = (function () {
  11740. function CollisionCoordinatorLegacy() {
  11741. this._scaledPosition = BABYLON.Vector3.Zero();
  11742. this._scaledVelocity = BABYLON.Vector3.Zero();
  11743. this._finalPosition = BABYLON.Vector3.Zero();
  11744. }
  11745. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  11746. position.divideToRef(collider.radius, this._scaledPosition);
  11747. velocity.divideToRef(collider.radius, this._scaledVelocity);
  11748. collider.collidedMesh = null;
  11749. collider.retry = 0;
  11750. collider.initialVelocity = this._scaledVelocity;
  11751. collider.initialPosition = this._scaledPosition;
  11752. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  11753. this._finalPosition.multiplyInPlace(collider.radius);
  11754. //run the callback
  11755. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  11756. };
  11757. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  11758. this._scene = scene;
  11759. };
  11760. CollisionCoordinatorLegacy.prototype.destroy = function () {
  11761. //Legacy need no destruction method.
  11762. };
  11763. //No update in legacy mode
  11764. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  11765. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  11766. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  11767. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  11768. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  11769. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  11770. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  11771. if (excludedMesh === void 0) { excludedMesh = null; }
  11772. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  11773. if (collider.retry >= maximumRetry) {
  11774. finalPosition.copyFrom(position);
  11775. return;
  11776. }
  11777. collider._initialize(position, velocity, closeDistance);
  11778. // Check all meshes
  11779. for (var index = 0; index < this._scene.meshes.length; index++) {
  11780. var mesh = this._scene.meshes[index];
  11781. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  11782. mesh._checkCollision(collider);
  11783. }
  11784. }
  11785. if (!collider.collisionFound) {
  11786. position.addToRef(velocity, finalPosition);
  11787. return;
  11788. }
  11789. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  11790. collider._getResponse(position, velocity);
  11791. }
  11792. if (velocity.length() <= closeDistance) {
  11793. finalPosition.copyFrom(position);
  11794. return;
  11795. }
  11796. collider.retry++;
  11797. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  11798. };
  11799. return CollisionCoordinatorLegacy;
  11800. }());
  11801. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  11802. })(BABYLON || (BABYLON = {}));
  11803. var BABYLON;
  11804. (function (BABYLON) {
  11805. var Camera = (function (_super) {
  11806. __extends(Camera, _super);
  11807. function Camera(name, position, scene) {
  11808. _super.call(this, name, scene);
  11809. this.upVector = BABYLON.Vector3.Up();
  11810. this.orthoLeft = null;
  11811. this.orthoRight = null;
  11812. this.orthoBottom = null;
  11813. this.orthoTop = null;
  11814. this.fov = 0.8;
  11815. this.minZ = 1.0;
  11816. this.maxZ = 10000.0;
  11817. this.inertia = 0.9;
  11818. this.mode = Camera.PERSPECTIVE_CAMERA;
  11819. this.isIntermediate = false;
  11820. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  11821. this.layerMask = 0x0FFFFFFF;
  11822. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  11823. // Camera rig members
  11824. this.cameraRigMode = Camera.RIG_MODE_NONE;
  11825. this._rigCameras = new Array();
  11826. // Cache
  11827. this._computedViewMatrix = BABYLON.Matrix.Identity();
  11828. this._projectionMatrix = new BABYLON.Matrix();
  11829. this._postProcesses = new Array();
  11830. this._transformMatrix = BABYLON.Matrix.Zero();
  11831. this._activeMeshes = new BABYLON.SmartArray(256);
  11832. this._globalPosition = BABYLON.Vector3.Zero();
  11833. this._refreshFrustumPlanes = true;
  11834. scene.addCamera(this);
  11835. if (!scene.activeCamera) {
  11836. scene.activeCamera = this;
  11837. }
  11838. this.position = position;
  11839. }
  11840. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  11841. get: function () {
  11842. return Camera._PERSPECTIVE_CAMERA;
  11843. },
  11844. enumerable: true,
  11845. configurable: true
  11846. });
  11847. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  11848. get: function () {
  11849. return Camera._ORTHOGRAPHIC_CAMERA;
  11850. },
  11851. enumerable: true,
  11852. configurable: true
  11853. });
  11854. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  11855. get: function () {
  11856. return Camera._FOVMODE_VERTICAL_FIXED;
  11857. },
  11858. enumerable: true,
  11859. configurable: true
  11860. });
  11861. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  11862. get: function () {
  11863. return Camera._FOVMODE_HORIZONTAL_FIXED;
  11864. },
  11865. enumerable: true,
  11866. configurable: true
  11867. });
  11868. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  11869. get: function () {
  11870. return Camera._RIG_MODE_NONE;
  11871. },
  11872. enumerable: true,
  11873. configurable: true
  11874. });
  11875. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  11876. get: function () {
  11877. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  11878. },
  11879. enumerable: true,
  11880. configurable: true
  11881. });
  11882. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  11883. get: function () {
  11884. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  11885. },
  11886. enumerable: true,
  11887. configurable: true
  11888. });
  11889. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  11890. get: function () {
  11891. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  11892. },
  11893. enumerable: true,
  11894. configurable: true
  11895. });
  11896. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  11897. get: function () {
  11898. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  11899. },
  11900. enumerable: true,
  11901. configurable: true
  11902. });
  11903. Object.defineProperty(Camera, "RIG_MODE_VR", {
  11904. get: function () {
  11905. return Camera._RIG_MODE_VR;
  11906. },
  11907. enumerable: true,
  11908. configurable: true
  11909. });
  11910. /**
  11911. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11912. */
  11913. Camera.prototype.toString = function (fullDetails) {
  11914. var ret = "Name: " + this.name;
  11915. ret += ", type: " + this.getTypeName();
  11916. if (this.animations) {
  11917. for (var i = 0; i < this.animations.length; i++) {
  11918. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11919. }
  11920. }
  11921. if (fullDetails) {
  11922. }
  11923. return ret;
  11924. };
  11925. Object.defineProperty(Camera.prototype, "globalPosition", {
  11926. get: function () {
  11927. return this._globalPosition;
  11928. },
  11929. enumerable: true,
  11930. configurable: true
  11931. });
  11932. Camera.prototype.getActiveMeshes = function () {
  11933. return this._activeMeshes;
  11934. };
  11935. Camera.prototype.isActiveMesh = function (mesh) {
  11936. return (this._activeMeshes.indexOf(mesh) !== -1);
  11937. };
  11938. //Cache
  11939. Camera.prototype._initCache = function () {
  11940. _super.prototype._initCache.call(this);
  11941. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11942. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11943. this._cache.mode = undefined;
  11944. this._cache.minZ = undefined;
  11945. this._cache.maxZ = undefined;
  11946. this._cache.fov = undefined;
  11947. this._cache.aspectRatio = undefined;
  11948. this._cache.orthoLeft = undefined;
  11949. this._cache.orthoRight = undefined;
  11950. this._cache.orthoBottom = undefined;
  11951. this._cache.orthoTop = undefined;
  11952. this._cache.renderWidth = undefined;
  11953. this._cache.renderHeight = undefined;
  11954. };
  11955. Camera.prototype._updateCache = function (ignoreParentClass) {
  11956. if (!ignoreParentClass) {
  11957. _super.prototype._updateCache.call(this);
  11958. }
  11959. var engine = this.getEngine();
  11960. this._cache.position.copyFrom(this.position);
  11961. this._cache.upVector.copyFrom(this.upVector);
  11962. this._cache.mode = this.mode;
  11963. this._cache.minZ = this.minZ;
  11964. this._cache.maxZ = this.maxZ;
  11965. this._cache.fov = this.fov;
  11966. this._cache.aspectRatio = engine.getAspectRatio(this);
  11967. this._cache.orthoLeft = this.orthoLeft;
  11968. this._cache.orthoRight = this.orthoRight;
  11969. this._cache.orthoBottom = this.orthoBottom;
  11970. this._cache.orthoTop = this.orthoTop;
  11971. this._cache.renderWidth = engine.getRenderWidth();
  11972. this._cache.renderHeight = engine.getRenderHeight();
  11973. };
  11974. Camera.prototype._updateFromScene = function () {
  11975. this.updateCache();
  11976. this._update();
  11977. };
  11978. // Synchronized
  11979. Camera.prototype._isSynchronized = function () {
  11980. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  11981. };
  11982. Camera.prototype._isSynchronizedViewMatrix = function () {
  11983. if (!_super.prototype._isSynchronized.call(this))
  11984. return false;
  11985. return this._cache.position.equals(this.position)
  11986. && this._cache.upVector.equals(this.upVector)
  11987. && this.isSynchronizedWithParent();
  11988. };
  11989. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  11990. var check = this._cache.mode === this.mode
  11991. && this._cache.minZ === this.minZ
  11992. && this._cache.maxZ === this.maxZ;
  11993. if (!check) {
  11994. return false;
  11995. }
  11996. var engine = this.getEngine();
  11997. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11998. check = this._cache.fov === this.fov
  11999. && this._cache.aspectRatio === engine.getAspectRatio(this);
  12000. }
  12001. else {
  12002. check = this._cache.orthoLeft === this.orthoLeft
  12003. && this._cache.orthoRight === this.orthoRight
  12004. && this._cache.orthoBottom === this.orthoBottom
  12005. && this._cache.orthoTop === this.orthoTop
  12006. && this._cache.renderWidth === engine.getRenderWidth()
  12007. && this._cache.renderHeight === engine.getRenderHeight();
  12008. }
  12009. return check;
  12010. };
  12011. // Controls
  12012. Camera.prototype.attachControl = function (element, noPreventDefault) {
  12013. };
  12014. Camera.prototype.detachControl = function (element) {
  12015. };
  12016. Camera.prototype._update = function () {
  12017. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12018. this._updateRigCameras();
  12019. }
  12020. this._checkInputs();
  12021. };
  12022. Camera.prototype._checkInputs = function () {
  12023. };
  12024. Camera.prototype._cascadePostProcessesToRigCams = function () {
  12025. // invalidate framebuffer
  12026. if (this._postProcesses.length > 0) {
  12027. this._postProcesses[0].markTextureDirty();
  12028. }
  12029. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  12030. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  12031. var cam = this._rigCameras[i];
  12032. var rigPostProcess = cam._rigPostProcess;
  12033. // for VR rig, there does not have to be a post process
  12034. if (rigPostProcess) {
  12035. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  12036. if (isPass) {
  12037. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  12038. cam.isIntermediate = this._postProcesses.length === 0;
  12039. }
  12040. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  12041. rigPostProcess.markTextureDirty();
  12042. }
  12043. else {
  12044. cam._postProcesses = this._postProcesses.slice(0);
  12045. }
  12046. }
  12047. };
  12048. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  12049. if (insertAt === void 0) { insertAt = null; }
  12050. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  12051. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  12052. return 0;
  12053. }
  12054. if (insertAt == null || insertAt < 0) {
  12055. this._postProcesses.push(postProcess);
  12056. }
  12057. else {
  12058. this._postProcesses.splice(insertAt, 0, postProcess);
  12059. }
  12060. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12061. return this._postProcesses.indexOf(postProcess);
  12062. };
  12063. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  12064. if (atIndices === void 0) { atIndices = null; }
  12065. var result = [];
  12066. var i;
  12067. var index;
  12068. if (!atIndices) {
  12069. var idx = this._postProcesses.indexOf(postProcess);
  12070. if (idx !== -1) {
  12071. this._postProcesses.splice(idx, 1);
  12072. }
  12073. }
  12074. else {
  12075. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  12076. // iterate descending, so can just splice as we go
  12077. for (i = atIndices.length - 1; i >= 0; i--) {
  12078. if (this._postProcesses[atIndices[i]] !== postProcess) {
  12079. result.push(i);
  12080. continue;
  12081. }
  12082. this._postProcesses.splice(index, 1);
  12083. }
  12084. }
  12085. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12086. return result;
  12087. };
  12088. Camera.prototype.getWorldMatrix = function () {
  12089. if (!this._worldMatrix) {
  12090. this._worldMatrix = BABYLON.Matrix.Identity();
  12091. }
  12092. var viewMatrix = this.getViewMatrix();
  12093. viewMatrix.invertToRef(this._worldMatrix);
  12094. return this._worldMatrix;
  12095. };
  12096. Camera.prototype._getViewMatrix = function () {
  12097. return BABYLON.Matrix.Identity();
  12098. };
  12099. Camera.prototype.getViewMatrix = function (force) {
  12100. this._computedViewMatrix = this._computeViewMatrix(force);
  12101. if (!force && this._isSynchronizedViewMatrix()) {
  12102. return this._computedViewMatrix;
  12103. }
  12104. this._refreshFrustumPlanes = true;
  12105. if (!this.parent || !this.parent.getWorldMatrix) {
  12106. this._globalPosition.copyFrom(this.position);
  12107. }
  12108. else {
  12109. if (!this._worldMatrix) {
  12110. this._worldMatrix = BABYLON.Matrix.Identity();
  12111. }
  12112. this._computedViewMatrix.invertToRef(this._worldMatrix);
  12113. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  12114. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  12115. this._computedViewMatrix.invert();
  12116. this._markSyncedWithParent();
  12117. }
  12118. this._currentRenderId = this.getScene().getRenderId();
  12119. return this._computedViewMatrix;
  12120. };
  12121. Camera.prototype._computeViewMatrix = function (force) {
  12122. if (!force && this._isSynchronizedViewMatrix()) {
  12123. return this._computedViewMatrix;
  12124. }
  12125. this._computedViewMatrix = this._getViewMatrix();
  12126. this._currentRenderId = this.getScene().getRenderId();
  12127. return this._computedViewMatrix;
  12128. };
  12129. Camera.prototype.getProjectionMatrix = function (force) {
  12130. if (!force && this._isSynchronizedProjectionMatrix()) {
  12131. return this._projectionMatrix;
  12132. }
  12133. this._refreshFrustumPlanes = true;
  12134. var engine = this.getEngine();
  12135. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12136. if (this.minZ <= 0) {
  12137. this.minZ = 0.1;
  12138. }
  12139. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  12140. return this._projectionMatrix;
  12141. }
  12142. var halfWidth = engine.getRenderWidth() / 2.0;
  12143. var halfHeight = engine.getRenderHeight() / 2.0;
  12144. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  12145. return this._projectionMatrix;
  12146. };
  12147. Camera.prototype.getTranformationMatrix = function () {
  12148. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12149. return this._transformMatrix;
  12150. };
  12151. Camera.prototype.updateFrustumPlanes = function () {
  12152. if (!this._refreshFrustumPlanes) {
  12153. return;
  12154. }
  12155. this.getTranformationMatrix();
  12156. if (!this._frustumPlanes) {
  12157. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12158. }
  12159. else {
  12160. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12161. }
  12162. this._refreshFrustumPlanes = false;
  12163. };
  12164. Camera.prototype.isInFrustum = function (target) {
  12165. this.updateFrustumPlanes();
  12166. return target.isInFrustum(this._frustumPlanes);
  12167. };
  12168. Camera.prototype.isCompletelyInFrustum = function (target) {
  12169. this.updateFrustumPlanes();
  12170. return target.isCompletelyInFrustum(this._frustumPlanes);
  12171. };
  12172. Camera.prototype.dispose = function () {
  12173. // Animations
  12174. this.getScene().stopAnimation(this);
  12175. // Remove from scene
  12176. this.getScene().removeCamera(this);
  12177. while (this._rigCameras.length > 0) {
  12178. this._rigCameras.pop().dispose();
  12179. }
  12180. // Postprocesses
  12181. for (var i = 0; i < this._postProcesses.length; ++i) {
  12182. this._postProcesses[i].dispose(this);
  12183. }
  12184. _super.prototype.dispose.call(this);
  12185. };
  12186. // ---- Camera rigs section ----
  12187. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  12188. while (this._rigCameras.length > 0) {
  12189. this._rigCameras.pop().dispose();
  12190. }
  12191. this.cameraRigMode = mode;
  12192. this._cameraRigParams = {};
  12193. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  12194. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  12195. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  12196. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  12197. // create the rig cameras, unless none
  12198. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12199. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  12200. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  12201. }
  12202. switch (this.cameraRigMode) {
  12203. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12204. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12205. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  12206. break;
  12207. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12208. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12209. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12210. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12211. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12212. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  12213. break;
  12214. case Camera.RIG_MODE_VR:
  12215. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  12216. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  12217. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  12218. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12219. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  12220. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  12221. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  12222. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  12223. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  12224. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12225. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  12226. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  12227. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  12228. if (metrics.compensateDistortion) {
  12229. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  12230. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  12231. }
  12232. break;
  12233. }
  12234. this._cascadePostProcessesToRigCams();
  12235. this._update();
  12236. };
  12237. Camera.prototype._getVRProjectionMatrix = function () {
  12238. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  12239. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  12240. return this._projectionMatrix;
  12241. };
  12242. Camera.prototype.setCameraRigParameter = function (name, value) {
  12243. if (!this._cameraRigParams) {
  12244. this._cameraRigParams = {};
  12245. }
  12246. this._cameraRigParams[name] = value;
  12247. //provisionnally:
  12248. if (name === "interaxialDistance") {
  12249. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  12250. }
  12251. };
  12252. /**
  12253. * needs to be overridden by children so sub has required properties to be copied
  12254. */
  12255. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  12256. return null;
  12257. };
  12258. /**
  12259. * May need to be overridden by children
  12260. */
  12261. Camera.prototype._updateRigCameras = function () {
  12262. for (var i = 0; i < this._rigCameras.length; i++) {
  12263. this._rigCameras[i].minZ = this.minZ;
  12264. this._rigCameras[i].maxZ = this.maxZ;
  12265. this._rigCameras[i].fov = this.fov;
  12266. }
  12267. // only update viewport when ANAGLYPH
  12268. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  12269. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  12270. }
  12271. };
  12272. Camera.prototype._setupInputs = function () {
  12273. };
  12274. Camera.prototype.serialize = function () {
  12275. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  12276. // Type
  12277. serializationObject.type = this.getTypeName();
  12278. // Parent
  12279. if (this.parent) {
  12280. serializationObject.parentId = this.parent.id;
  12281. }
  12282. if (this.inputs) {
  12283. this.inputs.serialize(serializationObject);
  12284. }
  12285. // Animations
  12286. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  12287. serializationObject.ranges = this.serializeAnimationRanges();
  12288. return serializationObject;
  12289. };
  12290. Camera.prototype.getTypeName = function () {
  12291. return "Camera";
  12292. };
  12293. Camera.prototype.clone = function (name) {
  12294. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  12295. };
  12296. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  12297. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  12298. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  12299. switch (type) {
  12300. case "ArcRotateCamera":
  12301. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  12302. case "DeviceOrientationCamera":
  12303. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  12304. case "FollowCamera":
  12305. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  12306. case "ArcFollowCamera":
  12307. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  12308. case "GamepadCamera":
  12309. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  12310. case "TouchCamera":
  12311. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  12312. case "VirtualJoysticksCamera":
  12313. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  12314. case "WebVRFreeCamera":
  12315. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  12316. case "VRDeviceOrientationFreeCamera":
  12317. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  12318. case "AnaglyphArcRotateCamera":
  12319. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12320. case "AnaglyphFreeCamera":
  12321. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12322. case "AnaglyphGamepadCamera":
  12323. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12324. case "AnaglyphUniversalCamera":
  12325. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12326. case "StereoscopicArcRotateCamera":
  12327. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12328. case "StereoscopicFreeCamera":
  12329. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12330. case "StereoscopicGamepadCamera":
  12331. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12332. case "StereoscopicUniversalCamera":
  12333. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12334. case "FreeCamera":
  12335. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  12336. default:
  12337. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  12338. }
  12339. };
  12340. Camera.Parse = function (parsedCamera, scene) {
  12341. var type = parsedCamera.type;
  12342. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  12343. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  12344. // Parent
  12345. if (parsedCamera.parentId) {
  12346. camera._waitingParentId = parsedCamera.parentId;
  12347. }
  12348. //If camera has an input manager, let it parse inputs settings
  12349. if (camera.inputs) {
  12350. camera.inputs.parse(parsedCamera);
  12351. camera._setupInputs();
  12352. }
  12353. // Target
  12354. if (parsedCamera.target) {
  12355. if (camera.setTarget) {
  12356. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  12357. }
  12358. }
  12359. // Apply 3d rig, when found
  12360. if (parsedCamera.cameraRigMode) {
  12361. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  12362. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  12363. }
  12364. // Animations
  12365. if (parsedCamera.animations) {
  12366. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  12367. var parsedAnimation = parsedCamera.animations[animationIndex];
  12368. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  12369. }
  12370. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  12371. }
  12372. if (parsedCamera.autoAnimate) {
  12373. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  12374. }
  12375. return camera;
  12376. };
  12377. // Statics
  12378. Camera._PERSPECTIVE_CAMERA = 0;
  12379. Camera._ORTHOGRAPHIC_CAMERA = 1;
  12380. Camera._FOVMODE_VERTICAL_FIXED = 0;
  12381. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  12382. Camera._RIG_MODE_NONE = 0;
  12383. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  12384. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  12385. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  12386. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  12387. Camera._RIG_MODE_VR = 20;
  12388. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  12389. __decorate([
  12390. BABYLON.serializeAsVector3()
  12391. ], Camera.prototype, "position", void 0);
  12392. __decorate([
  12393. BABYLON.serializeAsVector3()
  12394. ], Camera.prototype, "upVector", void 0);
  12395. __decorate([
  12396. BABYLON.serialize()
  12397. ], Camera.prototype, "orthoLeft", void 0);
  12398. __decorate([
  12399. BABYLON.serialize()
  12400. ], Camera.prototype, "orthoRight", void 0);
  12401. __decorate([
  12402. BABYLON.serialize()
  12403. ], Camera.prototype, "orthoBottom", void 0);
  12404. __decorate([
  12405. BABYLON.serialize()
  12406. ], Camera.prototype, "orthoTop", void 0);
  12407. __decorate([
  12408. BABYLON.serialize()
  12409. ], Camera.prototype, "fov", void 0);
  12410. __decorate([
  12411. BABYLON.serialize()
  12412. ], Camera.prototype, "minZ", void 0);
  12413. __decorate([
  12414. BABYLON.serialize()
  12415. ], Camera.prototype, "maxZ", void 0);
  12416. __decorate([
  12417. BABYLON.serialize()
  12418. ], Camera.prototype, "inertia", void 0);
  12419. __decorate([
  12420. BABYLON.serialize()
  12421. ], Camera.prototype, "mode", void 0);
  12422. __decorate([
  12423. BABYLON.serialize()
  12424. ], Camera.prototype, "layerMask", void 0);
  12425. __decorate([
  12426. BABYLON.serialize()
  12427. ], Camera.prototype, "fovMode", void 0);
  12428. __decorate([
  12429. BABYLON.serialize()
  12430. ], Camera.prototype, "cameraRigMode", void 0);
  12431. __decorate([
  12432. BABYLON.serialize()
  12433. ], Camera.prototype, "interaxialDistance", void 0);
  12434. __decorate([
  12435. BABYLON.serialize()
  12436. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  12437. return Camera;
  12438. }(BABYLON.Node));
  12439. BABYLON.Camera = Camera;
  12440. })(BABYLON || (BABYLON = {}));
  12441. var BABYLON;
  12442. (function (BABYLON) {
  12443. BABYLON.CameraInputTypes = {};
  12444. var CameraInputsManager = (function () {
  12445. function CameraInputsManager(camera) {
  12446. this.attached = {};
  12447. this.camera = camera;
  12448. this.checkInputs = function () { };
  12449. }
  12450. CameraInputsManager.prototype.add = function (input) {
  12451. var type = input.getSimpleName();
  12452. if (this.attached[type]) {
  12453. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  12454. return;
  12455. }
  12456. this.attached[type] = input;
  12457. input.camera = this.camera;
  12458. //for checkInputs, we are dynamically creating a function
  12459. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  12460. if (input.checkInputs) {
  12461. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  12462. }
  12463. if (this.attachedElement) {
  12464. input.attachControl(this.attachedElement);
  12465. }
  12466. };
  12467. CameraInputsManager.prototype.remove = function (inputToRemove) {
  12468. for (var cam in this.attached) {
  12469. var input = this.attached[cam];
  12470. if (input === inputToRemove) {
  12471. input.detachControl(this.attachedElement);
  12472. delete this.attached[cam];
  12473. this.rebuildInputCheck();
  12474. }
  12475. }
  12476. };
  12477. CameraInputsManager.prototype.removeByType = function (inputType) {
  12478. for (var cam in this.attached) {
  12479. var input = this.attached[cam];
  12480. if (input.getTypeName() === inputType) {
  12481. input.detachControl(this.attachedElement);
  12482. delete this.attached[cam];
  12483. this.rebuildInputCheck();
  12484. }
  12485. }
  12486. };
  12487. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  12488. var current = this.checkInputs;
  12489. return function () {
  12490. current();
  12491. fn();
  12492. };
  12493. };
  12494. CameraInputsManager.prototype.attachInput = function (input) {
  12495. input.attachControl(this.attachedElement, this.noPreventDefault);
  12496. };
  12497. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  12498. if (this.attachedElement) {
  12499. return;
  12500. }
  12501. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  12502. this.attachedElement = element;
  12503. this.noPreventDefault = noPreventDefault;
  12504. for (var cam in this.attached) {
  12505. var input = this.attached[cam];
  12506. this.attached[cam].attachControl(element, noPreventDefault);
  12507. }
  12508. };
  12509. CameraInputsManager.prototype.detachElement = function (element) {
  12510. if (this.attachedElement !== element) {
  12511. return;
  12512. }
  12513. for (var cam in this.attached) {
  12514. var input = this.attached[cam];
  12515. this.attached[cam].detachControl(element);
  12516. }
  12517. this.attachedElement = null;
  12518. };
  12519. CameraInputsManager.prototype.rebuildInputCheck = function () {
  12520. this.checkInputs = function () { };
  12521. for (var cam in this.attached) {
  12522. var input = this.attached[cam];
  12523. if (input.checkInputs) {
  12524. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  12525. }
  12526. }
  12527. };
  12528. CameraInputsManager.prototype.clear = function () {
  12529. if (this.attachedElement) {
  12530. this.detachElement(this.attachedElement);
  12531. }
  12532. this.attached = {};
  12533. this.attachedElement = null;
  12534. this.checkInputs = function () { };
  12535. };
  12536. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  12537. var inputs = {};
  12538. for (var cam in this.attached) {
  12539. var input = this.attached[cam];
  12540. var res = BABYLON.SerializationHelper.Serialize(input);
  12541. inputs[input.getTypeName()] = res;
  12542. }
  12543. serializedCamera.inputsmgr = inputs;
  12544. };
  12545. CameraInputsManager.prototype.parse = function (parsedCamera) {
  12546. var parsedInputs = parsedCamera.inputsmgr;
  12547. if (parsedInputs) {
  12548. this.clear();
  12549. for (var n in parsedInputs) {
  12550. var construct = BABYLON.CameraInputTypes[n];
  12551. if (construct) {
  12552. var parsedinput = parsedInputs[n];
  12553. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  12554. this.add(input);
  12555. }
  12556. }
  12557. }
  12558. else {
  12559. //2016-03-08 this part is for managing backward compatibility
  12560. for (var n in this.attached) {
  12561. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  12562. if (construct) {
  12563. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  12564. this.remove(this.attached[n]);
  12565. this.add(input);
  12566. }
  12567. }
  12568. }
  12569. };
  12570. return CameraInputsManager;
  12571. }());
  12572. BABYLON.CameraInputsManager = CameraInputsManager;
  12573. })(BABYLON || (BABYLON = {}));
  12574. var BABYLON;
  12575. (function (BABYLON) {
  12576. var FreeCameraMouseInput = (function () {
  12577. function FreeCameraMouseInput(touchEnabled) {
  12578. if (touchEnabled === void 0) { touchEnabled = true; }
  12579. this.touchEnabled = touchEnabled;
  12580. this.angularSensibility = 2000.0;
  12581. }
  12582. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  12583. var _this = this;
  12584. if (!this._pointerInput) {
  12585. var camera = this.camera;
  12586. var engine = this.camera.getEngine();
  12587. this._pointerInput = function (p, s) {
  12588. var evt = p.event;
  12589. if (!_this.touchEnabled && evt.pointerType === "touch") {
  12590. return;
  12591. }
  12592. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12593. try {
  12594. evt.srcElement.setPointerCapture(evt.pointerId);
  12595. }
  12596. catch (e) {
  12597. }
  12598. _this.previousPosition = {
  12599. x: evt.clientX,
  12600. y: evt.clientY
  12601. };
  12602. if (!noPreventDefault) {
  12603. evt.preventDefault();
  12604. element.focus();
  12605. }
  12606. }
  12607. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12608. try {
  12609. evt.srcElement.releasePointerCapture(evt.pointerId);
  12610. }
  12611. catch (e) {
  12612. }
  12613. _this.previousPosition = null;
  12614. if (!noPreventDefault) {
  12615. evt.preventDefault();
  12616. }
  12617. }
  12618. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12619. if (!_this.previousPosition && !engine.isPointerLock) {
  12620. return;
  12621. }
  12622. var offsetX;
  12623. var offsetY;
  12624. if (!engine.isPointerLock) {
  12625. offsetX = evt.clientX - _this.previousPosition.x;
  12626. offsetY = evt.clientY - _this.previousPosition.y;
  12627. }
  12628. else {
  12629. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12630. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12631. }
  12632. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  12633. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  12634. _this.previousPosition = {
  12635. x: evt.clientX,
  12636. y: evt.clientY
  12637. };
  12638. if (!noPreventDefault) {
  12639. evt.preventDefault();
  12640. }
  12641. }
  12642. };
  12643. }
  12644. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12645. };
  12646. FreeCameraMouseInput.prototype.detachControl = function (element) {
  12647. if (this._observer && element) {
  12648. this.camera.getScene().onPointerObservable.remove(this._observer);
  12649. this._observer = null;
  12650. this.previousPosition = null;
  12651. }
  12652. };
  12653. FreeCameraMouseInput.prototype.getTypeName = function () {
  12654. return "FreeCameraMouseInput";
  12655. };
  12656. FreeCameraMouseInput.prototype.getSimpleName = function () {
  12657. return "mouse";
  12658. };
  12659. __decorate([
  12660. BABYLON.serialize()
  12661. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  12662. return FreeCameraMouseInput;
  12663. }());
  12664. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  12665. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  12666. })(BABYLON || (BABYLON = {}));
  12667. var BABYLON;
  12668. (function (BABYLON) {
  12669. var FreeCameraKeyboardMoveInput = (function () {
  12670. function FreeCameraKeyboardMoveInput() {
  12671. this._keys = [];
  12672. this.keysUp = [38];
  12673. this.keysDown = [40];
  12674. this.keysLeft = [37];
  12675. this.keysRight = [39];
  12676. }
  12677. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  12678. var _this = this;
  12679. if (!this._onKeyDown) {
  12680. element.tabIndex = 1;
  12681. this._onKeyDown = function (evt) {
  12682. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12683. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12684. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12685. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12686. var index = _this._keys.indexOf(evt.keyCode);
  12687. if (index === -1) {
  12688. _this._keys.push(evt.keyCode);
  12689. }
  12690. if (!noPreventDefault) {
  12691. evt.preventDefault();
  12692. }
  12693. }
  12694. };
  12695. this._onKeyUp = function (evt) {
  12696. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12697. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12698. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12699. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12700. var index = _this._keys.indexOf(evt.keyCode);
  12701. if (index >= 0) {
  12702. _this._keys.splice(index, 1);
  12703. }
  12704. if (!noPreventDefault) {
  12705. evt.preventDefault();
  12706. }
  12707. }
  12708. };
  12709. element.addEventListener("keydown", this._onKeyDown, false);
  12710. element.addEventListener("keyup", this._onKeyUp, false);
  12711. BABYLON.Tools.RegisterTopRootEvents([
  12712. { name: "blur", handler: this._onLostFocus }
  12713. ]);
  12714. }
  12715. };
  12716. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  12717. if (this._onKeyDown) {
  12718. element.removeEventListener("keydown", this._onKeyDown);
  12719. element.removeEventListener("keyup", this._onKeyUp);
  12720. BABYLON.Tools.UnregisterTopRootEvents([
  12721. { name: "blur", handler: this._onLostFocus }
  12722. ]);
  12723. this._keys = [];
  12724. this._onKeyDown = null;
  12725. this._onKeyUp = null;
  12726. }
  12727. };
  12728. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  12729. if (this._onKeyDown) {
  12730. var camera = this.camera;
  12731. // Keyboard
  12732. for (var index = 0; index < this._keys.length; index++) {
  12733. var keyCode = this._keys[index];
  12734. var speed = camera._computeLocalCameraSpeed();
  12735. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12736. camera._localDirection.copyFromFloats(-speed, 0, 0);
  12737. }
  12738. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12739. camera._localDirection.copyFromFloats(0, 0, speed);
  12740. }
  12741. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12742. camera._localDirection.copyFromFloats(speed, 0, 0);
  12743. }
  12744. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12745. camera._localDirection.copyFromFloats(0, 0, -speed);
  12746. }
  12747. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  12748. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  12749. camera.cameraDirection.addInPlace(camera._transformedDirection);
  12750. }
  12751. }
  12752. };
  12753. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  12754. return "FreeCameraKeyboardMoveInput";
  12755. };
  12756. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  12757. this._keys = [];
  12758. };
  12759. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  12760. return "keyboard";
  12761. };
  12762. __decorate([
  12763. BABYLON.serialize()
  12764. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  12765. __decorate([
  12766. BABYLON.serialize()
  12767. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  12768. __decorate([
  12769. BABYLON.serialize()
  12770. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  12771. __decorate([
  12772. BABYLON.serialize()
  12773. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  12774. return FreeCameraKeyboardMoveInput;
  12775. }());
  12776. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  12777. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  12778. })(BABYLON || (BABYLON = {}));
  12779. var BABYLON;
  12780. (function (BABYLON) {
  12781. var FreeCameraTouchInput = (function () {
  12782. function FreeCameraTouchInput() {
  12783. this._offsetX = null;
  12784. this._offsetY = null;
  12785. this._pointerCount = 0;
  12786. this._pointerPressed = [];
  12787. this.touchAngularSensibility = 200000.0;
  12788. this.touchMoveSensibility = 250.0;
  12789. }
  12790. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  12791. var _this = this;
  12792. var previousPosition;
  12793. if (this._pointerInput === undefined) {
  12794. this._onLostFocus = function (evt) {
  12795. _this._offsetX = null;
  12796. _this._offsetY = null;
  12797. };
  12798. this._pointerInput = function (p, s) {
  12799. var evt = p.event;
  12800. if (evt.pointerType === "mouse") {
  12801. return;
  12802. }
  12803. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12804. if (!noPreventDefault) {
  12805. evt.preventDefault();
  12806. }
  12807. _this._pointerPressed.push(evt.pointerId);
  12808. if (_this._pointerPressed.length !== 1) {
  12809. return;
  12810. }
  12811. previousPosition = {
  12812. x: evt.clientX,
  12813. y: evt.clientY
  12814. };
  12815. }
  12816. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12817. if (!noPreventDefault) {
  12818. evt.preventDefault();
  12819. }
  12820. var index = _this._pointerPressed.indexOf(evt.pointerId);
  12821. if (index === -1) {
  12822. return;
  12823. }
  12824. _this._pointerPressed.splice(index, 1);
  12825. if (index != 0) {
  12826. return;
  12827. }
  12828. previousPosition = null;
  12829. _this._offsetX = null;
  12830. _this._offsetY = null;
  12831. }
  12832. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12833. if (!noPreventDefault) {
  12834. evt.preventDefault();
  12835. }
  12836. if (!previousPosition) {
  12837. return;
  12838. }
  12839. var index = _this._pointerPressed.indexOf(evt.pointerId);
  12840. if (index != 0) {
  12841. return;
  12842. }
  12843. _this._offsetX = evt.clientX - previousPosition.x;
  12844. _this._offsetY = -(evt.clientY - previousPosition.y);
  12845. }
  12846. };
  12847. }
  12848. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12849. element.addEventListener("blur", this._onLostFocus);
  12850. };
  12851. FreeCameraTouchInput.prototype.detachControl = function (element) {
  12852. if (this._pointerInput && element) {
  12853. this.camera.getScene().onPointerObservable.remove(this._observer);
  12854. this._observer = null;
  12855. element.removeEventListener("blur", this._onLostFocus);
  12856. this._onLostFocus = null;
  12857. this._pointerPressed = [];
  12858. this._offsetX = null;
  12859. this._offsetY = null;
  12860. this._pointerCount = 0;
  12861. }
  12862. };
  12863. FreeCameraTouchInput.prototype.checkInputs = function () {
  12864. if (this._offsetX) {
  12865. var camera = this.camera;
  12866. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  12867. if (this._pointerPressed.length > 1) {
  12868. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  12869. }
  12870. else {
  12871. var speed = camera._computeLocalCameraSpeed();
  12872. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  12873. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  12874. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  12875. }
  12876. }
  12877. };
  12878. FreeCameraTouchInput.prototype.getTypeName = function () {
  12879. return "FreeCameraTouchInput";
  12880. };
  12881. FreeCameraTouchInput.prototype.getSimpleName = function () {
  12882. return "touch";
  12883. };
  12884. __decorate([
  12885. BABYLON.serialize()
  12886. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  12887. __decorate([
  12888. BABYLON.serialize()
  12889. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  12890. return FreeCameraTouchInput;
  12891. }());
  12892. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  12893. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  12894. })(BABYLON || (BABYLON = {}));
  12895. var BABYLON;
  12896. (function (BABYLON) {
  12897. var FreeCameraDeviceOrientationInput = (function () {
  12898. function FreeCameraDeviceOrientationInput() {
  12899. var _this = this;
  12900. this._screenOrientationAngle = 0;
  12901. this._screenQuaternion = new BABYLON.Quaternion();
  12902. this._alpha = 0;
  12903. this._beta = 0;
  12904. this._gamma = 0;
  12905. this._orientationChanged = function () {
  12906. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  12907. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  12908. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  12909. };
  12910. this._deviceOrientation = function (evt) {
  12911. _this._alpha = evt.alpha;
  12912. _this._beta = evt.beta;
  12913. _this._gamma = evt.gamma;
  12914. };
  12915. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  12916. this._orientationChanged();
  12917. }
  12918. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  12919. get: function () {
  12920. return this._camera;
  12921. },
  12922. set: function (camera) {
  12923. this._camera = camera;
  12924. if (!this._camera.rotationQuaternion)
  12925. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  12926. },
  12927. enumerable: true,
  12928. configurable: true
  12929. });
  12930. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12931. window.addEventListener("orientationchange", this._orientationChanged);
  12932. window.addEventListener("deviceorientation", this._deviceOrientation);
  12933. };
  12934. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  12935. window.removeEventListener("orientationchange", this._orientationChanged);
  12936. window.removeEventListener("deviceorientation", this._deviceOrientation);
  12937. };
  12938. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  12939. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  12940. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  12941. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  12942. //Mirror on XY Plane
  12943. this._camera.rotationQuaternion.z *= -1;
  12944. this._camera.rotationQuaternion.w *= -1;
  12945. };
  12946. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  12947. return "FreeCameraDeviceOrientationInput";
  12948. };
  12949. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  12950. return "deviceOrientation";
  12951. };
  12952. return FreeCameraDeviceOrientationInput;
  12953. }());
  12954. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  12955. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  12956. })(BABYLON || (BABYLON = {}));
  12957. var BABYLON;
  12958. (function (BABYLON) {
  12959. var FreeCameraVRDeviceOrientationInput = (function () {
  12960. function FreeCameraVRDeviceOrientationInput() {
  12961. this.alphaCorrection = 1;
  12962. this.betaCorrection = 1;
  12963. this.gammaCorrection = 1;
  12964. this._alpha = 0;
  12965. this._beta = 0;
  12966. this._gamma = 0;
  12967. this._dirty = false;
  12968. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  12969. }
  12970. FreeCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12971. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  12972. };
  12973. FreeCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  12974. var camera = this.camera;
  12975. this._alpha = evt.alpha;
  12976. this._beta = evt.beta;
  12977. this._gamma = evt.gamma;
  12978. this._dirty = true;
  12979. };
  12980. FreeCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  12981. if (this._dirty) {
  12982. this._dirty = false;
  12983. var rotationX = this._gamma;
  12984. if (rotationX < 0) {
  12985. rotationX = 90 + rotationX;
  12986. }
  12987. else {
  12988. // Incline it in the correct angle.
  12989. rotationX = 270 - rotationX;
  12990. }
  12991. this.camera.rotation.x = this.gammaCorrection * rotationX / 180.0 * Math.PI;
  12992. this.camera.rotation.y = this.alphaCorrection * -this._alpha / 180.0 * Math.PI;
  12993. this.camera.rotation.z = this.betaCorrection * this._beta / 180.0 * Math.PI;
  12994. }
  12995. };
  12996. FreeCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  12997. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  12998. };
  12999. FreeCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  13000. return "FreeCameraVRDeviceOrientationInput";
  13001. };
  13002. FreeCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  13003. return "VRDeviceOrientation";
  13004. };
  13005. return FreeCameraVRDeviceOrientationInput;
  13006. }());
  13007. BABYLON.FreeCameraVRDeviceOrientationInput = FreeCameraVRDeviceOrientationInput;
  13008. BABYLON.CameraInputTypes["FreeCameraVRDeviceOrientationInput"] = FreeCameraVRDeviceOrientationInput;
  13009. })(BABYLON || (BABYLON = {}));
  13010. var BABYLON;
  13011. (function (BABYLON) {
  13012. var FreeCameraGamepadInput = (function () {
  13013. function FreeCameraGamepadInput() {
  13014. this.gamepadAngularSensibility = 200;
  13015. this.gamepadMoveSensibility = 40;
  13016. }
  13017. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13018. var _this = this;
  13019. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13020. };
  13021. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  13022. if (this._gamepads) {
  13023. this._gamepads.dispose();
  13024. }
  13025. this.gamepad = null;
  13026. };
  13027. FreeCameraGamepadInput.prototype.checkInputs = function () {
  13028. if (this.gamepad) {
  13029. var camera = this.camera;
  13030. var LSValues = this.gamepad.leftStick;
  13031. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  13032. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13033. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  13034. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  13035. var RSValues = this.gamepad.rightStick;
  13036. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  13037. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  13038. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  13039. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  13040. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  13041. var speed = camera._computeLocalCameraSpeed() * 50.0;
  13042. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  13043. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  13044. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  13045. }
  13046. };
  13047. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13048. // Only the first gamepad can control the camera
  13049. if (gamepad.index === 0) {
  13050. this.gamepad = gamepad;
  13051. }
  13052. };
  13053. FreeCameraGamepadInput.prototype.getTypeName = function () {
  13054. return "FreeCameraGamepadInput";
  13055. };
  13056. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  13057. return "gamepad";
  13058. };
  13059. __decorate([
  13060. BABYLON.serialize()
  13061. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  13062. __decorate([
  13063. BABYLON.serialize()
  13064. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13065. return FreeCameraGamepadInput;
  13066. }());
  13067. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  13068. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  13069. })(BABYLON || (BABYLON = {}));
  13070. var BABYLON;
  13071. (function (BABYLON) {
  13072. var ArcRotateCameraKeyboardMoveInput = (function () {
  13073. function ArcRotateCameraKeyboardMoveInput() {
  13074. this._keys = [];
  13075. this.keysUp = [38];
  13076. this.keysDown = [40];
  13077. this.keysLeft = [37];
  13078. this.keysRight = [39];
  13079. }
  13080. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13081. var _this = this;
  13082. element.tabIndex = 1;
  13083. this._onKeyDown = function (evt) {
  13084. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13085. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13086. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13087. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13088. var index = _this._keys.indexOf(evt.keyCode);
  13089. if (index === -1) {
  13090. _this._keys.push(evt.keyCode);
  13091. }
  13092. if (evt.preventDefault) {
  13093. if (!noPreventDefault) {
  13094. evt.preventDefault();
  13095. }
  13096. }
  13097. }
  13098. };
  13099. this._onKeyUp = function (evt) {
  13100. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13101. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13102. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13103. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13104. var index = _this._keys.indexOf(evt.keyCode);
  13105. if (index >= 0) {
  13106. _this._keys.splice(index, 1);
  13107. }
  13108. if (evt.preventDefault) {
  13109. if (!noPreventDefault) {
  13110. evt.preventDefault();
  13111. }
  13112. }
  13113. }
  13114. };
  13115. this._onLostFocus = function () {
  13116. _this._keys = [];
  13117. };
  13118. element.addEventListener("keydown", this._onKeyDown, false);
  13119. element.addEventListener("keyup", this._onKeyUp, false);
  13120. BABYLON.Tools.RegisterTopRootEvents([
  13121. { name: "blur", handler: this._onLostFocus }
  13122. ]);
  13123. };
  13124. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13125. if (element) {
  13126. element.removeEventListener("keydown", this._onKeyDown);
  13127. element.removeEventListener("keyup", this._onKeyUp);
  13128. }
  13129. BABYLON.Tools.UnregisterTopRootEvents([
  13130. { name: "blur", handler: this._onLostFocus }
  13131. ]);
  13132. this._keys = [];
  13133. this._onKeyDown = null;
  13134. this._onKeyUp = null;
  13135. this._onLostFocus = null;
  13136. };
  13137. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13138. if (this._onKeyDown) {
  13139. var camera = this.camera;
  13140. for (var index = 0; index < this._keys.length; index++) {
  13141. var keyCode = this._keys[index];
  13142. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13143. camera.inertialAlphaOffset -= 0.01;
  13144. }
  13145. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13146. camera.inertialBetaOffset -= 0.01;
  13147. }
  13148. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13149. camera.inertialAlphaOffset += 0.01;
  13150. }
  13151. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13152. camera.inertialBetaOffset += 0.01;
  13153. }
  13154. }
  13155. }
  13156. };
  13157. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13158. return "ArcRotateCameraKeyboardMoveInput";
  13159. };
  13160. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13161. return "keyboard";
  13162. };
  13163. __decorate([
  13164. BABYLON.serialize()
  13165. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13166. __decorate([
  13167. BABYLON.serialize()
  13168. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13169. __decorate([
  13170. BABYLON.serialize()
  13171. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13172. __decorate([
  13173. BABYLON.serialize()
  13174. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13175. return ArcRotateCameraKeyboardMoveInput;
  13176. }());
  13177. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  13178. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  13179. })(BABYLON || (BABYLON = {}));
  13180. var BABYLON;
  13181. (function (BABYLON) {
  13182. var ArcRotateCameraMouseWheelInput = (function () {
  13183. function ArcRotateCameraMouseWheelInput() {
  13184. this.wheelPrecision = 3.0;
  13185. }
  13186. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  13187. var _this = this;
  13188. this._wheel = function (p, s) {
  13189. //sanity check - this should be a PointerWheel event.
  13190. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  13191. return;
  13192. var event = p.event;
  13193. var delta = 0;
  13194. if (event.wheelDelta) {
  13195. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  13196. }
  13197. else if (event.detail) {
  13198. delta = -event.detail / _this.wheelPrecision;
  13199. }
  13200. if (delta)
  13201. _this.camera.inertialRadiusOffset += delta;
  13202. if (event.preventDefault) {
  13203. if (!noPreventDefault) {
  13204. event.preventDefault();
  13205. }
  13206. }
  13207. };
  13208. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  13209. };
  13210. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  13211. if (this._observer && element) {
  13212. this.camera.getScene().onPointerObservable.remove(this._observer);
  13213. this._observer = null;
  13214. this._wheel = null;
  13215. }
  13216. };
  13217. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  13218. return "ArcRotateCameraMouseWheelInput";
  13219. };
  13220. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  13221. return "mousewheel";
  13222. };
  13223. __decorate([
  13224. BABYLON.serialize()
  13225. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  13226. return ArcRotateCameraMouseWheelInput;
  13227. }());
  13228. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  13229. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  13230. })(BABYLON || (BABYLON = {}));
  13231. var BABYLON;
  13232. (function (BABYLON) {
  13233. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13234. var ArcRotateCameraPointersInput = (function () {
  13235. function ArcRotateCameraPointersInput() {
  13236. this.angularSensibilityX = 1000.0;
  13237. this.angularSensibilityY = 1000.0;
  13238. this.pinchPrecision = 6.0;
  13239. this.panningSensibility = 50.0;
  13240. this._isPanClick = false;
  13241. this._isCtrlPushed = false;
  13242. this.pinchInwards = true;
  13243. }
  13244. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  13245. var _this = this;
  13246. var engine = this.camera.getEngine();
  13247. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  13248. var pointA, pointB;
  13249. var previousPinchDistance = 0;
  13250. this._pointerInput = function (p, s) {
  13251. var evt = p.event;
  13252. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13253. try {
  13254. evt.srcElement.setPointerCapture(evt.pointerId);
  13255. }
  13256. catch (e) {
  13257. }
  13258. // Manage panning with pan button click
  13259. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  13260. // manage pointers
  13261. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  13262. if (pointA === undefined) {
  13263. pointA = cacheSoloPointer;
  13264. }
  13265. else if (pointB === undefined) {
  13266. pointB = cacheSoloPointer;
  13267. }
  13268. if (!noPreventDefault) {
  13269. evt.preventDefault();
  13270. element.focus();
  13271. }
  13272. }
  13273. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13274. try {
  13275. evt.srcElement.releasePointerCapture(evt.pointerId);
  13276. }
  13277. catch (e) {
  13278. }
  13279. cacheSoloPointer = null;
  13280. previousPinchDistance = 0;
  13281. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  13282. //but emptying completly pointers collection is required to fix a bug on iPhone :
  13283. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  13284. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  13285. pointA = pointB = undefined;
  13286. if (!noPreventDefault) {
  13287. evt.preventDefault();
  13288. }
  13289. }
  13290. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13291. if (!noPreventDefault) {
  13292. evt.preventDefault();
  13293. }
  13294. // One button down
  13295. if (pointA && pointB === undefined) {
  13296. if (_this.panningSensibility !== 0 &&
  13297. ((_this._isCtrlPushed && _this.camera._useCtrlForPanning) ||
  13298. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  13299. _this.camera
  13300. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  13301. _this.camera
  13302. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  13303. }
  13304. else {
  13305. var offsetX = evt.clientX - cacheSoloPointer.x;
  13306. var offsetY = evt.clientY - cacheSoloPointer.y;
  13307. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  13308. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  13309. }
  13310. cacheSoloPointer.x = evt.clientX;
  13311. cacheSoloPointer.y = evt.clientY;
  13312. }
  13313. else if (pointA && pointB) {
  13314. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  13315. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  13316. ed.x = evt.clientX;
  13317. ed.y = evt.clientY;
  13318. var direction = _this.pinchInwards ? 1 : -1;
  13319. var distX = pointA.x - pointB.x;
  13320. var distY = pointA.y - pointB.y;
  13321. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  13322. if (previousPinchDistance === 0) {
  13323. previousPinchDistance = pinchSquaredDistance;
  13324. return;
  13325. }
  13326. if (pinchSquaredDistance !== previousPinchDistance) {
  13327. _this.camera
  13328. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  13329. (_this.pinchPrecision *
  13330. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  13331. direction);
  13332. previousPinchDistance = pinchSquaredDistance;
  13333. }
  13334. }
  13335. }
  13336. };
  13337. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13338. this._onContextMenu = function (evt) {
  13339. evt.preventDefault();
  13340. };
  13341. if (!this.camera._useCtrlForPanning) {
  13342. element.addEventListener("contextmenu", this._onContextMenu, false);
  13343. }
  13344. this._onLostFocus = function () {
  13345. //this._keys = [];
  13346. pointA = pointB = undefined;
  13347. previousPinchDistance = 0;
  13348. cacheSoloPointer = null;
  13349. };
  13350. this._onKeyDown = function (evt) {
  13351. _this._isCtrlPushed = evt.ctrlKey;
  13352. };
  13353. this._onKeyUp = function (evt) {
  13354. _this._isCtrlPushed = evt.ctrlKey;
  13355. };
  13356. this._onMouseMove = function (evt) {
  13357. if (!engine.isPointerLock) {
  13358. return;
  13359. }
  13360. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13361. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13362. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  13363. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  13364. if (!noPreventDefault) {
  13365. evt.preventDefault();
  13366. }
  13367. };
  13368. this._onGestureStart = function (e) {
  13369. if (window.MSGesture === undefined) {
  13370. return;
  13371. }
  13372. if (!_this._MSGestureHandler) {
  13373. _this._MSGestureHandler = new MSGesture();
  13374. _this._MSGestureHandler.target = element;
  13375. }
  13376. _this._MSGestureHandler.addPointer(e.pointerId);
  13377. };
  13378. this._onGesture = function (e) {
  13379. _this.camera.radius *= e.scale;
  13380. if (e.preventDefault) {
  13381. if (!noPreventDefault) {
  13382. e.stopPropagation();
  13383. e.preventDefault();
  13384. }
  13385. }
  13386. };
  13387. element.addEventListener("mousemove", this._onMouseMove, false);
  13388. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  13389. element.addEventListener("MSGestureChange", this._onGesture, false);
  13390. element.addEventListener("keydown", this._onKeyDown, false);
  13391. element.addEventListener("keyup", this._onKeyUp, false);
  13392. BABYLON.Tools.RegisterTopRootEvents([
  13393. { name: "blur", handler: this._onLostFocus }
  13394. ]);
  13395. };
  13396. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  13397. if (element && this._observer) {
  13398. this.camera.getScene().onPointerObservable.remove(this._observer);
  13399. this._observer = null;
  13400. element.removeEventListener("contextmenu", this._onContextMenu);
  13401. element.removeEventListener("mousemove", this._onMouseMove);
  13402. element.removeEventListener("MSPointerDown", this._onGestureStart);
  13403. element.removeEventListener("MSGestureChange", this._onGesture);
  13404. element.removeEventListener("keydown", this._onKeyDown);
  13405. element.removeEventListener("keyup", this._onKeyUp);
  13406. this._isPanClick = false;
  13407. this._isCtrlPushed = false;
  13408. this.pinchInwards = true;
  13409. this._onKeyDown = null;
  13410. this._onKeyUp = null;
  13411. this._onMouseMove = null;
  13412. this._onGestureStart = null;
  13413. this._onGesture = null;
  13414. this._MSGestureHandler = null;
  13415. this._onLostFocus = null;
  13416. this._onContextMenu = null;
  13417. }
  13418. BABYLON.Tools.UnregisterTopRootEvents([
  13419. { name: "blur", handler: this._onLostFocus }
  13420. ]);
  13421. };
  13422. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  13423. return "ArcRotateCameraPointersInput";
  13424. };
  13425. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  13426. return "pointers";
  13427. };
  13428. __decorate([
  13429. BABYLON.serialize()
  13430. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  13431. __decorate([
  13432. BABYLON.serialize()
  13433. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  13434. __decorate([
  13435. BABYLON.serialize()
  13436. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  13437. __decorate([
  13438. BABYLON.serialize()
  13439. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  13440. return ArcRotateCameraPointersInput;
  13441. }());
  13442. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  13443. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  13444. })(BABYLON || (BABYLON = {}));
  13445. var BABYLON;
  13446. (function (BABYLON) {
  13447. var ArcRotateCameraGamepadInput = (function () {
  13448. function ArcRotateCameraGamepadInput() {
  13449. this.gamepadRotationSensibility = 80;
  13450. this.gamepadMoveSensibility = 40;
  13451. }
  13452. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13453. var _this = this;
  13454. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13455. };
  13456. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  13457. if (this._gamepads) {
  13458. this._gamepads.dispose();
  13459. }
  13460. this.gamepad = null;
  13461. };
  13462. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  13463. if (this.gamepad) {
  13464. var camera = this.camera;
  13465. var RSValues = this.gamepad.rightStick;
  13466. if (RSValues.x != 0) {
  13467. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  13468. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  13469. camera.inertialAlphaOffset += normalizedRX;
  13470. }
  13471. }
  13472. if (RSValues.y != 0) {
  13473. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  13474. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  13475. camera.inertialBetaOffset += normalizedRY;
  13476. }
  13477. }
  13478. var LSValues = this.gamepad.leftStick;
  13479. if (LSValues.y != 0) {
  13480. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13481. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  13482. this.camera.inertialRadiusOffset -= normalizedLY;
  13483. }
  13484. }
  13485. }
  13486. };
  13487. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13488. // Only the first gamepad can control the camera
  13489. if (gamepad.index === 0) {
  13490. this.gamepad = gamepad;
  13491. }
  13492. };
  13493. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  13494. return "ArcRotateCameraGamepadInput";
  13495. };
  13496. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  13497. return "gamepad";
  13498. };
  13499. __decorate([
  13500. BABYLON.serialize()
  13501. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  13502. __decorate([
  13503. BABYLON.serialize()
  13504. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13505. return ArcRotateCameraGamepadInput;
  13506. }());
  13507. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  13508. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  13509. })(BABYLON || (BABYLON = {}));
  13510. var BABYLON;
  13511. (function (BABYLON) {
  13512. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  13513. function ArcRotateCameraVRDeviceOrientationInput() {
  13514. this.alphaCorrection = 1;
  13515. this.betaCorrection = 1;
  13516. this.gammaCorrection = 1;
  13517. this._alpha = 0;
  13518. this._beta = 0;
  13519. this._gamma = 0;
  13520. this._dirty = false;
  13521. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  13522. }
  13523. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13524. this.camera.attachControl(element, noPreventDefault);
  13525. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  13526. };
  13527. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  13528. var camera = this.camera;
  13529. this._alpha = +evt.alpha | 0;
  13530. this._beta = +evt.beta | 0;
  13531. this._gamma = +evt.gamma | 0;
  13532. this._dirty = true;
  13533. };
  13534. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  13535. if (this._dirty) {
  13536. this._dirty = false;
  13537. if (this._gamma < 0) {
  13538. this._gamma = 180 + this._gamma;
  13539. }
  13540. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  13541. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  13542. }
  13543. };
  13544. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  13545. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  13546. };
  13547. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  13548. return "ArcRotateCameraVRDeviceOrientationInput";
  13549. };
  13550. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  13551. return "VRDeviceOrientation";
  13552. };
  13553. return ArcRotateCameraVRDeviceOrientationInput;
  13554. }());
  13555. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  13556. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  13557. })(BABYLON || (BABYLON = {}));
  13558. var BABYLON;
  13559. (function (BABYLON) {
  13560. var TargetCamera = (function (_super) {
  13561. __extends(TargetCamera, _super);
  13562. function TargetCamera(name, position, scene) {
  13563. _super.call(this, name, position, scene);
  13564. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13565. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13566. this.rotation = new BABYLON.Vector3(0, 0, 0);
  13567. this.speed = 2.0;
  13568. this.noRotationConstraint = false;
  13569. this.lockedTarget = null;
  13570. this._currentTarget = BABYLON.Vector3.Zero();
  13571. this._viewMatrix = BABYLON.Matrix.Zero();
  13572. this._camMatrix = BABYLON.Matrix.Zero();
  13573. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  13574. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  13575. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  13576. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  13577. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  13578. this._lookAtTemp = BABYLON.Matrix.Zero();
  13579. this._tempMatrix = BABYLON.Matrix.Zero();
  13580. }
  13581. TargetCamera.prototype.getFrontPosition = function (distance) {
  13582. var direction = this.getTarget().subtract(this.position);
  13583. direction.normalize();
  13584. direction.scaleInPlace(distance);
  13585. return this.globalPosition.add(direction);
  13586. };
  13587. TargetCamera.prototype._getLockedTargetPosition = function () {
  13588. if (!this.lockedTarget) {
  13589. return null;
  13590. }
  13591. return this.lockedTarget.position || this.lockedTarget;
  13592. };
  13593. // Cache
  13594. TargetCamera.prototype._initCache = function () {
  13595. _super.prototype._initCache.call(this);
  13596. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13597. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13598. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13599. };
  13600. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  13601. if (!ignoreParentClass) {
  13602. _super.prototype._updateCache.call(this);
  13603. }
  13604. var lockedTargetPosition = this._getLockedTargetPosition();
  13605. if (!lockedTargetPosition) {
  13606. this._cache.lockedTarget = null;
  13607. }
  13608. else {
  13609. if (!this._cache.lockedTarget) {
  13610. this._cache.lockedTarget = lockedTargetPosition.clone();
  13611. }
  13612. else {
  13613. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  13614. }
  13615. }
  13616. this._cache.rotation.copyFrom(this.rotation);
  13617. if (this.rotationQuaternion)
  13618. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13619. };
  13620. // Synchronized
  13621. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  13622. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  13623. return false;
  13624. }
  13625. var lockedTargetPosition = this._getLockedTargetPosition();
  13626. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  13627. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  13628. };
  13629. // Methods
  13630. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  13631. var engine = this.getEngine();
  13632. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  13633. };
  13634. // Target
  13635. TargetCamera.prototype.setTarget = function (target) {
  13636. this.upVector.normalize();
  13637. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  13638. this._camMatrix.invert();
  13639. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  13640. var vDir = target.subtract(this.position);
  13641. if (vDir.x >= 0.0) {
  13642. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  13643. }
  13644. else {
  13645. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  13646. }
  13647. this.rotation.z = 0;
  13648. if (isNaN(this.rotation.x)) {
  13649. this.rotation.x = 0;
  13650. }
  13651. if (isNaN(this.rotation.y)) {
  13652. this.rotation.y = 0;
  13653. }
  13654. if (isNaN(this.rotation.z)) {
  13655. this.rotation.z = 0;
  13656. }
  13657. if (this.rotationQuaternion) {
  13658. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  13659. }
  13660. };
  13661. TargetCamera.prototype.getTarget = function () {
  13662. return this._currentTarget;
  13663. };
  13664. TargetCamera.prototype._decideIfNeedsToMove = function () {
  13665. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  13666. };
  13667. TargetCamera.prototype._updatePosition = function () {
  13668. this.position.addInPlace(this.cameraDirection);
  13669. };
  13670. TargetCamera.prototype._checkInputs = function () {
  13671. var needToMove = this._decideIfNeedsToMove();
  13672. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  13673. // Move
  13674. if (needToMove) {
  13675. this._updatePosition();
  13676. }
  13677. // Rotate
  13678. if (needToRotate) {
  13679. this.rotation.x += this.cameraRotation.x;
  13680. this.rotation.y += this.cameraRotation.y;
  13681. if (!this.noRotationConstraint) {
  13682. var limit = (Math.PI / 2) * 0.95;
  13683. if (this.rotation.x > limit)
  13684. this.rotation.x = limit;
  13685. if (this.rotation.x < -limit)
  13686. this.rotation.x = -limit;
  13687. }
  13688. }
  13689. // Inertia
  13690. if (needToMove) {
  13691. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  13692. this.cameraDirection.x = 0;
  13693. }
  13694. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  13695. this.cameraDirection.y = 0;
  13696. }
  13697. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  13698. this.cameraDirection.z = 0;
  13699. }
  13700. this.cameraDirection.scaleInPlace(this.inertia);
  13701. }
  13702. if (needToRotate) {
  13703. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  13704. this.cameraRotation.x = 0;
  13705. }
  13706. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  13707. this.cameraRotation.y = 0;
  13708. }
  13709. this.cameraRotation.scaleInPlace(this.inertia);
  13710. }
  13711. _super.prototype._checkInputs.call(this);
  13712. };
  13713. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  13714. if (this.rotationQuaternion) {
  13715. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  13716. //update the up vector!
  13717. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  13718. }
  13719. else {
  13720. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  13721. }
  13722. };
  13723. TargetCamera.prototype._getViewMatrix = function () {
  13724. if (!this.lockedTarget) {
  13725. // Compute
  13726. this._updateCameraRotationMatrix();
  13727. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  13728. // Computing target and final matrix
  13729. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  13730. }
  13731. else {
  13732. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  13733. }
  13734. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  13735. return this._viewMatrix;
  13736. };
  13737. /**
  13738. * @override
  13739. * Override Camera.createRigCamera
  13740. */
  13741. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  13742. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  13743. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  13744. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  13745. if (!this.rotationQuaternion) {
  13746. this.rotationQuaternion = new BABYLON.Quaternion();
  13747. }
  13748. rigCamera._cameraRigParams = {};
  13749. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  13750. }
  13751. return rigCamera;
  13752. }
  13753. return null;
  13754. };
  13755. /**
  13756. * @override
  13757. * Override Camera._updateRigCameras
  13758. */
  13759. TargetCamera.prototype._updateRigCameras = function () {
  13760. var camLeft = this._rigCameras[0];
  13761. var camRight = this._rigCameras[1];
  13762. switch (this.cameraRigMode) {
  13763. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13764. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13765. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13766. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13767. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  13768. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  13769. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  13770. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  13771. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  13772. camLeft.setTarget(this.getTarget());
  13773. camRight.setTarget(this.getTarget());
  13774. break;
  13775. case BABYLON.Camera.RIG_MODE_VR:
  13776. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13777. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13778. camLeft.position.copyFrom(this.position);
  13779. camRight.position.copyFrom(this.position);
  13780. break;
  13781. }
  13782. _super.prototype._updateRigCameras.call(this);
  13783. };
  13784. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  13785. if (!this._rigCamTransformMatrix) {
  13786. this._rigCamTransformMatrix = new BABYLON.Matrix();
  13787. }
  13788. var target = this.getTarget();
  13789. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  13790. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  13791. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  13792. };
  13793. TargetCamera.prototype.getTypeName = function () {
  13794. return "TargetCamera";
  13795. };
  13796. __decorate([
  13797. BABYLON.serializeAsVector3()
  13798. ], TargetCamera.prototype, "rotation", void 0);
  13799. __decorate([
  13800. BABYLON.serialize()
  13801. ], TargetCamera.prototype, "speed", void 0);
  13802. __decorate([
  13803. BABYLON.serializeAsMeshReference("lockedTargetId")
  13804. ], TargetCamera.prototype, "lockedTarget", void 0);
  13805. return TargetCamera;
  13806. }(BABYLON.Camera));
  13807. BABYLON.TargetCamera = TargetCamera;
  13808. })(BABYLON || (BABYLON = {}));
  13809. var BABYLON;
  13810. (function (BABYLON) {
  13811. var FreeCamera = (function (_super) {
  13812. __extends(FreeCamera, _super);
  13813. function FreeCamera(name, position, scene) {
  13814. var _this = this;
  13815. _super.call(this, name, position, scene);
  13816. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  13817. this.checkCollisions = false;
  13818. this.applyGravity = false;
  13819. this._collider = new BABYLON.Collider();
  13820. this._needMoveForGravity = false;
  13821. this._oldPosition = BABYLON.Vector3.Zero();
  13822. this._diffPosition = BABYLON.Vector3.Zero();
  13823. this._newPosition = BABYLON.Vector3.Zero();
  13824. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13825. if (collidedMesh === void 0) { collidedMesh = null; }
  13826. //TODO move this to the collision coordinator!
  13827. if (_this.getScene().workerCollisions)
  13828. newPosition.multiplyInPlace(_this._collider.radius);
  13829. var updatePosition = function (newPos) {
  13830. _this._newPosition.copyFrom(newPos);
  13831. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  13832. var oldPosition = _this.position.clone();
  13833. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  13834. _this.position.addInPlace(_this._diffPosition);
  13835. if (_this.onCollide && collidedMesh) {
  13836. _this.onCollide(collidedMesh);
  13837. }
  13838. }
  13839. };
  13840. updatePosition(newPosition);
  13841. };
  13842. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  13843. this.inputs.addKeyboard().addMouse();
  13844. }
  13845. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  13846. //-- begin properties for backward compatibility for inputs
  13847. get: function () {
  13848. var mouse = this.inputs.attached["mouse"];
  13849. if (mouse)
  13850. return mouse.angularSensibility;
  13851. },
  13852. set: function (value) {
  13853. var mouse = this.inputs.attached["mouse"];
  13854. if (mouse)
  13855. mouse.angularSensibility = value;
  13856. },
  13857. enumerable: true,
  13858. configurable: true
  13859. });
  13860. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  13861. get: function () {
  13862. var keyboard = this.inputs.attached["keyboard"];
  13863. if (keyboard)
  13864. return keyboard.keysUp;
  13865. },
  13866. set: function (value) {
  13867. var keyboard = this.inputs.attached["keyboard"];
  13868. if (keyboard)
  13869. keyboard.keysUp = value;
  13870. },
  13871. enumerable: true,
  13872. configurable: true
  13873. });
  13874. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  13875. get: function () {
  13876. var keyboard = this.inputs.attached["keyboard"];
  13877. if (keyboard)
  13878. return keyboard.keysDown;
  13879. },
  13880. set: function (value) {
  13881. var keyboard = this.inputs.attached["keyboard"];
  13882. if (keyboard)
  13883. keyboard.keysDown = value;
  13884. },
  13885. enumerable: true,
  13886. configurable: true
  13887. });
  13888. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  13889. get: function () {
  13890. var keyboard = this.inputs.attached["keyboard"];
  13891. if (keyboard)
  13892. return keyboard.keysLeft;
  13893. },
  13894. set: function (value) {
  13895. var keyboard = this.inputs.attached["keyboard"];
  13896. if (keyboard)
  13897. keyboard.keysLeft = value;
  13898. },
  13899. enumerable: true,
  13900. configurable: true
  13901. });
  13902. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  13903. get: function () {
  13904. var keyboard = this.inputs.attached["keyboard"];
  13905. if (keyboard)
  13906. return keyboard.keysRight;
  13907. },
  13908. set: function (value) {
  13909. var keyboard = this.inputs.attached["keyboard"];
  13910. if (keyboard)
  13911. keyboard.keysRight = value;
  13912. },
  13913. enumerable: true,
  13914. configurable: true
  13915. });
  13916. // Controls
  13917. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  13918. this.inputs.attachElement(element, noPreventDefault);
  13919. };
  13920. FreeCamera.prototype.detachControl = function (element) {
  13921. this.inputs.detachElement(element);
  13922. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13923. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13924. };
  13925. FreeCamera.prototype._collideWithWorld = function (velocity) {
  13926. var globalPosition;
  13927. if (this.parent) {
  13928. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  13929. }
  13930. else {
  13931. globalPosition = this.position;
  13932. }
  13933. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  13934. this._collider.radius = this.ellipsoid;
  13935. //no need for clone, as long as gravity is not on.
  13936. var actualVelocity = velocity;
  13937. //add gravity to the velocity to prevent the dual-collision checking
  13938. if (this.applyGravity) {
  13939. //this prevents mending with cameraDirection, a global variable of the free camera class.
  13940. actualVelocity = velocity.add(this.getScene().gravity);
  13941. }
  13942. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13943. };
  13944. FreeCamera.prototype._checkInputs = function () {
  13945. if (!this._localDirection) {
  13946. this._localDirection = BABYLON.Vector3.Zero();
  13947. this._transformedDirection = BABYLON.Vector3.Zero();
  13948. }
  13949. this.inputs.checkInputs();
  13950. _super.prototype._checkInputs.call(this);
  13951. };
  13952. FreeCamera.prototype._decideIfNeedsToMove = function () {
  13953. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  13954. };
  13955. FreeCamera.prototype._updatePosition = function () {
  13956. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  13957. this._collideWithWorld(this.cameraDirection);
  13958. }
  13959. else {
  13960. this.position.addInPlace(this.cameraDirection);
  13961. }
  13962. };
  13963. FreeCamera.prototype.dispose = function () {
  13964. this.inputs.clear();
  13965. _super.prototype.dispose.call(this);
  13966. };
  13967. FreeCamera.prototype.getTypeName = function () {
  13968. return "FreeCamera";
  13969. };
  13970. __decorate([
  13971. BABYLON.serializeAsVector3()
  13972. ], FreeCamera.prototype, "ellipsoid", void 0);
  13973. __decorate([
  13974. BABYLON.serialize()
  13975. ], FreeCamera.prototype, "checkCollisions", void 0);
  13976. __decorate([
  13977. BABYLON.serialize()
  13978. ], FreeCamera.prototype, "applyGravity", void 0);
  13979. return FreeCamera;
  13980. }(BABYLON.TargetCamera));
  13981. BABYLON.FreeCamera = FreeCamera;
  13982. })(BABYLON || (BABYLON = {}));
  13983. var BABYLON;
  13984. (function (BABYLON) {
  13985. var FreeCameraInputsManager = (function (_super) {
  13986. __extends(FreeCameraInputsManager, _super);
  13987. function FreeCameraInputsManager(camera) {
  13988. _super.call(this, camera);
  13989. }
  13990. FreeCameraInputsManager.prototype.addKeyboard = function () {
  13991. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  13992. return this;
  13993. };
  13994. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  13995. if (touchEnabled === void 0) { touchEnabled = true; }
  13996. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  13997. return this;
  13998. };
  13999. FreeCameraInputsManager.prototype.addGamepad = function () {
  14000. this.add(new BABYLON.FreeCameraGamepadInput());
  14001. return this;
  14002. };
  14003. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  14004. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  14005. return this;
  14006. };
  14007. FreeCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  14008. this.add(new BABYLON.FreeCameraVRDeviceOrientationInput());
  14009. return this;
  14010. };
  14011. FreeCameraInputsManager.prototype.addTouch = function () {
  14012. this.add(new BABYLON.FreeCameraTouchInput());
  14013. return this;
  14014. };
  14015. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  14016. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  14017. return this;
  14018. };
  14019. return FreeCameraInputsManager;
  14020. }(BABYLON.CameraInputsManager));
  14021. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  14022. })(BABYLON || (BABYLON = {}));
  14023. var BABYLON;
  14024. (function (BABYLON) {
  14025. var FollowCamera = (function (_super) {
  14026. __extends(FollowCamera, _super);
  14027. function FollowCamera(name, position, scene, target) {
  14028. _super.call(this, name, position, scene);
  14029. this.radius = 12;
  14030. this.rotationOffset = 0;
  14031. this.heightOffset = 4;
  14032. this.cameraAcceleration = 0.05;
  14033. this.maxCameraSpeed = 20;
  14034. this.target = target;
  14035. }
  14036. FollowCamera.prototype.getRadians = function (degrees) {
  14037. return degrees * Math.PI / 180;
  14038. };
  14039. FollowCamera.prototype.follow = function (cameraTarget) {
  14040. if (!cameraTarget)
  14041. return;
  14042. var yRotation;
  14043. if (cameraTarget.rotationQuaternion) {
  14044. var rotMatrix = new BABYLON.Matrix();
  14045. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  14046. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  14047. }
  14048. else {
  14049. yRotation = cameraTarget.rotation.y;
  14050. }
  14051. var radians = this.getRadians(this.rotationOffset) + yRotation;
  14052. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  14053. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  14054. var dx = targetX - this.position.x;
  14055. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  14056. var dz = (targetZ) - this.position.z;
  14057. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  14058. var vy = dy * this.cameraAcceleration;
  14059. var vz = dz * this.cameraAcceleration * 2;
  14060. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  14061. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14062. }
  14063. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  14064. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14065. }
  14066. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  14067. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14068. }
  14069. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  14070. this.setTarget(cameraTarget.position);
  14071. };
  14072. FollowCamera.prototype._checkInputs = function () {
  14073. _super.prototype._checkInputs.call(this);
  14074. this.follow(this.target);
  14075. };
  14076. FollowCamera.prototype.getTypeName = function () {
  14077. return "FollowCamera";
  14078. };
  14079. __decorate([
  14080. BABYLON.serialize()
  14081. ], FollowCamera.prototype, "radius", void 0);
  14082. __decorate([
  14083. BABYLON.serialize()
  14084. ], FollowCamera.prototype, "rotationOffset", void 0);
  14085. __decorate([
  14086. BABYLON.serialize()
  14087. ], FollowCamera.prototype, "heightOffset", void 0);
  14088. __decorate([
  14089. BABYLON.serialize()
  14090. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  14091. __decorate([
  14092. BABYLON.serialize()
  14093. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  14094. __decorate([
  14095. BABYLON.serializeAsMeshReference("lockedTargetId")
  14096. ], FollowCamera.prototype, "target", void 0);
  14097. return FollowCamera;
  14098. }(BABYLON.TargetCamera));
  14099. BABYLON.FollowCamera = FollowCamera;
  14100. var ArcFollowCamera = (function (_super) {
  14101. __extends(ArcFollowCamera, _super);
  14102. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  14103. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14104. this.alpha = alpha;
  14105. this.beta = beta;
  14106. this.radius = radius;
  14107. this.target = target;
  14108. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  14109. this.follow();
  14110. }
  14111. ArcFollowCamera.prototype.follow = function () {
  14112. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  14113. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  14114. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  14115. this.position = this.target.position.add(this._cartesianCoordinates);
  14116. this.setTarget(this.target.position);
  14117. };
  14118. ArcFollowCamera.prototype._checkInputs = function () {
  14119. _super.prototype._checkInputs.call(this);
  14120. this.follow();
  14121. };
  14122. ArcFollowCamera.prototype.getTypeName = function () {
  14123. return "ArcFollowCamera";
  14124. };
  14125. return ArcFollowCamera;
  14126. }(BABYLON.TargetCamera));
  14127. BABYLON.ArcFollowCamera = ArcFollowCamera;
  14128. })(BABYLON || (BABYLON = {}));
  14129. var BABYLON;
  14130. (function (BABYLON) {
  14131. // We're mainly based on the logic defined into the FreeCamera code
  14132. var TouchCamera = (function (_super) {
  14133. __extends(TouchCamera, _super);
  14134. //-- end properties for backward compatibility for inputs
  14135. function TouchCamera(name, position, scene) {
  14136. _super.call(this, name, position, scene);
  14137. this.inputs.addTouch();
  14138. this._setupInputs();
  14139. }
  14140. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  14141. //-- Begin properties for backward compatibility for inputs
  14142. get: function () {
  14143. var touch = this.inputs.attached["touch"];
  14144. if (touch)
  14145. return touch.touchAngularSensibility;
  14146. },
  14147. set: function (value) {
  14148. var touch = this.inputs.attached["touch"];
  14149. if (touch)
  14150. touch.touchAngularSensibility = value;
  14151. },
  14152. enumerable: true,
  14153. configurable: true
  14154. });
  14155. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  14156. get: function () {
  14157. var touch = this.inputs.attached["touch"];
  14158. if (touch)
  14159. return touch.touchMoveSensibility;
  14160. },
  14161. set: function (value) {
  14162. var touch = this.inputs.attached["touch"];
  14163. if (touch)
  14164. touch.touchMoveSensibility = value;
  14165. },
  14166. enumerable: true,
  14167. configurable: true
  14168. });
  14169. TouchCamera.prototype.getTypeName = function () {
  14170. return "TouchCamera";
  14171. };
  14172. TouchCamera.prototype._setupInputs = function () {
  14173. var mouse = this.inputs.attached["mouse"];
  14174. if (mouse) {
  14175. mouse.touchEnabled = false;
  14176. }
  14177. };
  14178. return TouchCamera;
  14179. }(BABYLON.FreeCamera));
  14180. BABYLON.TouchCamera = TouchCamera;
  14181. })(BABYLON || (BABYLON = {}));
  14182. var BABYLON;
  14183. (function (BABYLON) {
  14184. var ArcRotateCamera = (function (_super) {
  14185. __extends(ArcRotateCamera, _super);
  14186. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  14187. var _this = this;
  14188. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14189. this.inertialAlphaOffset = 0;
  14190. this.inertialBetaOffset = 0;
  14191. this.inertialRadiusOffset = 0;
  14192. this.lowerAlphaLimit = null;
  14193. this.upperAlphaLimit = null;
  14194. this.lowerBetaLimit = 0.01;
  14195. this.upperBetaLimit = Math.PI;
  14196. this.lowerRadiusLimit = null;
  14197. this.upperRadiusLimit = null;
  14198. this.inertialPanningX = 0;
  14199. this.inertialPanningY = 0;
  14200. //-- end properties for backward compatibility for inputs
  14201. this.zoomOnFactor = 1;
  14202. this.targetScreenOffset = BABYLON.Vector2.Zero();
  14203. this.allowUpsideDown = true;
  14204. this._viewMatrix = new BABYLON.Matrix();
  14205. // Panning
  14206. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  14207. this.checkCollisions = false;
  14208. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14209. this._collider = new BABYLON.Collider();
  14210. this._previousPosition = BABYLON.Vector3.Zero();
  14211. this._collisionVelocity = BABYLON.Vector3.Zero();
  14212. this._newPosition = BABYLON.Vector3.Zero();
  14213. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14214. if (collidedMesh === void 0) { collidedMesh = null; }
  14215. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  14216. newPosition.multiplyInPlace(_this._collider.radius);
  14217. }
  14218. if (!collidedMesh) {
  14219. _this._previousPosition.copyFrom(_this.position);
  14220. }
  14221. else {
  14222. _this.setPosition(newPosition);
  14223. if (_this.onCollide) {
  14224. _this.onCollide(collidedMesh);
  14225. }
  14226. }
  14227. // Recompute because of constraints
  14228. var cosa = Math.cos(_this.alpha);
  14229. var sina = Math.sin(_this.alpha);
  14230. var cosb = Math.cos(_this.beta);
  14231. var sinb = Math.sin(_this.beta);
  14232. if (sinb === 0) {
  14233. sinb = 0.0001;
  14234. }
  14235. var target = _this._getTargetPosition();
  14236. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  14237. _this.position.copyFrom(_this._newPosition);
  14238. var up = _this.upVector;
  14239. if (_this.allowUpsideDown && _this.beta < 0) {
  14240. up = up.clone();
  14241. up = up.negate();
  14242. }
  14243. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  14244. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  14245. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  14246. _this._collisionTriggered = false;
  14247. };
  14248. if (!target) {
  14249. this.target = BABYLON.Vector3.Zero();
  14250. }
  14251. else {
  14252. this.target = target;
  14253. }
  14254. this.alpha = alpha;
  14255. this.beta = beta;
  14256. this.radius = radius;
  14257. this.getViewMatrix();
  14258. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  14259. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  14260. }
  14261. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  14262. //-- begin properties for backward compatibility for inputs
  14263. get: function () {
  14264. var pointers = this.inputs.attached["pointers"];
  14265. if (pointers)
  14266. return pointers.angularSensibilityX;
  14267. },
  14268. set: function (value) {
  14269. var pointers = this.inputs.attached["pointers"];
  14270. if (pointers) {
  14271. pointers.angularSensibilityX = value;
  14272. }
  14273. },
  14274. enumerable: true,
  14275. configurable: true
  14276. });
  14277. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  14278. get: function () {
  14279. var pointers = this.inputs.attached["pointers"];
  14280. if (pointers)
  14281. return pointers.angularSensibilityY;
  14282. },
  14283. set: function (value) {
  14284. var pointers = this.inputs.attached["pointers"];
  14285. if (pointers) {
  14286. pointers.angularSensibilityY = value;
  14287. }
  14288. },
  14289. enumerable: true,
  14290. configurable: true
  14291. });
  14292. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  14293. get: function () {
  14294. var pointers = this.inputs.attached["pointers"];
  14295. if (pointers)
  14296. return pointers.pinchPrecision;
  14297. },
  14298. set: function (value) {
  14299. var pointers = this.inputs.attached["pointers"];
  14300. if (pointers) {
  14301. pointers.pinchPrecision = value;
  14302. }
  14303. },
  14304. enumerable: true,
  14305. configurable: true
  14306. });
  14307. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  14308. get: function () {
  14309. var pointers = this.inputs.attached["pointers"];
  14310. if (pointers)
  14311. return pointers.panningSensibility;
  14312. },
  14313. set: function (value) {
  14314. var pointers = this.inputs.attached["pointers"];
  14315. if (pointers) {
  14316. pointers.panningSensibility = value;
  14317. }
  14318. },
  14319. enumerable: true,
  14320. configurable: true
  14321. });
  14322. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  14323. get: function () {
  14324. var keyboard = this.inputs.attached["keyboard"];
  14325. if (keyboard)
  14326. return keyboard.keysUp;
  14327. },
  14328. set: function (value) {
  14329. var keyboard = this.inputs.attached["keyboard"];
  14330. if (keyboard)
  14331. keyboard.keysUp = value;
  14332. },
  14333. enumerable: true,
  14334. configurable: true
  14335. });
  14336. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  14337. get: function () {
  14338. var keyboard = this.inputs.attached["keyboard"];
  14339. if (keyboard)
  14340. return keyboard.keysDown;
  14341. },
  14342. set: function (value) {
  14343. var keyboard = this.inputs.attached["keyboard"];
  14344. if (keyboard)
  14345. keyboard.keysDown = value;
  14346. },
  14347. enumerable: true,
  14348. configurable: true
  14349. });
  14350. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  14351. get: function () {
  14352. var keyboard = this.inputs.attached["keyboard"];
  14353. if (keyboard)
  14354. return keyboard.keysLeft;
  14355. },
  14356. set: function (value) {
  14357. var keyboard = this.inputs.attached["keyboard"];
  14358. if (keyboard)
  14359. keyboard.keysLeft = value;
  14360. },
  14361. enumerable: true,
  14362. configurable: true
  14363. });
  14364. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  14365. get: function () {
  14366. var keyboard = this.inputs.attached["keyboard"];
  14367. if (keyboard)
  14368. return keyboard.keysRight;
  14369. },
  14370. set: function (value) {
  14371. var keyboard = this.inputs.attached["keyboard"];
  14372. if (keyboard)
  14373. keyboard.keysRight = value;
  14374. },
  14375. enumerable: true,
  14376. configurable: true
  14377. });
  14378. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  14379. get: function () {
  14380. var mousewheel = this.inputs.attached["mousewheel"];
  14381. if (mousewheel)
  14382. return mousewheel.wheelPrecision;
  14383. },
  14384. set: function (value) {
  14385. var mousewheel = this.inputs.attached["mousewheel"];
  14386. if (mousewheel)
  14387. mousewheel.wheelPrecision = value;
  14388. },
  14389. enumerable: true,
  14390. configurable: true
  14391. });
  14392. // Cache
  14393. ArcRotateCamera.prototype._initCache = function () {
  14394. _super.prototype._initCache.call(this);
  14395. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14396. this._cache.alpha = undefined;
  14397. this._cache.beta = undefined;
  14398. this._cache.radius = undefined;
  14399. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  14400. };
  14401. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  14402. if (!ignoreParentClass) {
  14403. _super.prototype._updateCache.call(this);
  14404. }
  14405. this._cache.target.copyFrom(this._getTargetPosition());
  14406. this._cache.alpha = this.alpha;
  14407. this._cache.beta = this.beta;
  14408. this._cache.radius = this.radius;
  14409. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  14410. };
  14411. ArcRotateCamera.prototype._getTargetPosition = function () {
  14412. if (this.target.getAbsolutePosition) {
  14413. return this.target.getAbsolutePosition();
  14414. }
  14415. return this.target;
  14416. };
  14417. // Synchronized
  14418. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  14419. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  14420. return false;
  14421. return this._cache.target.equals(this.target)
  14422. && this._cache.alpha === this.alpha
  14423. && this._cache.beta === this.beta
  14424. && this._cache.radius === this.radius
  14425. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  14426. };
  14427. // Methods
  14428. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  14429. var _this = this;
  14430. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  14431. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  14432. this._useCtrlForPanning = useCtrlForPanning;
  14433. this._panningMouseButton = panningMouseButton;
  14434. this.inputs.attachElement(element, noPreventDefault);
  14435. this._reset = function () {
  14436. _this.inertialAlphaOffset = 0;
  14437. _this.inertialBetaOffset = 0;
  14438. _this.inertialRadiusOffset = 0;
  14439. };
  14440. };
  14441. ArcRotateCamera.prototype.detachControl = function (element) {
  14442. this.inputs.detachElement(element);
  14443. if (this._reset) {
  14444. this._reset();
  14445. }
  14446. };
  14447. ArcRotateCamera.prototype._checkInputs = function () {
  14448. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  14449. if (this._collisionTriggered) {
  14450. return;
  14451. }
  14452. this.inputs.checkInputs();
  14453. // Inertia
  14454. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  14455. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  14456. this.beta += this.inertialBetaOffset;
  14457. this.radius -= this.inertialRadiusOffset;
  14458. this.inertialAlphaOffset *= this.inertia;
  14459. this.inertialBetaOffset *= this.inertia;
  14460. this.inertialRadiusOffset *= this.inertia;
  14461. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  14462. this.inertialAlphaOffset = 0;
  14463. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  14464. this.inertialBetaOffset = 0;
  14465. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  14466. this.inertialRadiusOffset = 0;
  14467. }
  14468. // Panning inertia
  14469. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  14470. if (!this._localDirection) {
  14471. this._localDirection = BABYLON.Vector3.Zero();
  14472. this._transformedDirection = BABYLON.Vector3.Zero();
  14473. }
  14474. this.inertialPanningX *= this.inertia;
  14475. this.inertialPanningY *= this.inertia;
  14476. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  14477. this.inertialPanningX = 0;
  14478. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  14479. this.inertialPanningY = 0;
  14480. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  14481. this._localDirection.multiplyInPlace(this.panningAxis);
  14482. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  14483. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  14484. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  14485. if (!this.panningAxis.y) {
  14486. this._transformedDirection.y = 0;
  14487. }
  14488. if (!this.target.getAbsolutePosition) {
  14489. this.target.addInPlace(this._transformedDirection);
  14490. }
  14491. }
  14492. // Limits
  14493. this._checkLimits();
  14494. _super.prototype._checkInputs.call(this);
  14495. };
  14496. ArcRotateCamera.prototype._checkLimits = function () {
  14497. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  14498. if (this.allowUpsideDown && this.beta > Math.PI) {
  14499. this.beta = this.beta - (2 * Math.PI);
  14500. }
  14501. }
  14502. else {
  14503. if (this.beta < this.lowerBetaLimit) {
  14504. this.beta = this.lowerBetaLimit;
  14505. }
  14506. }
  14507. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  14508. if (this.allowUpsideDown && this.beta < -Math.PI) {
  14509. this.beta = this.beta + (2 * Math.PI);
  14510. }
  14511. }
  14512. else {
  14513. if (this.beta > this.upperBetaLimit) {
  14514. this.beta = this.upperBetaLimit;
  14515. }
  14516. }
  14517. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  14518. this.alpha = this.lowerAlphaLimit;
  14519. }
  14520. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  14521. this.alpha = this.upperAlphaLimit;
  14522. }
  14523. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  14524. this.radius = this.lowerRadiusLimit;
  14525. }
  14526. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  14527. this.radius = this.upperRadiusLimit;
  14528. }
  14529. };
  14530. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  14531. var radiusv3 = this.position.subtract(this._getTargetPosition());
  14532. this.radius = radiusv3.length();
  14533. // Alpha
  14534. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  14535. if (radiusv3.z < 0) {
  14536. this.alpha = 2 * Math.PI - this.alpha;
  14537. }
  14538. // Beta
  14539. this.beta = Math.acos(radiusv3.y / this.radius);
  14540. this._checkLimits();
  14541. };
  14542. ArcRotateCamera.prototype.setPosition = function (position) {
  14543. if (this.position.equals(position)) {
  14544. return;
  14545. }
  14546. this.position.copyFrom(position);
  14547. this.rebuildAnglesAndRadius();
  14548. };
  14549. ArcRotateCamera.prototype.setTarget = function (target) {
  14550. if (this._getTargetPosition().equals(target)) {
  14551. return;
  14552. }
  14553. this.target = target;
  14554. this.rebuildAnglesAndRadius();
  14555. };
  14556. ArcRotateCamera.prototype._getViewMatrix = function () {
  14557. // Compute
  14558. var cosa = Math.cos(this.alpha);
  14559. var sina = Math.sin(this.alpha);
  14560. var cosb = Math.cos(this.beta);
  14561. var sinb = Math.sin(this.beta);
  14562. if (sinb === 0) {
  14563. sinb = 0.0001;
  14564. }
  14565. var target = this._getTargetPosition();
  14566. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  14567. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  14568. this._collider.radius = this.collisionRadius;
  14569. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  14570. this._collisionTriggered = true;
  14571. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14572. }
  14573. else {
  14574. this.position.copyFrom(this._newPosition);
  14575. var up = this.upVector;
  14576. if (this.allowUpsideDown && this.beta < 0) {
  14577. up = up.clone();
  14578. up = up.negate();
  14579. }
  14580. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  14581. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  14582. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  14583. }
  14584. return this._viewMatrix;
  14585. };
  14586. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  14587. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  14588. meshes = meshes || this.getScene().meshes;
  14589. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  14590. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  14591. this.radius = distance * this.zoomOnFactor;
  14592. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  14593. };
  14594. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  14595. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  14596. var meshesOrMinMaxVector;
  14597. var distance;
  14598. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  14599. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  14600. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  14601. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  14602. }
  14603. else {
  14604. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  14605. distance = meshesOrMinMaxVectorAndDistance.distance;
  14606. }
  14607. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  14608. if (!doNotUpdateMaxZ) {
  14609. this.maxZ = distance * 2;
  14610. }
  14611. };
  14612. /**
  14613. * @override
  14614. * Override Camera.createRigCamera
  14615. */
  14616. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14617. var alphaShift;
  14618. switch (this.cameraRigMode) {
  14619. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14620. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14621. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14622. case BABYLON.Camera.RIG_MODE_VR:
  14623. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  14624. break;
  14625. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14626. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  14627. break;
  14628. }
  14629. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  14630. rigCam._cameraRigParams = {};
  14631. return rigCam;
  14632. };
  14633. /**
  14634. * @override
  14635. * Override Camera._updateRigCameras
  14636. */
  14637. ArcRotateCamera.prototype._updateRigCameras = function () {
  14638. var camLeft = this._rigCameras[0];
  14639. var camRight = this._rigCameras[1];
  14640. camLeft.beta = camRight.beta = this.beta;
  14641. camLeft.radius = camRight.radius = this.radius;
  14642. switch (this.cameraRigMode) {
  14643. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14644. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14645. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14646. case BABYLON.Camera.RIG_MODE_VR:
  14647. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  14648. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  14649. break;
  14650. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14651. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  14652. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  14653. break;
  14654. }
  14655. _super.prototype._updateRigCameras.call(this);
  14656. };
  14657. ArcRotateCamera.prototype.dispose = function () {
  14658. this.inputs.clear();
  14659. _super.prototype.dispose.call(this);
  14660. };
  14661. ArcRotateCamera.prototype.getTypeName = function () {
  14662. return "ArcRotateCamera";
  14663. };
  14664. __decorate([
  14665. BABYLON.serialize()
  14666. ], ArcRotateCamera.prototype, "alpha", void 0);
  14667. __decorate([
  14668. BABYLON.serialize()
  14669. ], ArcRotateCamera.prototype, "beta", void 0);
  14670. __decorate([
  14671. BABYLON.serialize()
  14672. ], ArcRotateCamera.prototype, "radius", void 0);
  14673. __decorate([
  14674. BABYLON.serializeAsVector3()
  14675. ], ArcRotateCamera.prototype, "target", void 0);
  14676. __decorate([
  14677. BABYLON.serialize()
  14678. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  14679. __decorate([
  14680. BABYLON.serialize()
  14681. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  14682. __decorate([
  14683. BABYLON.serialize()
  14684. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  14685. __decorate([
  14686. BABYLON.serialize()
  14687. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  14688. __decorate([
  14689. BABYLON.serialize()
  14690. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  14691. __decorate([
  14692. BABYLON.serialize()
  14693. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  14694. __decorate([
  14695. BABYLON.serialize()
  14696. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  14697. __decorate([
  14698. BABYLON.serialize()
  14699. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  14700. __decorate([
  14701. BABYLON.serialize()
  14702. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  14703. __decorate([
  14704. BABYLON.serialize()
  14705. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  14706. __decorate([
  14707. BABYLON.serialize()
  14708. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  14709. __decorate([
  14710. BABYLON.serialize()
  14711. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  14712. __decorate([
  14713. BABYLON.serialize()
  14714. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  14715. return ArcRotateCamera;
  14716. }(BABYLON.TargetCamera));
  14717. BABYLON.ArcRotateCamera = ArcRotateCamera;
  14718. })(BABYLON || (BABYLON = {}));
  14719. var BABYLON;
  14720. (function (BABYLON) {
  14721. var ArcRotateCameraInputsManager = (function (_super) {
  14722. __extends(ArcRotateCameraInputsManager, _super);
  14723. function ArcRotateCameraInputsManager(camera) {
  14724. _super.call(this, camera);
  14725. }
  14726. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  14727. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  14728. return this;
  14729. };
  14730. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  14731. this.add(new BABYLON.ArcRotateCameraPointersInput());
  14732. return this;
  14733. };
  14734. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  14735. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  14736. return this;
  14737. };
  14738. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  14739. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  14740. return this;
  14741. };
  14742. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  14743. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  14744. return this;
  14745. };
  14746. return ArcRotateCameraInputsManager;
  14747. }(BABYLON.CameraInputsManager));
  14748. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  14749. })(BABYLON || (BABYLON = {}));
  14750. var BABYLON;
  14751. (function (BABYLON) {
  14752. var RenderingManager = (function () {
  14753. function RenderingManager(scene) {
  14754. this._renderingGroups = new Array();
  14755. this._scene = scene;
  14756. }
  14757. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  14758. if (this._scene._activeParticleSystems.length === 0) {
  14759. return;
  14760. }
  14761. // Particles
  14762. var activeCamera = this._scene.activeCamera;
  14763. this._scene._particlesDuration.beginMonitoring();
  14764. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  14765. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  14766. if (particleSystem.renderingGroupId !== index) {
  14767. continue;
  14768. }
  14769. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  14770. continue;
  14771. }
  14772. this._clearDepthBuffer();
  14773. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  14774. this._scene._activeParticles.addCount(particleSystem.render(), false);
  14775. }
  14776. }
  14777. this._scene._particlesDuration.endMonitoring(false);
  14778. };
  14779. RenderingManager.prototype._renderSprites = function (index) {
  14780. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  14781. return;
  14782. }
  14783. // Sprites
  14784. var activeCamera = this._scene.activeCamera;
  14785. this._scene._spritesDuration.beginMonitoring();
  14786. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  14787. var spriteManager = this._scene.spriteManagers[id];
  14788. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  14789. this._clearDepthBuffer();
  14790. spriteManager.render();
  14791. }
  14792. }
  14793. this._scene._spritesDuration.endMonitoring(false);
  14794. };
  14795. RenderingManager.prototype._clearDepthBuffer = function () {
  14796. if (this._depthBufferAlreadyCleaned) {
  14797. return;
  14798. }
  14799. this._scene.getEngine().clear(0, false, true);
  14800. this._depthBufferAlreadyCleaned = true;
  14801. };
  14802. RenderingManager.prototype._renderSpritesAndParticles = function () {
  14803. if (this._currentRenderSprites) {
  14804. this._renderSprites(this._currentIndex);
  14805. }
  14806. if (this._currentRenderParticles) {
  14807. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  14808. }
  14809. };
  14810. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14811. this._currentActiveMeshes = activeMeshes;
  14812. this._currentRenderParticles = renderParticles;
  14813. this._currentRenderSprites = renderSprites;
  14814. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14815. this._depthBufferAlreadyCleaned = index === 0;
  14816. var renderingGroup = this._renderingGroups[index];
  14817. var needToStepBack = false;
  14818. this._currentIndex = index;
  14819. if (renderingGroup) {
  14820. this._clearDepthBuffer();
  14821. if (!renderingGroup.onBeforeTransparentRendering) {
  14822. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  14823. }
  14824. if (!renderingGroup.render(customRenderFunction)) {
  14825. this._renderingGroups.splice(index, 1);
  14826. needToStepBack = true;
  14827. this._renderSpritesAndParticles();
  14828. }
  14829. }
  14830. else {
  14831. this._renderSpritesAndParticles();
  14832. }
  14833. if (needToStepBack) {
  14834. index--;
  14835. }
  14836. }
  14837. };
  14838. RenderingManager.prototype.reset = function () {
  14839. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  14840. if (renderingGroup) {
  14841. renderingGroup.prepare();
  14842. }
  14843. });
  14844. };
  14845. RenderingManager.prototype.dispatch = function (subMesh) {
  14846. var mesh = subMesh.getMesh();
  14847. var renderingGroupId = mesh.renderingGroupId || 0;
  14848. if (!this._renderingGroups[renderingGroupId]) {
  14849. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  14850. }
  14851. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14852. };
  14853. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14854. return RenderingManager;
  14855. }());
  14856. BABYLON.RenderingManager = RenderingManager;
  14857. })(BABYLON || (BABYLON = {}));
  14858. var BABYLON;
  14859. (function (BABYLON) {
  14860. var RenderingGroup = (function () {
  14861. function RenderingGroup(index, scene) {
  14862. this.index = index;
  14863. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14864. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14865. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14866. this._scene = scene;
  14867. }
  14868. RenderingGroup.prototype.render = function (customRenderFunction) {
  14869. if (customRenderFunction) {
  14870. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14871. return true;
  14872. }
  14873. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  14874. if (this.onBeforeTransparentRendering) {
  14875. this.onBeforeTransparentRendering();
  14876. }
  14877. return false;
  14878. }
  14879. var engine = this._scene.getEngine();
  14880. // Opaque
  14881. var subIndex;
  14882. var submesh;
  14883. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  14884. submesh = this._opaqueSubMeshes.data[subIndex];
  14885. submesh.render(false);
  14886. }
  14887. // Alpha test
  14888. engine.setAlphaTesting(true);
  14889. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  14890. submesh = this._alphaTestSubMeshes.data[subIndex];
  14891. submesh.render(false);
  14892. }
  14893. engine.setAlphaTesting(false);
  14894. if (this.onBeforeTransparentRendering) {
  14895. this.onBeforeTransparentRendering();
  14896. }
  14897. // Transparent
  14898. if (this._transparentSubMeshes.length) {
  14899. // Sorting
  14900. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  14901. submesh = this._transparentSubMeshes.data[subIndex];
  14902. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  14903. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  14904. }
  14905. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  14906. sortedArray.sort(function (a, b) {
  14907. // Alpha index first
  14908. if (a._alphaIndex > b._alphaIndex) {
  14909. return 1;
  14910. }
  14911. if (a._alphaIndex < b._alphaIndex) {
  14912. return -1;
  14913. }
  14914. // Then distance to camera
  14915. if (a._distanceToCamera < b._distanceToCamera) {
  14916. return 1;
  14917. }
  14918. if (a._distanceToCamera > b._distanceToCamera) {
  14919. return -1;
  14920. }
  14921. return 0;
  14922. });
  14923. // Rendering
  14924. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14925. submesh = sortedArray[subIndex];
  14926. submesh.render(true);
  14927. }
  14928. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14929. }
  14930. return true;
  14931. };
  14932. RenderingGroup.prototype.prepare = function () {
  14933. this._opaqueSubMeshes.reset();
  14934. this._transparentSubMeshes.reset();
  14935. this._alphaTestSubMeshes.reset();
  14936. };
  14937. RenderingGroup.prototype.dispatch = function (subMesh) {
  14938. var material = subMesh.getMaterial();
  14939. var mesh = subMesh.getMesh();
  14940. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  14941. this._transparentSubMeshes.push(subMesh);
  14942. }
  14943. else if (material.needAlphaTesting()) {
  14944. this._alphaTestSubMeshes.push(subMesh);
  14945. }
  14946. else {
  14947. this._opaqueSubMeshes.push(subMesh); // Opaque
  14948. }
  14949. };
  14950. return RenderingGroup;
  14951. }());
  14952. BABYLON.RenderingGroup = RenderingGroup;
  14953. })(BABYLON || (BABYLON = {}));
  14954. var BABYLON;
  14955. (function (BABYLON) {
  14956. var PointerEventTypes = (function () {
  14957. function PointerEventTypes() {
  14958. }
  14959. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  14960. get: function () {
  14961. return PointerEventTypes._POINTERDOWN;
  14962. },
  14963. enumerable: true,
  14964. configurable: true
  14965. });
  14966. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  14967. get: function () {
  14968. return PointerEventTypes._POINTERUP;
  14969. },
  14970. enumerable: true,
  14971. configurable: true
  14972. });
  14973. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  14974. get: function () {
  14975. return PointerEventTypes._POINTERMOVE;
  14976. },
  14977. enumerable: true,
  14978. configurable: true
  14979. });
  14980. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  14981. get: function () {
  14982. return PointerEventTypes._POINTERWHEEL;
  14983. },
  14984. enumerable: true,
  14985. configurable: true
  14986. });
  14987. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  14988. get: function () {
  14989. return PointerEventTypes._POINTERPICK;
  14990. },
  14991. enumerable: true,
  14992. configurable: true
  14993. });
  14994. PointerEventTypes._POINTERDOWN = 0x01;
  14995. PointerEventTypes._POINTERUP = 0x02;
  14996. PointerEventTypes._POINTERMOVE = 0x04;
  14997. PointerEventTypes._POINTERWHEEL = 0x08;
  14998. PointerEventTypes._POINTERPICK = 0x10;
  14999. return PointerEventTypes;
  15000. }());
  15001. BABYLON.PointerEventTypes = PointerEventTypes;
  15002. var PointerInfoBase = (function () {
  15003. function PointerInfoBase(type, event) {
  15004. this.type = type;
  15005. this.event = event;
  15006. }
  15007. return PointerInfoBase;
  15008. }());
  15009. BABYLON.PointerInfoBase = PointerInfoBase;
  15010. /**
  15011. * This class is used to store pointer related info for the onPrePointerObservable event.
  15012. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15013. */
  15014. var PointerInfoPre = (function (_super) {
  15015. __extends(PointerInfoPre, _super);
  15016. function PointerInfoPre(type, event, localX, localY) {
  15017. _super.call(this, type, event);
  15018. this.skipOnPointerObservable = false;
  15019. this.localPosition = new BABYLON.Vector2(localX, localY);
  15020. }
  15021. return PointerInfoPre;
  15022. }(PointerInfoBase));
  15023. BABYLON.PointerInfoPre = PointerInfoPre;
  15024. /**
  15025. * This type contains all the data related to a pointer event in Babylon.js.
  15026. * 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.
  15027. */
  15028. var PointerInfo = (function (_super) {
  15029. __extends(PointerInfo, _super);
  15030. function PointerInfo(type, event, pickInfo) {
  15031. _super.call(this, type, event);
  15032. this.pickInfo = pickInfo;
  15033. }
  15034. return PointerInfo;
  15035. }(PointerInfoBase));
  15036. BABYLON.PointerInfo = PointerInfo;
  15037. /**
  15038. * Represents a scene to be rendered by the engine.
  15039. * @see http://doc.babylonjs.com/page.php?p=21911
  15040. */
  15041. var Scene = (function () {
  15042. /**
  15043. * @constructor
  15044. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15045. */
  15046. function Scene(engine) {
  15047. // Members
  15048. this.autoClear = true;
  15049. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15050. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15051. this.forceWireframe = false;
  15052. this.forcePointsCloud = false;
  15053. this.forceShowBoundingBoxes = false;
  15054. this.animationsEnabled = true;
  15055. this.constantlyUpdateMeshUnderPointer = false;
  15056. this.hoverCursor = "pointer";
  15057. // Events
  15058. /**
  15059. * An event triggered when the scene is disposed.
  15060. * @type {BABYLON.Observable}
  15061. */
  15062. this.onDisposeObservable = new BABYLON.Observable();
  15063. /**
  15064. * An event triggered before rendering the scene
  15065. * @type {BABYLON.Observable}
  15066. */
  15067. this.onBeforeRenderObservable = new BABYLON.Observable();
  15068. /**
  15069. * An event triggered after rendering the scene
  15070. * @type {BABYLON.Observable}
  15071. */
  15072. this.onAfterRenderObservable = new BABYLON.Observable();
  15073. /**
  15074. * An event triggered when the scene is ready
  15075. * @type {BABYLON.Observable}
  15076. */
  15077. this.onReadyObservable = new BABYLON.Observable();
  15078. /**
  15079. * An event triggered before rendering a camera
  15080. * @type {BABYLON.Observable}
  15081. */
  15082. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15083. /**
  15084. * An event triggered after rendering a camera
  15085. * @type {BABYLON.Observable}
  15086. */
  15087. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15088. /**
  15089. * An event triggered when a camera is created
  15090. * @type {BABYLON.Observable}
  15091. */
  15092. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15093. /**
  15094. * An event triggered when a camera is removed
  15095. * @type {BABYLON.Observable}
  15096. */
  15097. this.onCameraRemovedObservable = new BABYLON.Observable();
  15098. /**
  15099. * An event triggered when a light is created
  15100. * @type {BABYLON.Observable}
  15101. */
  15102. this.onNewLightAddedObservable = new BABYLON.Observable();
  15103. /**
  15104. * An event triggered when a light is removed
  15105. * @type {BABYLON.Observable}
  15106. */
  15107. this.onLightRemovedObservable = new BABYLON.Observable();
  15108. /**
  15109. * An event triggered when a geometry is created
  15110. * @type {BABYLON.Observable}
  15111. */
  15112. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15113. /**
  15114. * An event triggered when a geometry is removed
  15115. * @type {BABYLON.Observable}
  15116. */
  15117. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15118. /**
  15119. * An event triggered when a mesh is created
  15120. * @type {BABYLON.Observable}
  15121. */
  15122. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15123. /**
  15124. * An event triggered when a mesh is removed
  15125. * @type {BABYLON.Observable}
  15126. */
  15127. this.onMeshRemovedObservable = new BABYLON.Observable();
  15128. // Animations
  15129. this.animations = [];
  15130. /**
  15131. * 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).
  15132. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15133. */
  15134. this.onPrePointerObservable = new BABYLON.Observable();
  15135. /**
  15136. * Observable event triggered each time an input event is received from the rendering canvas
  15137. */
  15138. this.onPointerObservable = new BABYLON.Observable();
  15139. 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
  15140. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15141. this._startingPointerTime = 0;
  15142. // Fog
  15143. /**
  15144. * is fog enabled on this scene.
  15145. * @type {boolean}
  15146. */
  15147. this.fogEnabled = true;
  15148. this.fogMode = Scene.FOGMODE_NONE;
  15149. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15150. this.fogDensity = 0.1;
  15151. this.fogStart = 0;
  15152. this.fogEnd = 1000.0;
  15153. // Lights
  15154. /**
  15155. * is shadow enabled on this scene.
  15156. * @type {boolean}
  15157. */
  15158. this.shadowsEnabled = true;
  15159. /**
  15160. * is light enabled on this scene.
  15161. * @type {boolean}
  15162. */
  15163. this.lightsEnabled = true;
  15164. /**
  15165. * All of the lights added to this scene.
  15166. * @see BABYLON.Light
  15167. * @type {BABYLON.Light[]}
  15168. */
  15169. this.lights = new Array();
  15170. // Cameras
  15171. /**
  15172. * All of the cameras added to this scene.
  15173. * @see BABYLON.Camera
  15174. * @type {BABYLON.Camera[]}
  15175. */
  15176. this.cameras = new Array();
  15177. this.activeCameras = new Array();
  15178. // Meshes
  15179. /**
  15180. * All of the (abstract) meshes added to this scene.
  15181. * @see BABYLON.AbstractMesh
  15182. * @type {BABYLON.AbstractMesh[]}
  15183. */
  15184. this.meshes = new Array();
  15185. // Geometries
  15186. this._geometries = new Array();
  15187. this.materials = new Array();
  15188. this.multiMaterials = new Array();
  15189. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15190. // Textures
  15191. this.texturesEnabled = true;
  15192. this.textures = new Array();
  15193. // Particles
  15194. this.particlesEnabled = true;
  15195. this.particleSystems = new Array();
  15196. // Sprites
  15197. this.spritesEnabled = true;
  15198. this.spriteManagers = new Array();
  15199. // Layers
  15200. this.layers = new Array();
  15201. // Skeletons
  15202. this.skeletonsEnabled = true;
  15203. this.skeletons = new Array();
  15204. // Lens flares
  15205. this.lensFlaresEnabled = true;
  15206. this.lensFlareSystems = new Array();
  15207. // Collisions
  15208. this.collisionsEnabled = true;
  15209. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15210. // Postprocesses
  15211. this.postProcessesEnabled = true;
  15212. // Customs render targets
  15213. this.renderTargetsEnabled = true;
  15214. this.dumpNextRenderTargets = false;
  15215. this.customRenderTargets = new Array();
  15216. // Imported meshes
  15217. this.importedMeshesFiles = new Array();
  15218. // Probes
  15219. this.probesEnabled = true;
  15220. this.reflectionProbes = new Array();
  15221. this._actionManagers = new Array();
  15222. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15223. // Procedural textures
  15224. this.proceduralTexturesEnabled = true;
  15225. this._proceduralTextures = new Array();
  15226. this.soundTracks = new Array();
  15227. this._audioEnabled = true;
  15228. this._headphone = false;
  15229. // Performance counters
  15230. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15231. this._totalLightsCounter = new BABYLON.PerfCounter();
  15232. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15233. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15234. this._totalVertices = new BABYLON.PerfCounter();
  15235. this._activeIndices = new BABYLON.PerfCounter();
  15236. this._activeParticles = new BABYLON.PerfCounter();
  15237. this._lastFrameDuration = new BABYLON.PerfCounter();
  15238. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15239. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15240. this._particlesDuration = new BABYLON.PerfCounter();
  15241. this._renderDuration = new BABYLON.PerfCounter();
  15242. this._spritesDuration = new BABYLON.PerfCounter();
  15243. this._activeBones = new BABYLON.PerfCounter();
  15244. this._renderId = 0;
  15245. this._executeWhenReadyTimeoutId = -1;
  15246. this._intermediateRendering = false;
  15247. this._toBeDisposed = new BABYLON.SmartArray(256);
  15248. this._pendingData = []; //ANY
  15249. this._activeMeshes = new BABYLON.SmartArray(256);
  15250. this._processedMaterials = new BABYLON.SmartArray(256);
  15251. this._renderTargets = new BABYLON.SmartArray(256);
  15252. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15253. this._activeSkeletons = new BABYLON.SmartArray(32);
  15254. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15255. this._activeAnimatables = new Array();
  15256. this._transformMatrix = BABYLON.Matrix.Zero();
  15257. this._edgesRenderers = new BABYLON.SmartArray(16);
  15258. this._uniqueIdCounter = 0;
  15259. this._engine = engine;
  15260. engine.scenes.push(this);
  15261. this._renderingManager = new BABYLON.RenderingManager(this);
  15262. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15263. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15264. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  15265. if (BABYLON.OutlineRenderer) {
  15266. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15267. }
  15268. this.attachControl();
  15269. if (BABYLON.SoundTrack) {
  15270. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15271. }
  15272. //simplification queue
  15273. if (BABYLON.SimplificationQueue) {
  15274. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15275. }
  15276. //collision coordinator initialization. For now legacy per default.
  15277. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15278. }
  15279. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15280. get: function () {
  15281. return Scene._FOGMODE_NONE;
  15282. },
  15283. enumerable: true,
  15284. configurable: true
  15285. });
  15286. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15287. get: function () {
  15288. return Scene._FOGMODE_EXP;
  15289. },
  15290. enumerable: true,
  15291. configurable: true
  15292. });
  15293. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15294. get: function () {
  15295. return Scene._FOGMODE_EXP2;
  15296. },
  15297. enumerable: true,
  15298. configurable: true
  15299. });
  15300. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15301. get: function () {
  15302. return Scene._FOGMODE_LINEAR;
  15303. },
  15304. enumerable: true,
  15305. configurable: true
  15306. });
  15307. Object.defineProperty(Scene.prototype, "onDispose", {
  15308. set: function (callback) {
  15309. if (this._onDisposeObserver) {
  15310. this.onDisposeObservable.remove(this._onDisposeObserver);
  15311. }
  15312. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15313. },
  15314. enumerable: true,
  15315. configurable: true
  15316. });
  15317. Object.defineProperty(Scene.prototype, "beforeRender", {
  15318. set: function (callback) {
  15319. if (this._onBeforeRenderObserver) {
  15320. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15321. }
  15322. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15323. },
  15324. enumerable: true,
  15325. configurable: true
  15326. });
  15327. Object.defineProperty(Scene.prototype, "afterRender", {
  15328. set: function (callback) {
  15329. if (this._onAfterRenderObserver) {
  15330. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15331. }
  15332. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15333. },
  15334. enumerable: true,
  15335. configurable: true
  15336. });
  15337. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15338. set: function (callback) {
  15339. if (this._onBeforeCameraRenderObserver) {
  15340. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15341. }
  15342. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15343. },
  15344. enumerable: true,
  15345. configurable: true
  15346. });
  15347. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15348. set: function (callback) {
  15349. if (this._onAfterCameraRenderObserver) {
  15350. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15351. }
  15352. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15353. },
  15354. enumerable: true,
  15355. configurable: true
  15356. });
  15357. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15358. get: function () {
  15359. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15360. },
  15361. enumerable: true,
  15362. configurable: true
  15363. });
  15364. Object.defineProperty(Scene.prototype, "debugLayer", {
  15365. // Properties
  15366. get: function () {
  15367. if (!this._debugLayer) {
  15368. this._debugLayer = new BABYLON.DebugLayer(this);
  15369. }
  15370. return this._debugLayer;
  15371. },
  15372. enumerable: true,
  15373. configurable: true
  15374. });
  15375. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15376. get: function () {
  15377. return this._workerCollisions;
  15378. },
  15379. set: function (enabled) {
  15380. enabled = (enabled && !!Worker);
  15381. this._workerCollisions = enabled;
  15382. if (this.collisionCoordinator) {
  15383. this.collisionCoordinator.destroy();
  15384. }
  15385. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15386. this.collisionCoordinator.init(this);
  15387. },
  15388. enumerable: true,
  15389. configurable: true
  15390. });
  15391. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  15392. get: function () {
  15393. return this._selectionOctree;
  15394. },
  15395. enumerable: true,
  15396. configurable: true
  15397. });
  15398. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15399. /**
  15400. * The mesh that is currently under the pointer.
  15401. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15402. */
  15403. get: function () {
  15404. return this._pointerOverMesh;
  15405. },
  15406. enumerable: true,
  15407. configurable: true
  15408. });
  15409. Object.defineProperty(Scene.prototype, "pointerX", {
  15410. /**
  15411. * Current on-screen X position of the pointer
  15412. * @return {number} X position of the pointer
  15413. */
  15414. get: function () {
  15415. return this._pointerX;
  15416. },
  15417. enumerable: true,
  15418. configurable: true
  15419. });
  15420. Object.defineProperty(Scene.prototype, "pointerY", {
  15421. /**
  15422. * Current on-screen Y position of the pointer
  15423. * @return {number} Y position of the pointer
  15424. */
  15425. get: function () {
  15426. return this._pointerY;
  15427. },
  15428. enumerable: true,
  15429. configurable: true
  15430. });
  15431. Scene.prototype.getCachedMaterial = function () {
  15432. return this._cachedMaterial;
  15433. };
  15434. Scene.prototype.getBoundingBoxRenderer = function () {
  15435. return this._boundingBoxRenderer;
  15436. };
  15437. Scene.prototype.getOutlineRenderer = function () {
  15438. return this._outlineRenderer;
  15439. };
  15440. Scene.prototype.getEngine = function () {
  15441. return this._engine;
  15442. };
  15443. Scene.prototype.getTotalVertices = function () {
  15444. return this._totalVertices.current;
  15445. };
  15446. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  15447. get: function () {
  15448. return this._totalVertices;
  15449. },
  15450. enumerable: true,
  15451. configurable: true
  15452. });
  15453. Scene.prototype.getActiveIndices = function () {
  15454. return this._activeIndices.current;
  15455. };
  15456. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  15457. get: function () {
  15458. return this._activeIndices;
  15459. },
  15460. enumerable: true,
  15461. configurable: true
  15462. });
  15463. Scene.prototype.getActiveParticles = function () {
  15464. return this._activeParticles.current;
  15465. };
  15466. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  15467. get: function () {
  15468. return this._activeParticles;
  15469. },
  15470. enumerable: true,
  15471. configurable: true
  15472. });
  15473. Scene.prototype.getActiveBones = function () {
  15474. return this._activeBones.current;
  15475. };
  15476. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  15477. get: function () {
  15478. return this._activeBones;
  15479. },
  15480. enumerable: true,
  15481. configurable: true
  15482. });
  15483. // Stats
  15484. Scene.prototype.getLastFrameDuration = function () {
  15485. return this._lastFrameDuration.current;
  15486. };
  15487. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  15488. get: function () {
  15489. return this._lastFrameDuration;
  15490. },
  15491. enumerable: true,
  15492. configurable: true
  15493. });
  15494. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  15495. return this._evaluateActiveMeshesDuration.current;
  15496. };
  15497. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  15498. get: function () {
  15499. return this._evaluateActiveMeshesDuration;
  15500. },
  15501. enumerable: true,
  15502. configurable: true
  15503. });
  15504. Scene.prototype.getActiveMeshes = function () {
  15505. return this._activeMeshes;
  15506. };
  15507. Scene.prototype.getRenderTargetsDuration = function () {
  15508. return this._renderTargetsDuration.current;
  15509. };
  15510. Scene.prototype.getRenderDuration = function () {
  15511. return this._renderDuration.current;
  15512. };
  15513. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  15514. get: function () {
  15515. return this._renderDuration;
  15516. },
  15517. enumerable: true,
  15518. configurable: true
  15519. });
  15520. Scene.prototype.getParticlesDuration = function () {
  15521. return this._particlesDuration.current;
  15522. };
  15523. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  15524. get: function () {
  15525. return this._particlesDuration;
  15526. },
  15527. enumerable: true,
  15528. configurable: true
  15529. });
  15530. Scene.prototype.getSpritesDuration = function () {
  15531. return this._spritesDuration.current;
  15532. };
  15533. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  15534. get: function () {
  15535. return this._spritesDuration;
  15536. },
  15537. enumerable: true,
  15538. configurable: true
  15539. });
  15540. Scene.prototype.getAnimationRatio = function () {
  15541. return this._animationRatio;
  15542. };
  15543. Scene.prototype.getRenderId = function () {
  15544. return this._renderId;
  15545. };
  15546. Scene.prototype.incrementRenderId = function () {
  15547. this._renderId++;
  15548. };
  15549. Scene.prototype._updatePointerPosition = function (evt) {
  15550. var canvasRect = this._engine.getRenderingCanvasClientRect();
  15551. this._pointerX = evt.clientX - canvasRect.left;
  15552. this._pointerY = evt.clientY - canvasRect.top;
  15553. this._unTranslatedPointerX = this._pointerX;
  15554. this._unTranslatedPointerY = this._pointerY;
  15555. if (this.cameraToUseForPointers) {
  15556. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  15557. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  15558. }
  15559. };
  15560. // Pointers handling
  15561. /**
  15562. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  15563. * @param attachUp defines if you want to attach events to pointerup
  15564. * @param attachDown defines if you want to attach events to pointerdown
  15565. * @param attachMove defines if you want to attach events to pointermove
  15566. */
  15567. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  15568. var _this = this;
  15569. if (attachUp === void 0) { attachUp = true; }
  15570. if (attachDown === void 0) { attachDown = true; }
  15571. if (attachMove === void 0) { attachMove = true; }
  15572. var spritePredicate = function (sprite) {
  15573. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  15574. };
  15575. this._onPointerMove = function (evt) {
  15576. _this._updatePointerPosition(evt);
  15577. // PreObservable support
  15578. if (_this.onPrePointerObservable.hasObservers()) {
  15579. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15580. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15581. _this.onPrePointerObservable.notifyObservers(pi, type);
  15582. if (pi.skipOnPointerObservable) {
  15583. return;
  15584. }
  15585. }
  15586. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15587. return;
  15588. }
  15589. var canvas = _this._engine.getRenderingCanvas();
  15590. if (!_this.pointerMovePredicate) {
  15591. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  15592. }
  15593. // Meshes
  15594. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  15595. if (pickResult.hit && pickResult.pickedMesh) {
  15596. _this.setPointerOverSprite(null);
  15597. _this.setPointerOverMesh(pickResult.pickedMesh);
  15598. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  15599. canvas.style.cursor = _this.hoverCursor;
  15600. }
  15601. else {
  15602. canvas.style.cursor = "";
  15603. }
  15604. }
  15605. else {
  15606. _this.setPointerOverMesh(null);
  15607. // Sprites
  15608. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15609. if (pickResult.hit && pickResult.pickedSprite) {
  15610. canvas.style.cursor = _this.hoverCursor;
  15611. _this.setPointerOverSprite(pickResult.pickedSprite);
  15612. }
  15613. else {
  15614. _this.setPointerOverSprite(null);
  15615. // Restore pointer
  15616. canvas.style.cursor = "";
  15617. }
  15618. }
  15619. if (_this.onPointerMove) {
  15620. _this.onPointerMove(evt, pickResult);
  15621. }
  15622. if (_this.onPointerObservable.hasObservers()) {
  15623. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15624. var pi = new PointerInfo(type, evt, pickResult);
  15625. _this.onPointerObservable.notifyObservers(pi, type);
  15626. }
  15627. };
  15628. this._onPointerDown = function (evt) {
  15629. _this._updatePointerPosition(evt);
  15630. // PreObservable support
  15631. if (_this.onPrePointerObservable.hasObservers()) {
  15632. var type = PointerEventTypes.POINTERDOWN;
  15633. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15634. _this.onPrePointerObservable.notifyObservers(pi, type);
  15635. if (pi.skipOnPointerObservable) {
  15636. return;
  15637. }
  15638. }
  15639. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15640. return;
  15641. }
  15642. _this._startingPointerPosition.x = _this._pointerX;
  15643. _this._startingPointerPosition.y = _this._pointerY;
  15644. _this._startingPointerTime = new Date().getTime();
  15645. if (!_this.pointerDownPredicate) {
  15646. _this.pointerDownPredicate = function (mesh) {
  15647. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  15648. };
  15649. }
  15650. // Meshes
  15651. _this._pickedDownMesh = null;
  15652. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  15653. if (pickResult.hit && pickResult.pickedMesh) {
  15654. if (pickResult.pickedMesh.actionManager) {
  15655. _this._pickedDownMesh = pickResult.pickedMesh;
  15656. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  15657. switch (evt.button) {
  15658. case 0:
  15659. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15660. break;
  15661. case 1:
  15662. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15663. break;
  15664. case 2:
  15665. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15666. break;
  15667. }
  15668. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15669. }
  15670. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  15671. var that = _this;
  15672. window.setTimeout(function () {
  15673. 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);
  15674. if (pickResult.hit && pickResult.pickedMesh) {
  15675. if (pickResult.pickedMesh.actionManager) {
  15676. 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)) {
  15677. that._startingPointerTime = 0;
  15678. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15679. }
  15680. }
  15681. }
  15682. }, BABYLON.ActionManager.LongPressDelay);
  15683. }
  15684. }
  15685. }
  15686. if (_this.onPointerDown) {
  15687. _this.onPointerDown(evt, pickResult);
  15688. }
  15689. if (_this.onPointerObservable.hasObservers()) {
  15690. var type = PointerEventTypes.POINTERDOWN;
  15691. var pi = new PointerInfo(type, evt, pickResult);
  15692. _this.onPointerObservable.notifyObservers(pi, type);
  15693. }
  15694. // Sprites
  15695. _this._pickedDownSprite = null;
  15696. if (_this.spriteManagers.length > 0) {
  15697. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15698. if (pickResult.hit && pickResult.pickedSprite) {
  15699. if (pickResult.pickedSprite.actionManager) {
  15700. _this._pickedDownSprite = pickResult.pickedSprite;
  15701. switch (evt.button) {
  15702. case 0:
  15703. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15704. break;
  15705. case 1:
  15706. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15707. break;
  15708. case 2:
  15709. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15710. break;
  15711. }
  15712. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15713. }
  15714. }
  15715. }
  15716. };
  15717. this._onPointerUp = function (evt) {
  15718. _this._updatePointerPosition(evt);
  15719. // PreObservable support
  15720. if (_this.onPrePointerObservable.hasObservers()) {
  15721. var type = PointerEventTypes.POINTERUP;
  15722. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15723. _this.onPrePointerObservable.notifyObservers(pi, type);
  15724. if (pi.skipOnPointerObservable) {
  15725. return;
  15726. }
  15727. }
  15728. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15729. return;
  15730. }
  15731. if (!_this.pointerUpPredicate) {
  15732. _this.pointerUpPredicate = function (mesh) {
  15733. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  15734. };
  15735. }
  15736. // Meshes
  15737. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  15738. if (pickResult.hit && pickResult.pickedMesh) {
  15739. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  15740. if (_this.onPointerPick) {
  15741. _this.onPointerPick(evt, pickResult);
  15742. }
  15743. if (_this.onPointerObservable.hasObservers()) {
  15744. var type = PointerEventTypes.POINTERPICK;
  15745. var pi = new PointerInfo(type, evt, pickResult);
  15746. _this.onPointerObservable.notifyObservers(pi, type);
  15747. }
  15748. }
  15749. if (pickResult.pickedMesh.actionManager) {
  15750. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15751. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  15752. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15753. }
  15754. }
  15755. }
  15756. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  15757. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  15758. }
  15759. if (_this.onPointerUp) {
  15760. _this.onPointerUp(evt, pickResult);
  15761. }
  15762. if (_this.onPointerObservable.hasObservers()) {
  15763. var type = PointerEventTypes.POINTERUP;
  15764. var pi = new PointerInfo(type, evt, pickResult);
  15765. _this.onPointerObservable.notifyObservers(pi, type);
  15766. }
  15767. _this._startingPointerTime = 0;
  15768. // Sprites
  15769. if (_this.spriteManagers.length > 0) {
  15770. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15771. if (pickResult.hit && pickResult.pickedSprite) {
  15772. if (pickResult.pickedSprite.actionManager) {
  15773. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15774. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  15775. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15776. }
  15777. }
  15778. }
  15779. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  15780. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  15781. }
  15782. }
  15783. };
  15784. this._onKeyDown = function (evt) {
  15785. if (_this.actionManager) {
  15786. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15787. }
  15788. };
  15789. this._onKeyUp = function (evt) {
  15790. if (_this.actionManager) {
  15791. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15792. }
  15793. };
  15794. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15795. var canvas = this._engine.getRenderingCanvas();
  15796. if (attachMove) {
  15797. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  15798. // Wheel
  15799. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  15800. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  15801. }
  15802. if (attachDown) {
  15803. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  15804. }
  15805. if (attachUp) {
  15806. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  15807. }
  15808. canvas.tabIndex = 1;
  15809. canvas.addEventListener("keydown", this._onKeyDown, false);
  15810. canvas.addEventListener("keyup", this._onKeyUp, false);
  15811. };
  15812. Scene.prototype.detachControl = function () {
  15813. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15814. var canvas = this._engine.getRenderingCanvas();
  15815. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  15816. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  15817. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  15818. // Wheel
  15819. canvas.removeEventListener('mousewheel', this._onPointerMove);
  15820. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  15821. canvas.removeEventListener("keydown", this._onKeyDown);
  15822. canvas.removeEventListener("keyup", this._onKeyUp);
  15823. };
  15824. // Ready
  15825. Scene.prototype.isReady = function () {
  15826. if (this._pendingData.length > 0) {
  15827. return false;
  15828. }
  15829. var index;
  15830. for (index = 0; index < this._geometries.length; index++) {
  15831. var geometry = this._geometries[index];
  15832. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15833. return false;
  15834. }
  15835. }
  15836. for (index = 0; index < this.meshes.length; index++) {
  15837. var mesh = this.meshes[index];
  15838. if (!mesh.isReady()) {
  15839. return false;
  15840. }
  15841. var mat = mesh.material;
  15842. if (mat) {
  15843. if (!mat.isReady(mesh)) {
  15844. return false;
  15845. }
  15846. }
  15847. }
  15848. return true;
  15849. };
  15850. Scene.prototype.resetCachedMaterial = function () {
  15851. this._cachedMaterial = null;
  15852. };
  15853. Scene.prototype.registerBeforeRender = function (func) {
  15854. this.onBeforeRenderObservable.add(func);
  15855. };
  15856. Scene.prototype.unregisterBeforeRender = function (func) {
  15857. this.onBeforeRenderObservable.removeCallback(func);
  15858. };
  15859. Scene.prototype.registerAfterRender = function (func) {
  15860. this.onAfterRenderObservable.add(func);
  15861. };
  15862. Scene.prototype.unregisterAfterRender = function (func) {
  15863. this.onAfterRenderObservable.removeCallback(func);
  15864. };
  15865. Scene.prototype._addPendingData = function (data) {
  15866. this._pendingData.push(data);
  15867. };
  15868. Scene.prototype._removePendingData = function (data) {
  15869. var index = this._pendingData.indexOf(data);
  15870. if (index !== -1) {
  15871. this._pendingData.splice(index, 1);
  15872. }
  15873. };
  15874. Scene.prototype.getWaitingItemsCount = function () {
  15875. return this._pendingData.length;
  15876. };
  15877. /**
  15878. * Registers a function to be executed when the scene is ready.
  15879. * @param {Function} func - the function to be executed.
  15880. */
  15881. Scene.prototype.executeWhenReady = function (func) {
  15882. var _this = this;
  15883. this.onReadyObservable.add(func);
  15884. if (this._executeWhenReadyTimeoutId !== -1) {
  15885. return;
  15886. }
  15887. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15888. _this._checkIsReady();
  15889. }, 150);
  15890. };
  15891. Scene.prototype._checkIsReady = function () {
  15892. var _this = this;
  15893. if (this.isReady()) {
  15894. this.onReadyObservable.notifyObservers(this);
  15895. this.onReadyObservable.clear();
  15896. this._executeWhenReadyTimeoutId = -1;
  15897. return;
  15898. }
  15899. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15900. _this._checkIsReady();
  15901. }, 150);
  15902. };
  15903. // Animations
  15904. /**
  15905. * Will start the animation sequence of a given target
  15906. * @param target - the target
  15907. * @param {number} from - from which frame should animation start
  15908. * @param {number} to - till which frame should animation run.
  15909. * @param {boolean} [loop] - should the animation loop
  15910. * @param {number} [speedRatio] - the speed in which to run the animation
  15911. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  15912. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  15913. * @return {BABYLON.Animatable} the animatable object created for this animation
  15914. * @see BABYLON.Animatable
  15915. * @see http://doc.babylonjs.com/page.php?p=22081
  15916. */
  15917. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  15918. if (speedRatio === void 0) { speedRatio = 1.0; }
  15919. this.stopAnimation(target);
  15920. if (!animatable) {
  15921. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  15922. }
  15923. // Local animations
  15924. if (target.animations) {
  15925. animatable.appendAnimations(target, target.animations);
  15926. }
  15927. // Children animations
  15928. if (target.getAnimatables) {
  15929. var animatables = target.getAnimatables();
  15930. for (var index = 0; index < animatables.length; index++) {
  15931. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  15932. }
  15933. }
  15934. animatable.reset();
  15935. return animatable;
  15936. };
  15937. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  15938. if (speedRatio === undefined) {
  15939. speedRatio = 1.0;
  15940. }
  15941. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  15942. return animatable;
  15943. };
  15944. Scene.prototype.getAnimatableByTarget = function (target) {
  15945. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15946. if (this._activeAnimatables[index].target === target) {
  15947. return this._activeAnimatables[index];
  15948. }
  15949. }
  15950. return null;
  15951. };
  15952. Object.defineProperty(Scene.prototype, "Animatables", {
  15953. get: function () {
  15954. return this._activeAnimatables;
  15955. },
  15956. enumerable: true,
  15957. configurable: true
  15958. });
  15959. /**
  15960. * Will stop the animation of the given target
  15961. * @param target - the target
  15962. * @see beginAnimation
  15963. */
  15964. Scene.prototype.stopAnimation = function (target) {
  15965. var animatable = this.getAnimatableByTarget(target);
  15966. if (animatable) {
  15967. animatable.stop();
  15968. }
  15969. };
  15970. Scene.prototype._animate = function () {
  15971. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  15972. return;
  15973. }
  15974. if (!this._animationStartDate) {
  15975. if (this._pendingData.length > 0) {
  15976. return;
  15977. }
  15978. this._animationStartDate = BABYLON.Tools.Now;
  15979. }
  15980. // Getting time
  15981. var now = BABYLON.Tools.Now;
  15982. var delay = now - this._animationStartDate;
  15983. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15984. this._activeAnimatables[index]._animate(delay);
  15985. }
  15986. };
  15987. // Matrix
  15988. Scene.prototype.getViewMatrix = function () {
  15989. return this._viewMatrix;
  15990. };
  15991. Scene.prototype.getProjectionMatrix = function () {
  15992. return this._projectionMatrix;
  15993. };
  15994. Scene.prototype.getTransformMatrix = function () {
  15995. return this._transformMatrix;
  15996. };
  15997. Scene.prototype.setTransformMatrix = function (view, projection) {
  15998. this._viewMatrix = view;
  15999. this._projectionMatrix = projection;
  16000. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16001. // Update frustum
  16002. if (!this._frustumPlanes) {
  16003. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16004. }
  16005. else {
  16006. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16007. }
  16008. };
  16009. // Methods
  16010. Scene.prototype.addMesh = function (newMesh) {
  16011. newMesh.uniqueId = this._uniqueIdCounter++;
  16012. var position = this.meshes.push(newMesh);
  16013. //notify the collision coordinator
  16014. this.collisionCoordinator.onMeshAdded(newMesh);
  16015. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  16016. };
  16017. Scene.prototype.removeMesh = function (toRemove) {
  16018. var index = this.meshes.indexOf(toRemove);
  16019. if (index !== -1) {
  16020. // Remove from the scene if mesh found
  16021. this.meshes.splice(index, 1);
  16022. }
  16023. //notify the collision coordinator
  16024. this.collisionCoordinator.onMeshRemoved(toRemove);
  16025. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16026. return index;
  16027. };
  16028. Scene.prototype.removeSkeleton = function (toRemove) {
  16029. var index = this.skeletons.indexOf(toRemove);
  16030. if (index !== -1) {
  16031. // Remove from the scene if mesh found
  16032. this.skeletons.splice(index, 1);
  16033. }
  16034. return index;
  16035. };
  16036. Scene.prototype.removeLight = function (toRemove) {
  16037. var index = this.lights.indexOf(toRemove);
  16038. if (index !== -1) {
  16039. // Remove from the scene if mesh found
  16040. this.lights.splice(index, 1);
  16041. }
  16042. this.onLightRemovedObservable.notifyObservers(toRemove);
  16043. return index;
  16044. };
  16045. Scene.prototype.removeCamera = function (toRemove) {
  16046. var index = this.cameras.indexOf(toRemove);
  16047. if (index !== -1) {
  16048. // Remove from the scene if mesh found
  16049. this.cameras.splice(index, 1);
  16050. }
  16051. // Remove from activeCameras
  16052. var index2 = this.activeCameras.indexOf(toRemove);
  16053. if (index2 !== -1) {
  16054. // Remove from the scene if mesh found
  16055. this.activeCameras.splice(index2, 1);
  16056. }
  16057. // Reset the activeCamera
  16058. if (this.activeCamera === toRemove) {
  16059. if (this.cameras.length > 0) {
  16060. this.activeCamera = this.cameras[0];
  16061. }
  16062. else {
  16063. this.activeCamera = null;
  16064. }
  16065. }
  16066. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16067. return index;
  16068. };
  16069. Scene.prototype.addLight = function (newLight) {
  16070. newLight.uniqueId = this._uniqueIdCounter++;
  16071. var position = this.lights.push(newLight);
  16072. this.onNewLightAddedObservable.notifyObservers(newLight);
  16073. };
  16074. Scene.prototype.addCamera = function (newCamera) {
  16075. newCamera.uniqueId = this._uniqueIdCounter++;
  16076. var position = this.cameras.push(newCamera);
  16077. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16078. };
  16079. /**
  16080. * Switch active camera
  16081. * @param {Camera} newCamera - new active camera
  16082. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16083. */
  16084. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16085. if (attachControl === void 0) { attachControl = true; }
  16086. var canvas = this._engine.getRenderingCanvas();
  16087. this.activeCamera.detachControl(canvas);
  16088. this.activeCamera = newCamera;
  16089. if (attachControl) {
  16090. newCamera.attachControl(canvas);
  16091. }
  16092. };
  16093. /**
  16094. * sets the active camera of the scene using its ID
  16095. * @param {string} id - the camera's ID
  16096. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16097. * @see activeCamera
  16098. */
  16099. Scene.prototype.setActiveCameraByID = function (id) {
  16100. var camera = this.getCameraByID(id);
  16101. if (camera) {
  16102. this.activeCamera = camera;
  16103. return camera;
  16104. }
  16105. return null;
  16106. };
  16107. /**
  16108. * sets the active camera of the scene using its name
  16109. * @param {string} name - the camera's name
  16110. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16111. * @see activeCamera
  16112. */
  16113. Scene.prototype.setActiveCameraByName = function (name) {
  16114. var camera = this.getCameraByName(name);
  16115. if (camera) {
  16116. this.activeCamera = camera;
  16117. return camera;
  16118. }
  16119. return null;
  16120. };
  16121. /**
  16122. * get a material using its id
  16123. * @param {string} the material's ID
  16124. * @return {BABYLON.Material|null} the material or null if none found.
  16125. */
  16126. Scene.prototype.getMaterialByID = function (id) {
  16127. for (var index = 0; index < this.materials.length; index++) {
  16128. if (this.materials[index].id === id) {
  16129. return this.materials[index];
  16130. }
  16131. }
  16132. return null;
  16133. };
  16134. /**
  16135. * get a material using its name
  16136. * @param {string} the material's name
  16137. * @return {BABYLON.Material|null} the material or null if none found.
  16138. */
  16139. Scene.prototype.getMaterialByName = function (name) {
  16140. for (var index = 0; index < this.materials.length; index++) {
  16141. if (this.materials[index].name === name) {
  16142. return this.materials[index];
  16143. }
  16144. }
  16145. return null;
  16146. };
  16147. Scene.prototype.getLensFlareSystemByName = function (name) {
  16148. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16149. if (this.lensFlareSystems[index].name === name) {
  16150. return this.lensFlareSystems[index];
  16151. }
  16152. }
  16153. return null;
  16154. };
  16155. Scene.prototype.getLensFlareSystemByID = function (id) {
  16156. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16157. if (this.lensFlareSystems[index].id === id) {
  16158. return this.lensFlareSystems[index];
  16159. }
  16160. }
  16161. return null;
  16162. };
  16163. Scene.prototype.getCameraByID = function (id) {
  16164. for (var index = 0; index < this.cameras.length; index++) {
  16165. if (this.cameras[index].id === id) {
  16166. return this.cameras[index];
  16167. }
  16168. }
  16169. return null;
  16170. };
  16171. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  16172. for (var index = 0; index < this.cameras.length; index++) {
  16173. if (this.cameras[index].uniqueId === uniqueId) {
  16174. return this.cameras[index];
  16175. }
  16176. }
  16177. return null;
  16178. };
  16179. /**
  16180. * get a camera using its name
  16181. * @param {string} the camera's name
  16182. * @return {BABYLON.Camera|null} the camera or null if none found.
  16183. */
  16184. Scene.prototype.getCameraByName = function (name) {
  16185. for (var index = 0; index < this.cameras.length; index++) {
  16186. if (this.cameras[index].name === name) {
  16187. return this.cameras[index];
  16188. }
  16189. }
  16190. return null;
  16191. };
  16192. /**
  16193. * get a bone using its id
  16194. * @param {string} the bone's id
  16195. * @return {BABYLON.Bone|null} the bone or null if not found
  16196. */
  16197. Scene.prototype.getBoneByID = function (id) {
  16198. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16199. var skeleton = this.skeletons[skeletonIndex];
  16200. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16201. if (skeleton.bones[boneIndex].id === id) {
  16202. return skeleton.bones[boneIndex];
  16203. }
  16204. }
  16205. }
  16206. return null;
  16207. };
  16208. /**
  16209. * get a bone using its id
  16210. * @param {string} the bone's name
  16211. * @return {BABYLON.Bone|null} the bone or null if not found
  16212. */
  16213. Scene.prototype.getBoneByName = function (name) {
  16214. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16215. var skeleton = this.skeletons[skeletonIndex];
  16216. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16217. if (skeleton.bones[boneIndex].name === name) {
  16218. return skeleton.bones[boneIndex];
  16219. }
  16220. }
  16221. }
  16222. return null;
  16223. };
  16224. /**
  16225. * get a light node using its name
  16226. * @param {string} the light's name
  16227. * @return {BABYLON.Light|null} the light or null if none found.
  16228. */
  16229. Scene.prototype.getLightByName = function (name) {
  16230. for (var index = 0; index < this.lights.length; index++) {
  16231. if (this.lights[index].name === name) {
  16232. return this.lights[index];
  16233. }
  16234. }
  16235. return null;
  16236. };
  16237. /**
  16238. * get a light node using its ID
  16239. * @param {string} the light's id
  16240. * @return {BABYLON.Light|null} the light or null if none found.
  16241. */
  16242. Scene.prototype.getLightByID = function (id) {
  16243. for (var index = 0; index < this.lights.length; index++) {
  16244. if (this.lights[index].id === id) {
  16245. return this.lights[index];
  16246. }
  16247. }
  16248. return null;
  16249. };
  16250. /**
  16251. * get a light node using its scene-generated unique ID
  16252. * @param {number} the light's unique id
  16253. * @return {BABYLON.Light|null} the light or null if none found.
  16254. */
  16255. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  16256. for (var index = 0; index < this.lights.length; index++) {
  16257. if (this.lights[index].uniqueId === uniqueId) {
  16258. return this.lights[index];
  16259. }
  16260. }
  16261. return null;
  16262. };
  16263. /**
  16264. * get a particle system by id
  16265. * @param id {number} the particle system id
  16266. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  16267. */
  16268. Scene.prototype.getParticleSystemByID = function (id) {
  16269. for (var index = 0; index < this.particleSystems.length; index++) {
  16270. if (this.particleSystems[index].id === id) {
  16271. return this.particleSystems[index];
  16272. }
  16273. }
  16274. return null;
  16275. };
  16276. /**
  16277. * get a geometry using its ID
  16278. * @param {string} the geometry's id
  16279. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  16280. */
  16281. Scene.prototype.getGeometryByID = function (id) {
  16282. for (var index = 0; index < this._geometries.length; index++) {
  16283. if (this._geometries[index].id === id) {
  16284. return this._geometries[index];
  16285. }
  16286. }
  16287. return null;
  16288. };
  16289. /**
  16290. * add a new geometry to this scene.
  16291. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  16292. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  16293. * @return {boolean} was the geometry added or not
  16294. */
  16295. Scene.prototype.pushGeometry = function (geometry, force) {
  16296. if (!force && this.getGeometryByID(geometry.id)) {
  16297. return false;
  16298. }
  16299. this._geometries.push(geometry);
  16300. //notify the collision coordinator
  16301. this.collisionCoordinator.onGeometryAdded(geometry);
  16302. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  16303. return true;
  16304. };
  16305. /**
  16306. * Removes an existing geometry
  16307. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  16308. * @return {boolean} was the geometry removed or not
  16309. */
  16310. Scene.prototype.removeGeometry = function (geometry) {
  16311. var index = this._geometries.indexOf(geometry);
  16312. if (index > -1) {
  16313. this._geometries.splice(index, 1);
  16314. //notify the collision coordinator
  16315. this.collisionCoordinator.onGeometryDeleted(geometry);
  16316. this.onGeometryRemovedObservable.notifyObservers(geometry);
  16317. return true;
  16318. }
  16319. return false;
  16320. };
  16321. Scene.prototype.getGeometries = function () {
  16322. return this._geometries;
  16323. };
  16324. /**
  16325. * Get the first added mesh found of a given ID
  16326. * @param {string} id - the id to search for
  16327. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16328. */
  16329. Scene.prototype.getMeshByID = function (id) {
  16330. for (var index = 0; index < this.meshes.length; index++) {
  16331. if (this.meshes[index].id === id) {
  16332. return this.meshes[index];
  16333. }
  16334. }
  16335. return null;
  16336. };
  16337. Scene.prototype.getMeshesByID = function (id) {
  16338. return this.meshes.filter(function (m) {
  16339. return m.id === id;
  16340. });
  16341. };
  16342. /**
  16343. * Get a mesh with its auto-generated unique id
  16344. * @param {number} uniqueId - the unique id to search for
  16345. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16346. */
  16347. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  16348. for (var index = 0; index < this.meshes.length; index++) {
  16349. if (this.meshes[index].uniqueId === uniqueId) {
  16350. return this.meshes[index];
  16351. }
  16352. }
  16353. return null;
  16354. };
  16355. /**
  16356. * Get a the last added mesh found of a given ID
  16357. * @param {string} id - the id to search for
  16358. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16359. */
  16360. Scene.prototype.getLastMeshByID = function (id) {
  16361. for (var index = this.meshes.length - 1; index >= 0; index--) {
  16362. if (this.meshes[index].id === id) {
  16363. return this.meshes[index];
  16364. }
  16365. }
  16366. return null;
  16367. };
  16368. /**
  16369. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  16370. * @param {string} id - the id to search for
  16371. * @return {BABYLON.Node|null} the node found or null if not found at all.
  16372. */
  16373. Scene.prototype.getLastEntryByID = function (id) {
  16374. var index;
  16375. for (index = this.meshes.length - 1; index >= 0; index--) {
  16376. if (this.meshes[index].id === id) {
  16377. return this.meshes[index];
  16378. }
  16379. }
  16380. for (index = this.cameras.length - 1; index >= 0; index--) {
  16381. if (this.cameras[index].id === id) {
  16382. return this.cameras[index];
  16383. }
  16384. }
  16385. for (index = this.lights.length - 1; index >= 0; index--) {
  16386. if (this.lights[index].id === id) {
  16387. return this.lights[index];
  16388. }
  16389. }
  16390. return null;
  16391. };
  16392. Scene.prototype.getNodeByID = function (id) {
  16393. var mesh = this.getMeshByID(id);
  16394. if (mesh) {
  16395. return mesh;
  16396. }
  16397. var light = this.getLightByID(id);
  16398. if (light) {
  16399. return light;
  16400. }
  16401. var camera = this.getCameraByID(id);
  16402. if (camera) {
  16403. return camera;
  16404. }
  16405. var bone = this.getBoneByID(id);
  16406. return bone;
  16407. };
  16408. Scene.prototype.getNodeByName = function (name) {
  16409. var mesh = this.getMeshByName(name);
  16410. if (mesh) {
  16411. return mesh;
  16412. }
  16413. var light = this.getLightByName(name);
  16414. if (light) {
  16415. return light;
  16416. }
  16417. var camera = this.getCameraByName(name);
  16418. if (camera) {
  16419. return camera;
  16420. }
  16421. var bone = this.getBoneByName(name);
  16422. return bone;
  16423. };
  16424. Scene.prototype.getMeshByName = function (name) {
  16425. for (var index = 0; index < this.meshes.length; index++) {
  16426. if (this.meshes[index].name === name) {
  16427. return this.meshes[index];
  16428. }
  16429. }
  16430. return null;
  16431. };
  16432. Scene.prototype.getSoundByName = function (name) {
  16433. var index;
  16434. if (BABYLON.AudioEngine) {
  16435. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  16436. if (this.mainSoundTrack.soundCollection[index].name === name) {
  16437. return this.mainSoundTrack.soundCollection[index];
  16438. }
  16439. }
  16440. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  16441. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  16442. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  16443. return this.soundTracks[sdIndex].soundCollection[index];
  16444. }
  16445. }
  16446. }
  16447. }
  16448. return null;
  16449. };
  16450. Scene.prototype.getLastSkeletonByID = function (id) {
  16451. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  16452. if (this.skeletons[index].id === id) {
  16453. return this.skeletons[index];
  16454. }
  16455. }
  16456. return null;
  16457. };
  16458. Scene.prototype.getSkeletonById = function (id) {
  16459. for (var index = 0; index < this.skeletons.length; index++) {
  16460. if (this.skeletons[index].id === id) {
  16461. return this.skeletons[index];
  16462. }
  16463. }
  16464. return null;
  16465. };
  16466. Scene.prototype.getSkeletonByName = function (name) {
  16467. for (var index = 0; index < this.skeletons.length; index++) {
  16468. if (this.skeletons[index].name === name) {
  16469. return this.skeletons[index];
  16470. }
  16471. }
  16472. return null;
  16473. };
  16474. Scene.prototype.isActiveMesh = function (mesh) {
  16475. return (this._activeMeshes.indexOf(mesh) !== -1);
  16476. };
  16477. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  16478. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  16479. var material = subMesh.getMaterial();
  16480. if (mesh.showSubMeshesBoundingBox) {
  16481. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  16482. }
  16483. if (material) {
  16484. // Render targets
  16485. if (material.getRenderTargetTextures) {
  16486. if (this._processedMaterials.indexOf(material) === -1) {
  16487. this._processedMaterials.push(material);
  16488. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  16489. }
  16490. }
  16491. // Dispatch
  16492. this._activeIndices.addCount(subMesh.indexCount, false);
  16493. this._renderingManager.dispatch(subMesh);
  16494. }
  16495. }
  16496. };
  16497. Scene.prototype._isInIntermediateRendering = function () {
  16498. return this._intermediateRendering;
  16499. };
  16500. Scene.prototype._evaluateActiveMeshes = function () {
  16501. this.activeCamera._activeMeshes.reset();
  16502. this._activeMeshes.reset();
  16503. this._renderingManager.reset();
  16504. this._processedMaterials.reset();
  16505. this._activeParticleSystems.reset();
  16506. this._activeSkeletons.reset();
  16507. this._softwareSkinnedMeshes.reset();
  16508. this._boundingBoxRenderer.reset();
  16509. this._edgesRenderers.reset();
  16510. // Meshes
  16511. var meshes;
  16512. var len;
  16513. if (this._selectionOctree) {
  16514. var selection = this._selectionOctree.select(this._frustumPlanes);
  16515. meshes = selection.data;
  16516. len = selection.length;
  16517. }
  16518. else {
  16519. len = this.meshes.length;
  16520. meshes = this.meshes;
  16521. }
  16522. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  16523. var mesh = meshes[meshIndex];
  16524. if (mesh.isBlocked) {
  16525. continue;
  16526. }
  16527. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  16528. if (!mesh.isReady() || !mesh.isEnabled()) {
  16529. continue;
  16530. }
  16531. mesh.computeWorldMatrix();
  16532. // Intersections
  16533. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  16534. this._meshesForIntersections.pushNoDuplicate(mesh);
  16535. }
  16536. // Switch to current LOD
  16537. var meshLOD = mesh.getLOD(this.activeCamera);
  16538. if (!meshLOD) {
  16539. continue;
  16540. }
  16541. mesh._preActivate();
  16542. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  16543. this._activeMeshes.push(mesh);
  16544. this.activeCamera._activeMeshes.push(mesh);
  16545. mesh._activate(this._renderId);
  16546. this._activeMesh(mesh, meshLOD);
  16547. }
  16548. }
  16549. // Particle systems
  16550. this._particlesDuration.beginMonitoring();
  16551. var beforeParticlesDate = BABYLON.Tools.Now;
  16552. if (this.particlesEnabled) {
  16553. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  16554. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  16555. var particleSystem = this.particleSystems[particleIndex];
  16556. if (!particleSystem.isStarted()) {
  16557. continue;
  16558. }
  16559. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  16560. this._activeParticleSystems.push(particleSystem);
  16561. particleSystem.animate();
  16562. }
  16563. }
  16564. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  16565. }
  16566. this._particlesDuration.endMonitoring(false);
  16567. };
  16568. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  16569. if (mesh.skeleton && this.skeletonsEnabled) {
  16570. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  16571. mesh.skeleton.prepare();
  16572. }
  16573. if (!mesh.computeBonesUsingShaders) {
  16574. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  16575. }
  16576. }
  16577. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  16578. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  16579. }
  16580. if (sourceMesh._edgesRenderer) {
  16581. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  16582. }
  16583. if (mesh && mesh.subMeshes) {
  16584. // Submeshes Octrees
  16585. var len;
  16586. var subMeshes;
  16587. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  16588. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  16589. len = intersections.length;
  16590. subMeshes = intersections.data;
  16591. }
  16592. else {
  16593. subMeshes = mesh.subMeshes;
  16594. len = subMeshes.length;
  16595. }
  16596. for (var subIndex = 0; subIndex < len; subIndex++) {
  16597. var subMesh = subMeshes[subIndex];
  16598. this._evaluateSubMesh(subMesh, mesh);
  16599. }
  16600. }
  16601. };
  16602. Scene.prototype.updateTransformMatrix = function (force) {
  16603. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  16604. };
  16605. Scene.prototype._renderForCamera = function (camera) {
  16606. var engine = this._engine;
  16607. var startTime = BABYLON.Tools.Now;
  16608. this.activeCamera = camera;
  16609. if (!this.activeCamera)
  16610. throw new Error("Active camera not set");
  16611. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16612. // Viewport
  16613. engine.setViewport(this.activeCamera.viewport);
  16614. // Camera
  16615. this.resetCachedMaterial();
  16616. this._renderId++;
  16617. this.updateTransformMatrix();
  16618. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  16619. // Meshes
  16620. this._evaluateActiveMeshesDuration.beginMonitoring();
  16621. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  16622. this._evaluateActiveMeshes();
  16623. this._evaluateActiveMeshesDuration.endMonitoring(false);
  16624. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  16625. // Software skinning
  16626. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  16627. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  16628. mesh.applySkeleton(mesh.skeleton);
  16629. }
  16630. // Render targets
  16631. this._renderTargetsDuration.beginMonitoring();
  16632. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16633. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  16634. this._intermediateRendering = true;
  16635. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16636. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  16637. var renderTarget = this._renderTargets.data[renderIndex];
  16638. if (renderTarget._shouldRender()) {
  16639. this._renderId++;
  16640. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  16641. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  16642. }
  16643. }
  16644. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16645. this._intermediateRendering = false;
  16646. this._renderId++;
  16647. engine.restoreDefaultFramebuffer(); // Restore back buffer
  16648. }
  16649. this._renderTargetsDuration.endMonitoring(false);
  16650. // Prepare Frame
  16651. this.postProcessManager._prepareFrame();
  16652. this._renderDuration.beginMonitoring();
  16653. // Backgrounds
  16654. var layerIndex;
  16655. var layer;
  16656. if (this.layers.length) {
  16657. engine.setDepthBuffer(false);
  16658. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16659. layer = this.layers[layerIndex];
  16660. if (layer.isBackground) {
  16661. layer.render();
  16662. }
  16663. }
  16664. engine.setDepthBuffer(true);
  16665. }
  16666. // Render
  16667. BABYLON.Tools.StartPerformanceCounter("Main render");
  16668. this._renderingManager.render(null, null, true, true);
  16669. BABYLON.Tools.EndPerformanceCounter("Main render");
  16670. // Bounding boxes
  16671. this._boundingBoxRenderer.render();
  16672. // Edges
  16673. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16674. this._edgesRenderers.data[edgesRendererIndex].render();
  16675. }
  16676. // Lens flares
  16677. if (this.lensFlaresEnabled) {
  16678. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16679. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  16680. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  16681. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  16682. lensFlareSystem.render();
  16683. }
  16684. }
  16685. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16686. }
  16687. // Foregrounds
  16688. if (this.layers.length) {
  16689. engine.setDepthBuffer(false);
  16690. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16691. layer = this.layers[layerIndex];
  16692. if (!layer.isBackground) {
  16693. layer.render();
  16694. }
  16695. }
  16696. engine.setDepthBuffer(true);
  16697. }
  16698. this._renderDuration.endMonitoring(false);
  16699. // Finalize frame
  16700. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  16701. // Update camera
  16702. this.activeCamera._updateFromScene();
  16703. // Reset some special arrays
  16704. this._renderTargets.reset();
  16705. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  16706. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16707. };
  16708. Scene.prototype._processSubCameras = function (camera) {
  16709. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  16710. this._renderForCamera(camera);
  16711. return;
  16712. }
  16713. // rig cameras
  16714. for (var index = 0; index < camera._rigCameras.length; index++) {
  16715. this._renderForCamera(camera._rigCameras[index]);
  16716. }
  16717. this.activeCamera = camera;
  16718. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  16719. // Update camera
  16720. this.activeCamera._updateFromScene();
  16721. };
  16722. Scene.prototype._checkIntersections = function () {
  16723. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  16724. var sourceMesh = this._meshesForIntersections.data[index];
  16725. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  16726. var action = sourceMesh.actionManager.actions[actionIndex];
  16727. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16728. var parameters = action.getTriggerParameter();
  16729. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  16730. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  16731. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  16732. if (areIntersecting && currentIntersectionInProgress === -1) {
  16733. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  16734. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16735. sourceMesh._intersectionsInProgress.push(otherMesh);
  16736. }
  16737. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16738. sourceMesh._intersectionsInProgress.push(otherMesh);
  16739. }
  16740. }
  16741. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  16742. //They intersected, and now they don't.
  16743. //is this trigger an exit trigger? execute an event.
  16744. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16745. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16746. }
  16747. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  16748. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16749. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  16750. }
  16751. }
  16752. }
  16753. }
  16754. }
  16755. };
  16756. Scene.prototype.render = function () {
  16757. this._lastFrameDuration.beginMonitoring();
  16758. this._particlesDuration.fetchNewFrame();
  16759. this._spritesDuration.fetchNewFrame();
  16760. this._activeParticles.fetchNewFrame();
  16761. this._renderDuration.fetchNewFrame();
  16762. this._renderTargetsDuration.fetchNewFrame();
  16763. this._evaluateActiveMeshesDuration.fetchNewFrame();
  16764. this._totalVertices.fetchNewFrame();
  16765. this._activeIndices.fetchNewFrame();
  16766. this._activeBones.fetchNewFrame();
  16767. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  16768. this._meshesForIntersections.reset();
  16769. this.resetCachedMaterial();
  16770. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  16771. // Actions
  16772. if (this.actionManager) {
  16773. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  16774. }
  16775. //Simplification Queue
  16776. if (this.simplificationQueue && !this.simplificationQueue.running) {
  16777. this.simplificationQueue.executeNext();
  16778. }
  16779. // Animations
  16780. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  16781. this._animationRatio = deltaTime * (60.0 / 1000.0);
  16782. this._animate();
  16783. // Physics
  16784. if (this._physicsEngine) {
  16785. BABYLON.Tools.StartPerformanceCounter("Physics");
  16786. this._physicsEngine._step(deltaTime / 1000.0);
  16787. BABYLON.Tools.EndPerformanceCounter("Physics");
  16788. }
  16789. // Before render
  16790. this.onBeforeRenderObservable.notifyObservers(this);
  16791. // Customs render targets
  16792. this._renderTargetsDuration.beginMonitoring();
  16793. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16794. var engine = this.getEngine();
  16795. var currentActiveCamera = this.activeCamera;
  16796. if (this.renderTargetsEnabled) {
  16797. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16798. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  16799. var renderTarget = this.customRenderTargets[customIndex];
  16800. if (renderTarget._shouldRender()) {
  16801. this._renderId++;
  16802. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  16803. if (!this.activeCamera)
  16804. throw new Error("Active camera not set");
  16805. // Viewport
  16806. engine.setViewport(this.activeCamera.viewport);
  16807. // Camera
  16808. this.updateTransformMatrix();
  16809. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  16810. }
  16811. }
  16812. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16813. this._renderId++;
  16814. }
  16815. if (this.customRenderTargets.length > 0) {
  16816. engine.restoreDefaultFramebuffer();
  16817. }
  16818. this._renderTargetsDuration.endMonitoring();
  16819. this.activeCamera = currentActiveCamera;
  16820. // Procedural textures
  16821. if (this.proceduralTexturesEnabled) {
  16822. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16823. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  16824. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  16825. if (proceduralTexture._shouldRender()) {
  16826. proceduralTexture.render();
  16827. }
  16828. }
  16829. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16830. }
  16831. // Clear
  16832. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  16833. // Shadows
  16834. if (this.shadowsEnabled) {
  16835. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  16836. var light = this.lights[lightIndex];
  16837. var shadowGenerator = light.getShadowGenerator();
  16838. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  16839. this._renderTargets.push(shadowGenerator.getShadowMap());
  16840. }
  16841. }
  16842. }
  16843. // Depth renderer
  16844. if (this._depthRenderer) {
  16845. this._renderTargets.push(this._depthRenderer.getDepthMap());
  16846. }
  16847. // RenderPipeline
  16848. this.postProcessRenderPipelineManager.update();
  16849. // Multi-cameras?
  16850. if (this.activeCameras.length > 0) {
  16851. var currentRenderId = this._renderId;
  16852. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  16853. this._renderId = currentRenderId;
  16854. if (cameraIndex > 0) {
  16855. this._engine.clear(0, false, true);
  16856. }
  16857. this._processSubCameras(this.activeCameras[cameraIndex]);
  16858. }
  16859. }
  16860. else {
  16861. if (!this.activeCamera) {
  16862. throw new Error("No camera defined");
  16863. }
  16864. this._processSubCameras(this.activeCamera);
  16865. }
  16866. // Intersection checks
  16867. this._checkIntersections();
  16868. // Update the audio listener attached to the camera
  16869. if (BABYLON.AudioEngine) {
  16870. this._updateAudioParameters();
  16871. }
  16872. // After render
  16873. if (this.afterRender) {
  16874. this.afterRender();
  16875. }
  16876. this.onAfterRenderObservable.notifyObservers(this);
  16877. // Cleaning
  16878. for (var index = 0; index < this._toBeDisposed.length; index++) {
  16879. this._toBeDisposed.data[index].dispose();
  16880. this._toBeDisposed[index] = null;
  16881. }
  16882. this._toBeDisposed.reset();
  16883. if (this.dumpNextRenderTargets) {
  16884. this.dumpNextRenderTargets = false;
  16885. }
  16886. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  16887. this._lastFrameDuration.endMonitoring();
  16888. this._totalMeshesCounter.addCount(this.meshes.length, true);
  16889. this._totalLightsCounter.addCount(this.lights.length, true);
  16890. this._totalMaterialsCounter.addCount(this.materials.length, true);
  16891. this._totalTexturesCounter.addCount(this.textures.length, true);
  16892. this._activeBones.addCount(0, true);
  16893. this._activeIndices.addCount(0, true);
  16894. this._activeParticles.addCount(0, true);
  16895. };
  16896. Scene.prototype._updateAudioParameters = function () {
  16897. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  16898. return;
  16899. }
  16900. var listeningCamera;
  16901. var audioEngine = BABYLON.Engine.audioEngine;
  16902. if (this.activeCameras.length > 0) {
  16903. listeningCamera = this.activeCameras[0];
  16904. }
  16905. else {
  16906. listeningCamera = this.activeCamera;
  16907. }
  16908. if (listeningCamera && audioEngine.canUseWebAudio) {
  16909. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  16910. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  16911. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  16912. cameraDirection.normalize();
  16913. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  16914. var i;
  16915. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16916. var sound = this.mainSoundTrack.soundCollection[i];
  16917. if (sound.useCustomAttenuation) {
  16918. sound.updateDistanceFromListener();
  16919. }
  16920. }
  16921. for (i = 0; i < this.soundTracks.length; i++) {
  16922. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16923. sound = this.soundTracks[i].soundCollection[j];
  16924. if (sound.useCustomAttenuation) {
  16925. sound.updateDistanceFromListener();
  16926. }
  16927. }
  16928. }
  16929. }
  16930. };
  16931. Object.defineProperty(Scene.prototype, "audioEnabled", {
  16932. // Audio
  16933. get: function () {
  16934. return this._audioEnabled;
  16935. },
  16936. set: function (value) {
  16937. this._audioEnabled = value;
  16938. if (BABYLON.AudioEngine) {
  16939. if (this._audioEnabled) {
  16940. this._enableAudio();
  16941. }
  16942. else {
  16943. this._disableAudio();
  16944. }
  16945. }
  16946. },
  16947. enumerable: true,
  16948. configurable: true
  16949. });
  16950. Scene.prototype._disableAudio = function () {
  16951. var i;
  16952. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16953. this.mainSoundTrack.soundCollection[i].pause();
  16954. }
  16955. for (i = 0; i < this.soundTracks.length; i++) {
  16956. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16957. this.soundTracks[i].soundCollection[j].pause();
  16958. }
  16959. }
  16960. };
  16961. Scene.prototype._enableAudio = function () {
  16962. var i;
  16963. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16964. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  16965. this.mainSoundTrack.soundCollection[i].play();
  16966. }
  16967. }
  16968. for (i = 0; i < this.soundTracks.length; i++) {
  16969. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16970. if (this.soundTracks[i].soundCollection[j].isPaused) {
  16971. this.soundTracks[i].soundCollection[j].play();
  16972. }
  16973. }
  16974. }
  16975. };
  16976. Object.defineProperty(Scene.prototype, "headphone", {
  16977. get: function () {
  16978. return this._headphone;
  16979. },
  16980. set: function (value) {
  16981. this._headphone = value;
  16982. if (BABYLON.AudioEngine) {
  16983. if (this._headphone) {
  16984. this._switchAudioModeForHeadphones();
  16985. }
  16986. else {
  16987. this._switchAudioModeForNormalSpeakers();
  16988. }
  16989. }
  16990. },
  16991. enumerable: true,
  16992. configurable: true
  16993. });
  16994. Scene.prototype._switchAudioModeForHeadphones = function () {
  16995. this.mainSoundTrack.switchPanningModelToHRTF();
  16996. for (var i = 0; i < this.soundTracks.length; i++) {
  16997. this.soundTracks[i].switchPanningModelToHRTF();
  16998. }
  16999. };
  17000. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17001. this.mainSoundTrack.switchPanningModelToEqualPower();
  17002. for (var i = 0; i < this.soundTracks.length; i++) {
  17003. this.soundTracks[i].switchPanningModelToEqualPower();
  17004. }
  17005. };
  17006. Scene.prototype.enableDepthRenderer = function () {
  17007. if (this._depthRenderer) {
  17008. return this._depthRenderer;
  17009. }
  17010. this._depthRenderer = new BABYLON.DepthRenderer(this);
  17011. return this._depthRenderer;
  17012. };
  17013. Scene.prototype.disableDepthRenderer = function () {
  17014. if (!this._depthRenderer) {
  17015. return;
  17016. }
  17017. this._depthRenderer.dispose();
  17018. this._depthRenderer = null;
  17019. };
  17020. Scene.prototype.freezeMaterials = function () {
  17021. for (var i = 0; i < this.materials.length; i++) {
  17022. this.materials[i].freeze();
  17023. }
  17024. };
  17025. Scene.prototype.unfreezeMaterials = function () {
  17026. for (var i = 0; i < this.materials.length; i++) {
  17027. this.materials[i].unfreeze();
  17028. }
  17029. };
  17030. Scene.prototype.dispose = function () {
  17031. this.beforeRender = null;
  17032. this.afterRender = null;
  17033. this.skeletons = [];
  17034. this._boundingBoxRenderer.dispose();
  17035. if (this._depthRenderer) {
  17036. this._depthRenderer.dispose();
  17037. }
  17038. // Debug layer
  17039. if (this._debugLayer) {
  17040. this._debugLayer.hide();
  17041. }
  17042. // Events
  17043. this.onDisposeObservable.notifyObservers(this);
  17044. this.onDisposeObservable.clear();
  17045. this.onBeforeRenderObservable.clear();
  17046. this.onAfterRenderObservable.clear();
  17047. this.detachControl();
  17048. // Release sounds & sounds tracks
  17049. if (BABYLON.AudioEngine) {
  17050. this.disposeSounds();
  17051. }
  17052. // Detach cameras
  17053. var canvas = this._engine.getRenderingCanvas();
  17054. var index;
  17055. for (index = 0; index < this.cameras.length; index++) {
  17056. this.cameras[index].detachControl(canvas);
  17057. }
  17058. // Release lights
  17059. while (this.lights.length) {
  17060. this.lights[0].dispose();
  17061. }
  17062. // Release meshes
  17063. while (this.meshes.length) {
  17064. this.meshes[0].dispose(true);
  17065. }
  17066. // Release cameras
  17067. while (this.cameras.length) {
  17068. this.cameras[0].dispose();
  17069. }
  17070. // Release materials
  17071. while (this.materials.length) {
  17072. this.materials[0].dispose();
  17073. }
  17074. // Release particles
  17075. while (this.particleSystems.length) {
  17076. this.particleSystems[0].dispose();
  17077. }
  17078. // Release sprites
  17079. while (this.spriteManagers.length) {
  17080. this.spriteManagers[0].dispose();
  17081. }
  17082. // Release layers
  17083. while (this.layers.length) {
  17084. this.layers[0].dispose();
  17085. }
  17086. // Release textures
  17087. while (this.textures.length) {
  17088. this.textures[0].dispose();
  17089. }
  17090. // Post-processes
  17091. this.postProcessManager.dispose();
  17092. // Physics
  17093. if (this._physicsEngine) {
  17094. this.disablePhysicsEngine();
  17095. }
  17096. // Remove from engine
  17097. index = this._engine.scenes.indexOf(this);
  17098. if (index > -1) {
  17099. this._engine.scenes.splice(index, 1);
  17100. }
  17101. this._engine.wipeCaches();
  17102. };
  17103. // Release sounds & sounds tracks
  17104. Scene.prototype.disposeSounds = function () {
  17105. this.mainSoundTrack.dispose();
  17106. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  17107. this.soundTracks[scIndex].dispose();
  17108. }
  17109. };
  17110. // Octrees
  17111. Scene.prototype.getWorldExtends = function () {
  17112. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17113. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17114. for (var index = 0; index < this.meshes.length; index++) {
  17115. var mesh = this.meshes[index];
  17116. mesh.computeWorldMatrix(true);
  17117. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  17118. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  17119. BABYLON.Tools.CheckExtends(minBox, min, max);
  17120. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17121. }
  17122. return {
  17123. min: min,
  17124. max: max
  17125. };
  17126. };
  17127. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  17128. if (maxCapacity === void 0) { maxCapacity = 64; }
  17129. if (maxDepth === void 0) { maxDepth = 2; }
  17130. if (!this._selectionOctree) {
  17131. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  17132. }
  17133. var worldExtends = this.getWorldExtends();
  17134. // Update octree
  17135. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  17136. return this._selectionOctree;
  17137. };
  17138. // Picking
  17139. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  17140. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  17141. var engine = this._engine;
  17142. if (!camera) {
  17143. if (!this.activeCamera)
  17144. throw new Error("Active camera not set");
  17145. camera = this.activeCamera;
  17146. }
  17147. var cameraViewport = camera.viewport;
  17148. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17149. // Moving coordinates to local viewport world
  17150. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17151. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17152. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  17153. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  17154. };
  17155. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  17156. var engine = this._engine;
  17157. if (!camera) {
  17158. if (!this.activeCamera)
  17159. throw new Error("Active camera not set");
  17160. camera = this.activeCamera;
  17161. }
  17162. var cameraViewport = camera.viewport;
  17163. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17164. var identity = BABYLON.Matrix.Identity();
  17165. // Moving coordinates to local viewport world
  17166. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17167. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17168. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  17169. };
  17170. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  17171. var pickingInfo = null;
  17172. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  17173. var mesh = this.meshes[meshIndex];
  17174. if (predicate) {
  17175. if (!predicate(mesh)) {
  17176. continue;
  17177. }
  17178. }
  17179. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  17180. continue;
  17181. }
  17182. var world = mesh.getWorldMatrix();
  17183. var ray = rayFunction(world);
  17184. var result = mesh.intersects(ray, fastCheck);
  17185. if (!result || !result.hit)
  17186. continue;
  17187. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17188. continue;
  17189. pickingInfo = result;
  17190. if (fastCheck) {
  17191. break;
  17192. }
  17193. }
  17194. return pickingInfo || new BABYLON.PickingInfo();
  17195. };
  17196. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  17197. var pickingInfo = null;
  17198. camera = camera || this.activeCamera;
  17199. if (this.spriteManagers.length > 0) {
  17200. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  17201. var spriteManager = this.spriteManagers[spriteIndex];
  17202. if (!spriteManager.isPickable) {
  17203. continue;
  17204. }
  17205. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  17206. if (!result || !result.hit)
  17207. continue;
  17208. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17209. continue;
  17210. pickingInfo = result;
  17211. if (fastCheck) {
  17212. break;
  17213. }
  17214. }
  17215. }
  17216. return pickingInfo || new BABYLON.PickingInfo();
  17217. };
  17218. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  17219. var _this = this;
  17220. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17221. /// <param name="x">X position on screen</param>
  17222. /// <param name="y">Y position on screen</param>
  17223. /// <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>
  17224. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17225. /// <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>
  17226. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  17227. };
  17228. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  17229. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17230. /// <param name="x">X position on screen</param>
  17231. /// <param name="y">Y position on screen</param>
  17232. /// <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>
  17233. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17234. /// <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>
  17235. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  17236. };
  17237. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  17238. var _this = this;
  17239. return this._internalPick(function (world) {
  17240. if (!_this._pickWithRayInverseMatrix) {
  17241. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  17242. }
  17243. world.invertToRef(_this._pickWithRayInverseMatrix);
  17244. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  17245. }, predicate, fastCheck);
  17246. };
  17247. Scene.prototype.setPointerOverMesh = function (mesh) {
  17248. if (this._pointerOverMesh === mesh) {
  17249. return;
  17250. }
  17251. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17252. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17253. }
  17254. this._pointerOverMesh = mesh;
  17255. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17256. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17257. }
  17258. };
  17259. Scene.prototype.getPointerOverMesh = function () {
  17260. return this._pointerOverMesh;
  17261. };
  17262. Scene.prototype.setPointerOverSprite = function (sprite) {
  17263. if (this._pointerOverSprite === sprite) {
  17264. return;
  17265. }
  17266. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17267. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17268. }
  17269. this._pointerOverSprite = sprite;
  17270. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17271. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17272. }
  17273. };
  17274. Scene.prototype.getPointerOverSprite = function () {
  17275. return this._pointerOverSprite;
  17276. };
  17277. // Physics
  17278. Scene.prototype.getPhysicsEngine = function () {
  17279. return this._physicsEngine;
  17280. };
  17281. /**
  17282. * Enables physics to the current scene
  17283. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  17284. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  17285. * @return {boolean} was the physics engine initialized
  17286. */
  17287. Scene.prototype.enablePhysics = function (gravity, plugin) {
  17288. if (this._physicsEngine) {
  17289. return true;
  17290. }
  17291. try {
  17292. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  17293. return true;
  17294. }
  17295. catch (e) {
  17296. BABYLON.Tools.Error(e.message);
  17297. return false;
  17298. }
  17299. };
  17300. Scene.prototype.disablePhysicsEngine = function () {
  17301. if (!this._physicsEngine) {
  17302. return;
  17303. }
  17304. this._physicsEngine.dispose();
  17305. this._physicsEngine = undefined;
  17306. };
  17307. Scene.prototype.isPhysicsEnabled = function () {
  17308. return this._physicsEngine !== undefined;
  17309. };
  17310. /**
  17311. *
  17312. * Sets the gravity of the physics engine (and NOT of the scene)
  17313. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  17314. */
  17315. Scene.prototype.setGravity = function (gravity) {
  17316. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  17317. if (!this._physicsEngine) {
  17318. return;
  17319. }
  17320. this._physicsEngine.setGravity(gravity);
  17321. };
  17322. /**
  17323. * Legacy support, using the new API
  17324. * @Deprecated
  17325. */
  17326. Scene.prototype.createCompoundImpostor = function (parts, options) {
  17327. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  17328. if (parts.parts) {
  17329. options = parts;
  17330. parts = parts.parts;
  17331. }
  17332. var mainMesh = parts[0].mesh;
  17333. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  17334. for (var index = 1; index < parts.length; index++) {
  17335. var mesh = parts[index].mesh;
  17336. if (mesh.parent !== mainMesh) {
  17337. mesh.position = mesh.position.subtract(mainMesh.position);
  17338. mesh.parent = mainMesh;
  17339. }
  17340. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  17341. }
  17342. mainMesh.physicsImpostor.forceUpdate();
  17343. };
  17344. Scene.prototype.deleteCompoundImpostor = function (compound) {
  17345. var mesh = compound.parts[0].mesh;
  17346. mesh.physicsImpostor.dispose();
  17347. mesh.physicsImpostor = null;
  17348. };
  17349. // Misc.
  17350. Scene.prototype.createDefaultCameraOrLight = function () {
  17351. // Light
  17352. if (this.lights.length === 0) {
  17353. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  17354. }
  17355. // Camera
  17356. if (!this.activeCamera) {
  17357. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  17358. // Compute position
  17359. var worldExtends = this.getWorldExtends();
  17360. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  17361. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  17362. camera.setTarget(worldCenter);
  17363. this.activeCamera = camera;
  17364. }
  17365. };
  17366. // Tags
  17367. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  17368. if (tagsQuery === undefined) {
  17369. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  17370. return list;
  17371. }
  17372. var listByTags = [];
  17373. forEach = forEach || (function (item) { return; });
  17374. for (var i in list) {
  17375. var item = list[i];
  17376. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  17377. listByTags.push(item);
  17378. forEach(item);
  17379. }
  17380. }
  17381. return listByTags;
  17382. };
  17383. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  17384. return this._getByTags(this.meshes, tagsQuery, forEach);
  17385. };
  17386. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  17387. return this._getByTags(this.cameras, tagsQuery, forEach);
  17388. };
  17389. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  17390. return this._getByTags(this.lights, tagsQuery, forEach);
  17391. };
  17392. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  17393. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  17394. };
  17395. // Statics
  17396. Scene._FOGMODE_NONE = 0;
  17397. Scene._FOGMODE_EXP = 1;
  17398. Scene._FOGMODE_EXP2 = 2;
  17399. Scene._FOGMODE_LINEAR = 3;
  17400. Scene.MinDeltaTime = 1.0;
  17401. Scene.MaxDeltaTime = 1000.0;
  17402. return Scene;
  17403. }());
  17404. BABYLON.Scene = Scene;
  17405. })(BABYLON || (BABYLON = {}));
  17406. var BABYLON;
  17407. (function (BABYLON) {
  17408. var Buffer = (function () {
  17409. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  17410. if (engine instanceof BABYLON.Mesh) {
  17411. this._engine = engine.getScene().getEngine();
  17412. }
  17413. else {
  17414. this._engine = engine;
  17415. }
  17416. this._updatable = updatable;
  17417. this._data = data;
  17418. this._strideSize = stride;
  17419. if (!postponeInternalCreation) {
  17420. this.create();
  17421. }
  17422. this._instanced = instanced;
  17423. }
  17424. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  17425. // a lot of these parameters are ignored as they are overriden by the buffer
  17426. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  17427. };
  17428. // Properties
  17429. Buffer.prototype.isUpdatable = function () {
  17430. return this._updatable;
  17431. };
  17432. Buffer.prototype.getData = function () {
  17433. return this._data;
  17434. };
  17435. Buffer.prototype.getBuffer = function () {
  17436. return this._buffer;
  17437. };
  17438. Buffer.prototype.getStrideSize = function () {
  17439. return this._strideSize;
  17440. };
  17441. Buffer.prototype.getIsInstanced = function () {
  17442. return this._instanced;
  17443. };
  17444. // Methods
  17445. Buffer.prototype.create = function (data) {
  17446. if (!data && this._buffer) {
  17447. return; // nothing to do
  17448. }
  17449. data = data || this._data;
  17450. if (!this._buffer) {
  17451. if (this._updatable) {
  17452. this._buffer = this._engine.createDynamicVertexBuffer(data);
  17453. this._data = data;
  17454. }
  17455. else {
  17456. this._buffer = this._engine.createVertexBuffer(data);
  17457. }
  17458. }
  17459. else if (this._updatable) {
  17460. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  17461. this._data = data;
  17462. }
  17463. };
  17464. Buffer.prototype.update = function (data) {
  17465. this.create(data);
  17466. };
  17467. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  17468. if (!this._buffer) {
  17469. return;
  17470. }
  17471. if (this._updatable) {
  17472. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  17473. this._data = null;
  17474. }
  17475. };
  17476. Buffer.prototype.dispose = function () {
  17477. if (!this._buffer) {
  17478. return;
  17479. }
  17480. if (this._engine._releaseBuffer(this._buffer)) {
  17481. this._buffer = null;
  17482. }
  17483. };
  17484. return Buffer;
  17485. }());
  17486. BABYLON.Buffer = Buffer;
  17487. })(BABYLON || (BABYLON = {}));
  17488. var BABYLON;
  17489. (function (BABYLON) {
  17490. var VertexBuffer = (function () {
  17491. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  17492. if (!stride) {
  17493. // Deduce stride from kind
  17494. switch (kind) {
  17495. case VertexBuffer.PositionKind:
  17496. stride = 3;
  17497. break;
  17498. case VertexBuffer.NormalKind:
  17499. stride = 3;
  17500. break;
  17501. case VertexBuffer.UVKind:
  17502. case VertexBuffer.UV2Kind:
  17503. case VertexBuffer.UV3Kind:
  17504. case VertexBuffer.UV4Kind:
  17505. case VertexBuffer.UV5Kind:
  17506. case VertexBuffer.UV6Kind:
  17507. stride = 2;
  17508. break;
  17509. case VertexBuffer.ColorKind:
  17510. stride = 4;
  17511. break;
  17512. case VertexBuffer.MatricesIndicesKind:
  17513. case VertexBuffer.MatricesIndicesExtraKind:
  17514. stride = 4;
  17515. break;
  17516. case VertexBuffer.MatricesWeightsKind:
  17517. case VertexBuffer.MatricesWeightsExtraKind:
  17518. stride = 4;
  17519. break;
  17520. }
  17521. }
  17522. if (data instanceof BABYLON.Buffer) {
  17523. if (!stride) {
  17524. stride = data.getStrideSize();
  17525. }
  17526. this._buffer = data;
  17527. this._ownsBuffer = false;
  17528. }
  17529. else {
  17530. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  17531. this._ownsBuffer = true;
  17532. }
  17533. this._stride = stride;
  17534. this._offset = offset ? offset : 0;
  17535. this._size = size ? size : stride;
  17536. this._kind = kind;
  17537. }
  17538. VertexBuffer.prototype.getKind = function () {
  17539. return this._kind;
  17540. };
  17541. // Properties
  17542. VertexBuffer.prototype.isUpdatable = function () {
  17543. return this._buffer.isUpdatable();
  17544. };
  17545. VertexBuffer.prototype.getData = function () {
  17546. return this._buffer.getData();
  17547. };
  17548. VertexBuffer.prototype.getBuffer = function () {
  17549. return this._buffer.getBuffer();
  17550. };
  17551. VertexBuffer.prototype.getStrideSize = function () {
  17552. return this._stride;
  17553. };
  17554. VertexBuffer.prototype.getOffset = function () {
  17555. return this._offset;
  17556. };
  17557. VertexBuffer.prototype.getSize = function () {
  17558. return this._size;
  17559. };
  17560. VertexBuffer.prototype.getIsInstanced = function () {
  17561. return this._buffer.getIsInstanced();
  17562. };
  17563. // Methods
  17564. VertexBuffer.prototype.create = function (data) {
  17565. return this._buffer.create(data);
  17566. };
  17567. VertexBuffer.prototype.update = function (data) {
  17568. return this._buffer.update(data);
  17569. };
  17570. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  17571. return this._buffer.updateDirectly(data, offset);
  17572. };
  17573. VertexBuffer.prototype.dispose = function () {
  17574. if (this._ownsBuffer) {
  17575. this._buffer.dispose();
  17576. }
  17577. };
  17578. Object.defineProperty(VertexBuffer, "PositionKind", {
  17579. get: function () {
  17580. return VertexBuffer._PositionKind;
  17581. },
  17582. enumerable: true,
  17583. configurable: true
  17584. });
  17585. Object.defineProperty(VertexBuffer, "NormalKind", {
  17586. get: function () {
  17587. return VertexBuffer._NormalKind;
  17588. },
  17589. enumerable: true,
  17590. configurable: true
  17591. });
  17592. Object.defineProperty(VertexBuffer, "UVKind", {
  17593. get: function () {
  17594. return VertexBuffer._UVKind;
  17595. },
  17596. enumerable: true,
  17597. configurable: true
  17598. });
  17599. Object.defineProperty(VertexBuffer, "UV2Kind", {
  17600. get: function () {
  17601. return VertexBuffer._UV2Kind;
  17602. },
  17603. enumerable: true,
  17604. configurable: true
  17605. });
  17606. Object.defineProperty(VertexBuffer, "UV3Kind", {
  17607. get: function () {
  17608. return VertexBuffer._UV3Kind;
  17609. },
  17610. enumerable: true,
  17611. configurable: true
  17612. });
  17613. Object.defineProperty(VertexBuffer, "UV4Kind", {
  17614. get: function () {
  17615. return VertexBuffer._UV4Kind;
  17616. },
  17617. enumerable: true,
  17618. configurable: true
  17619. });
  17620. Object.defineProperty(VertexBuffer, "UV5Kind", {
  17621. get: function () {
  17622. return VertexBuffer._UV5Kind;
  17623. },
  17624. enumerable: true,
  17625. configurable: true
  17626. });
  17627. Object.defineProperty(VertexBuffer, "UV6Kind", {
  17628. get: function () {
  17629. return VertexBuffer._UV6Kind;
  17630. },
  17631. enumerable: true,
  17632. configurable: true
  17633. });
  17634. Object.defineProperty(VertexBuffer, "ColorKind", {
  17635. get: function () {
  17636. return VertexBuffer._ColorKind;
  17637. },
  17638. enumerable: true,
  17639. configurable: true
  17640. });
  17641. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  17642. get: function () {
  17643. return VertexBuffer._MatricesIndicesKind;
  17644. },
  17645. enumerable: true,
  17646. configurable: true
  17647. });
  17648. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  17649. get: function () {
  17650. return VertexBuffer._MatricesWeightsKind;
  17651. },
  17652. enumerable: true,
  17653. configurable: true
  17654. });
  17655. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  17656. get: function () {
  17657. return VertexBuffer._MatricesIndicesExtraKind;
  17658. },
  17659. enumerable: true,
  17660. configurable: true
  17661. });
  17662. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  17663. get: function () {
  17664. return VertexBuffer._MatricesWeightsExtraKind;
  17665. },
  17666. enumerable: true,
  17667. configurable: true
  17668. });
  17669. // Enums
  17670. VertexBuffer._PositionKind = "position";
  17671. VertexBuffer._NormalKind = "normal";
  17672. VertexBuffer._UVKind = "uv";
  17673. VertexBuffer._UV2Kind = "uv2";
  17674. VertexBuffer._UV3Kind = "uv3";
  17675. VertexBuffer._UV4Kind = "uv4";
  17676. VertexBuffer._UV5Kind = "uv5";
  17677. VertexBuffer._UV6Kind = "uv6";
  17678. VertexBuffer._ColorKind = "color";
  17679. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  17680. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  17681. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  17682. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  17683. return VertexBuffer;
  17684. }());
  17685. BABYLON.VertexBuffer = VertexBuffer;
  17686. })(BABYLON || (BABYLON = {}));
  17687. var BABYLON;
  17688. (function (BABYLON) {
  17689. /**
  17690. * Creates an instance based on a source mesh.
  17691. */
  17692. var InstancedMesh = (function (_super) {
  17693. __extends(InstancedMesh, _super);
  17694. function InstancedMesh(name, source) {
  17695. _super.call(this, name, source.getScene());
  17696. source.instances.push(this);
  17697. this._sourceMesh = source;
  17698. this.position.copyFrom(source.position);
  17699. this.rotation.copyFrom(source.rotation);
  17700. this.scaling.copyFrom(source.scaling);
  17701. if (source.rotationQuaternion) {
  17702. this.rotationQuaternion = source.rotationQuaternion.clone();
  17703. }
  17704. this.infiniteDistance = source.infiniteDistance;
  17705. this.setPivotMatrix(source.getPivotMatrix());
  17706. this.refreshBoundingInfo();
  17707. this._syncSubMeshes();
  17708. }
  17709. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  17710. // Methods
  17711. get: function () {
  17712. return this._sourceMesh.receiveShadows;
  17713. },
  17714. enumerable: true,
  17715. configurable: true
  17716. });
  17717. Object.defineProperty(InstancedMesh.prototype, "material", {
  17718. get: function () {
  17719. return this._sourceMesh.material;
  17720. },
  17721. enumerable: true,
  17722. configurable: true
  17723. });
  17724. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  17725. get: function () {
  17726. return this._sourceMesh.visibility;
  17727. },
  17728. enumerable: true,
  17729. configurable: true
  17730. });
  17731. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  17732. get: function () {
  17733. return this._sourceMesh.skeleton;
  17734. },
  17735. enumerable: true,
  17736. configurable: true
  17737. });
  17738. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  17739. get: function () {
  17740. return this._sourceMesh.renderingGroupId;
  17741. },
  17742. enumerable: true,
  17743. configurable: true
  17744. });
  17745. InstancedMesh.prototype.getTotalVertices = function () {
  17746. return this._sourceMesh.getTotalVertices();
  17747. };
  17748. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  17749. get: function () {
  17750. return this._sourceMesh;
  17751. },
  17752. enumerable: true,
  17753. configurable: true
  17754. });
  17755. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  17756. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  17757. };
  17758. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  17759. return this._sourceMesh.isVerticesDataPresent(kind);
  17760. };
  17761. InstancedMesh.prototype.getIndices = function () {
  17762. return this._sourceMesh.getIndices();
  17763. };
  17764. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  17765. get: function () {
  17766. return this._sourceMesh._positions;
  17767. },
  17768. enumerable: true,
  17769. configurable: true
  17770. });
  17771. InstancedMesh.prototype.refreshBoundingInfo = function () {
  17772. var meshBB = this._sourceMesh.getBoundingInfo();
  17773. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  17774. this._updateBoundingInfo();
  17775. };
  17776. InstancedMesh.prototype._preActivate = function () {
  17777. if (this._currentLOD) {
  17778. this._currentLOD._preActivate();
  17779. }
  17780. };
  17781. InstancedMesh.prototype._activate = function (renderId) {
  17782. if (this._currentLOD) {
  17783. this._currentLOD._registerInstanceForRenderId(this, renderId);
  17784. }
  17785. };
  17786. InstancedMesh.prototype.getLOD = function (camera) {
  17787. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  17788. if (this._currentLOD === this.sourceMesh) {
  17789. return this;
  17790. }
  17791. return this._currentLOD;
  17792. };
  17793. InstancedMesh.prototype._syncSubMeshes = function () {
  17794. this.releaseSubMeshes();
  17795. if (this._sourceMesh.subMeshes) {
  17796. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  17797. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  17798. }
  17799. }
  17800. };
  17801. InstancedMesh.prototype._generatePointsArray = function () {
  17802. return this._sourceMesh._generatePointsArray();
  17803. };
  17804. // Clone
  17805. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17806. var result = this._sourceMesh.createInstance(name);
  17807. // Deep copy
  17808. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  17809. // Bounding info
  17810. this.refreshBoundingInfo();
  17811. // Parent
  17812. if (newParent) {
  17813. result.parent = newParent;
  17814. }
  17815. if (!doNotCloneChildren) {
  17816. // Children
  17817. for (var index = 0; index < this.getScene().meshes.length; index++) {
  17818. var mesh = this.getScene().meshes[index];
  17819. if (mesh.parent === this) {
  17820. mesh.clone(mesh.name, result);
  17821. }
  17822. }
  17823. }
  17824. result.computeWorldMatrix(true);
  17825. return result;
  17826. };
  17827. // Dispoe
  17828. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  17829. // Remove from mesh
  17830. var index = this._sourceMesh.instances.indexOf(this);
  17831. this._sourceMesh.instances.splice(index, 1);
  17832. _super.prototype.dispose.call(this, doNotRecurse);
  17833. };
  17834. return InstancedMesh;
  17835. }(BABYLON.AbstractMesh));
  17836. BABYLON.InstancedMesh = InstancedMesh;
  17837. })(BABYLON || (BABYLON = {}));
  17838. var BABYLON;
  17839. (function (BABYLON) {
  17840. var _InstancesBatch = (function () {
  17841. function _InstancesBatch() {
  17842. this.mustReturn = false;
  17843. this.visibleInstances = new Array();
  17844. this.renderSelf = new Array();
  17845. }
  17846. return _InstancesBatch;
  17847. }());
  17848. BABYLON._InstancesBatch = _InstancesBatch;
  17849. var Mesh = (function (_super) {
  17850. __extends(Mesh, _super);
  17851. /**
  17852. * @constructor
  17853. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  17854. * @param {Scene} scene The scene to add this mesh to.
  17855. * @param {Node} parent The parent of this mesh, if it has one
  17856. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  17857. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  17858. * When false, achieved by calling a clone(), also passing False.
  17859. * This will make creation of children, recursive.
  17860. */
  17861. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  17862. if (parent === void 0) { parent = null; }
  17863. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  17864. _super.call(this, name, scene);
  17865. // Events
  17866. /**
  17867. * An event triggered before rendering the mesh
  17868. * @type {BABYLON.Observable}
  17869. */
  17870. this.onBeforeRenderObservable = new BABYLON.Observable();
  17871. /**
  17872. * An event triggered after rendering the mesh
  17873. * @type {BABYLON.Observable}
  17874. */
  17875. this.onAfterRenderObservable = new BABYLON.Observable();
  17876. /**
  17877. * An event triggered before drawing the mesh
  17878. * @type {BABYLON.Observable}
  17879. */
  17880. this.onBeforeDrawObservable = new BABYLON.Observable();
  17881. // Members
  17882. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17883. this.instances = new Array();
  17884. this._LODLevels = new Array();
  17885. this._visibleInstances = {};
  17886. this._renderIdForInstances = new Array();
  17887. this._batchCache = new _InstancesBatch();
  17888. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  17889. this._sideOrientation = Mesh._DEFAULTSIDE;
  17890. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  17891. if (source) {
  17892. // Geometry
  17893. if (source._geometry) {
  17894. source._geometry.applyToMesh(this);
  17895. }
  17896. // Deep copy
  17897. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  17898. // Pivot
  17899. this.setPivotMatrix(source.getPivotMatrix());
  17900. this.id = name + "." + source.id;
  17901. // Material
  17902. this.material = source.material;
  17903. var index;
  17904. if (!doNotCloneChildren) {
  17905. // Children
  17906. for (index = 0; index < scene.meshes.length; index++) {
  17907. var mesh = scene.meshes[index];
  17908. if (mesh.parent === source) {
  17909. // doNotCloneChildren is always going to be False
  17910. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  17911. }
  17912. }
  17913. }
  17914. // Physics clone
  17915. var physicsEngine = this.getScene().getPhysicsEngine();
  17916. if (clonePhysicsImpostor && physicsEngine) {
  17917. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  17918. if (impostor) {
  17919. this.physicsImpostor = impostor.clone(this);
  17920. }
  17921. }
  17922. // Particles
  17923. for (index = 0; index < scene.particleSystems.length; index++) {
  17924. var system = scene.particleSystems[index];
  17925. if (system.emitter === source) {
  17926. system.clone(system.name, this);
  17927. }
  17928. }
  17929. this.computeWorldMatrix(true);
  17930. }
  17931. // Parent
  17932. if (parent !== null) {
  17933. this.parent = parent;
  17934. }
  17935. }
  17936. Object.defineProperty(Mesh, "FRONTSIDE", {
  17937. /**
  17938. * Mesh side orientation : usually the external or front surface
  17939. */
  17940. get: function () {
  17941. return Mesh._FRONTSIDE;
  17942. },
  17943. enumerable: true,
  17944. configurable: true
  17945. });
  17946. Object.defineProperty(Mesh, "BACKSIDE", {
  17947. /**
  17948. * Mesh side orientation : usually the internal or back surface
  17949. */
  17950. get: function () {
  17951. return Mesh._BACKSIDE;
  17952. },
  17953. enumerable: true,
  17954. configurable: true
  17955. });
  17956. Object.defineProperty(Mesh, "DOUBLESIDE", {
  17957. /**
  17958. * Mesh side orientation : both internal and external or front and back surfaces
  17959. */
  17960. get: function () {
  17961. return Mesh._DOUBLESIDE;
  17962. },
  17963. enumerable: true,
  17964. configurable: true
  17965. });
  17966. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  17967. /**
  17968. * Mesh side orientation : by default, `FRONTSIDE`
  17969. */
  17970. get: function () {
  17971. return Mesh._DEFAULTSIDE;
  17972. },
  17973. enumerable: true,
  17974. configurable: true
  17975. });
  17976. Object.defineProperty(Mesh, "NO_CAP", {
  17977. /**
  17978. * Mesh cap setting : no cap
  17979. */
  17980. get: function () {
  17981. return Mesh._NO_CAP;
  17982. },
  17983. enumerable: true,
  17984. configurable: true
  17985. });
  17986. Object.defineProperty(Mesh, "CAP_START", {
  17987. /**
  17988. * Mesh cap setting : one cap at the beginning of the mesh
  17989. */
  17990. get: function () {
  17991. return Mesh._CAP_START;
  17992. },
  17993. enumerable: true,
  17994. configurable: true
  17995. });
  17996. Object.defineProperty(Mesh, "CAP_END", {
  17997. /**
  17998. * Mesh cap setting : one cap at the end of the mesh
  17999. */
  18000. get: function () {
  18001. return Mesh._CAP_END;
  18002. },
  18003. enumerable: true,
  18004. configurable: true
  18005. });
  18006. Object.defineProperty(Mesh, "CAP_ALL", {
  18007. /**
  18008. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  18009. */
  18010. get: function () {
  18011. return Mesh._CAP_ALL;
  18012. },
  18013. enumerable: true,
  18014. configurable: true
  18015. });
  18016. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  18017. set: function (callback) {
  18018. if (this._onBeforeDrawObserver) {
  18019. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  18020. }
  18021. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  18022. },
  18023. enumerable: true,
  18024. configurable: true
  18025. });
  18026. // Methods
  18027. /**
  18028. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18029. */
  18030. Mesh.prototype.toString = function (fullDetails) {
  18031. var ret = _super.prototype.toString.call(this, fullDetails);
  18032. ret += ", n vertices: " + this.getTotalVertices();
  18033. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  18034. if (this.animations) {
  18035. for (var i = 0; i < this.animations.length; i++) {
  18036. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18037. }
  18038. }
  18039. if (fullDetails) {
  18040. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  18041. }
  18042. return ret;
  18043. };
  18044. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  18045. get: function () {
  18046. return this._LODLevels.length > 0;
  18047. },
  18048. enumerable: true,
  18049. configurable: true
  18050. });
  18051. Mesh.prototype._sortLODLevels = function () {
  18052. this._LODLevels.sort(function (a, b) {
  18053. if (a.distance < b.distance) {
  18054. return 1;
  18055. }
  18056. if (a.distance > b.distance) {
  18057. return -1;
  18058. }
  18059. return 0;
  18060. });
  18061. };
  18062. /**
  18063. * Add a mesh as LOD level triggered at the given distance.
  18064. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18065. * @param {number} distance The distance from the center of the object to show this level
  18066. * @param {Mesh} mesh The mesh to be added as LOD level
  18067. * @return {Mesh} This mesh (for chaining)
  18068. */
  18069. Mesh.prototype.addLODLevel = function (distance, mesh) {
  18070. if (mesh && mesh._masterMesh) {
  18071. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  18072. return this;
  18073. }
  18074. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  18075. this._LODLevels.push(level);
  18076. if (mesh) {
  18077. mesh._masterMesh = this;
  18078. }
  18079. this._sortLODLevels();
  18080. return this;
  18081. };
  18082. /**
  18083. * Returns the LOD level mesh at the passed distance or null if not found.
  18084. * It is related to the method `addLODLevel(distance, mesh)`.
  18085. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18086. */
  18087. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  18088. for (var index = 0; index < this._LODLevels.length; index++) {
  18089. var level = this._LODLevels[index];
  18090. if (level.distance === distance) {
  18091. return level.mesh;
  18092. }
  18093. }
  18094. return null;
  18095. };
  18096. /**
  18097. * Remove a mesh from the LOD array
  18098. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18099. * @param {Mesh} mesh The mesh to be removed.
  18100. * @return {Mesh} This mesh (for chaining)
  18101. */
  18102. Mesh.prototype.removeLODLevel = function (mesh) {
  18103. for (var index = 0; index < this._LODLevels.length; index++) {
  18104. if (this._LODLevels[index].mesh === mesh) {
  18105. this._LODLevels.splice(index, 1);
  18106. if (mesh) {
  18107. mesh._masterMesh = null;
  18108. }
  18109. }
  18110. }
  18111. this._sortLODLevels();
  18112. return this;
  18113. };
  18114. /**
  18115. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  18116. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18117. */
  18118. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  18119. if (!this._LODLevels || this._LODLevels.length === 0) {
  18120. return this;
  18121. }
  18122. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  18123. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  18124. if (this.onLODLevelSelection) {
  18125. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  18126. }
  18127. return this;
  18128. }
  18129. for (var index = 0; index < this._LODLevels.length; index++) {
  18130. var level = this._LODLevels[index];
  18131. if (level.distance < distanceToCamera) {
  18132. if (level.mesh) {
  18133. level.mesh._preActivate();
  18134. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18135. }
  18136. if (this.onLODLevelSelection) {
  18137. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  18138. }
  18139. return level.mesh;
  18140. }
  18141. }
  18142. if (this.onLODLevelSelection) {
  18143. this.onLODLevelSelection(distanceToCamera, this, this);
  18144. }
  18145. return this;
  18146. };
  18147. Object.defineProperty(Mesh.prototype, "geometry", {
  18148. /**
  18149. * Returns the mesh internal Geometry object.
  18150. */
  18151. get: function () {
  18152. return this._geometry;
  18153. },
  18154. enumerable: true,
  18155. configurable: true
  18156. });
  18157. /**
  18158. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  18159. */
  18160. Mesh.prototype.getTotalVertices = function () {
  18161. if (!this._geometry) {
  18162. return 0;
  18163. }
  18164. return this._geometry.getTotalVertices();
  18165. };
  18166. /**
  18167. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  18168. * 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.
  18169. * Returns null if the mesh has no geometry or no vertex buffer.
  18170. * Possible `kind` values :
  18171. * - BABYLON.VertexBuffer.PositionKind
  18172. * - BABYLON.VertexBuffer.UVKind
  18173. * - BABYLON.VertexBuffer.UV2Kind
  18174. * - BABYLON.VertexBuffer.UV3Kind
  18175. * - BABYLON.VertexBuffer.UV4Kind
  18176. * - BABYLON.VertexBuffer.UV5Kind
  18177. * - BABYLON.VertexBuffer.UV6Kind
  18178. * - BABYLON.VertexBuffer.ColorKind
  18179. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18180. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18181. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18182. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18183. */
  18184. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  18185. if (!this._geometry) {
  18186. return null;
  18187. }
  18188. return this._geometry.getVerticesData(kind, copyWhenShared);
  18189. };
  18190. /**
  18191. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  18192. * Returns `undefined` if the mesh has no geometry.
  18193. * Possible `kind` values :
  18194. * - BABYLON.VertexBuffer.PositionKind
  18195. * - BABYLON.VertexBuffer.UVKind
  18196. * - BABYLON.VertexBuffer.UV2Kind
  18197. * - BABYLON.VertexBuffer.UV3Kind
  18198. * - BABYLON.VertexBuffer.UV4Kind
  18199. * - BABYLON.VertexBuffer.UV5Kind
  18200. * - BABYLON.VertexBuffer.UV6Kind
  18201. * - BABYLON.VertexBuffer.ColorKind
  18202. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18203. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18204. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18205. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18206. */
  18207. Mesh.prototype.getVertexBuffer = function (kind) {
  18208. if (!this._geometry) {
  18209. return undefined;
  18210. }
  18211. return this._geometry.getVertexBuffer(kind);
  18212. };
  18213. /**
  18214. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  18215. * Possible `kind` values :
  18216. * - BABYLON.VertexBuffer.PositionKind
  18217. * - BABYLON.VertexBuffer.UVKind
  18218. * - BABYLON.VertexBuffer.UV2Kind
  18219. * - BABYLON.VertexBuffer.UV3Kind
  18220. * - BABYLON.VertexBuffer.UV4Kind
  18221. * - BABYLON.VertexBuffer.UV5Kind
  18222. * - BABYLON.VertexBuffer.UV6Kind
  18223. * - BABYLON.VertexBuffer.ColorKind
  18224. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18225. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18226. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18227. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18228. */
  18229. Mesh.prototype.isVerticesDataPresent = function (kind) {
  18230. if (!this._geometry) {
  18231. if (this._delayInfo) {
  18232. return this._delayInfo.indexOf(kind) !== -1;
  18233. }
  18234. return false;
  18235. }
  18236. return this._geometry.isVerticesDataPresent(kind);
  18237. };
  18238. /**
  18239. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  18240. * Possible `kind` values :
  18241. * - BABYLON.VertexBuffer.PositionKind
  18242. * - BABYLON.VertexBuffer.UVKind
  18243. * - BABYLON.VertexBuffer.UV2Kind
  18244. * - BABYLON.VertexBuffer.UV3Kind
  18245. * - BABYLON.VertexBuffer.UV4Kind
  18246. * - BABYLON.VertexBuffer.UV5Kind
  18247. * - BABYLON.VertexBuffer.UV6Kind
  18248. * - BABYLON.VertexBuffer.ColorKind
  18249. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18250. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18251. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18252. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18253. */
  18254. Mesh.prototype.getVerticesDataKinds = function () {
  18255. if (!this._geometry) {
  18256. var result = [];
  18257. if (this._delayInfo) {
  18258. for (var kind in this._delayInfo) {
  18259. result.push(kind);
  18260. }
  18261. }
  18262. return result;
  18263. }
  18264. return this._geometry.getVerticesDataKinds();
  18265. };
  18266. /**
  18267. * Returns a positive integer : the total number of indices in this mesh geometry.
  18268. * Returns zero if the mesh has no geometry.
  18269. */
  18270. Mesh.prototype.getTotalIndices = function () {
  18271. if (!this._geometry) {
  18272. return 0;
  18273. }
  18274. return this._geometry.getTotalIndices();
  18275. };
  18276. /**
  18277. * Returns an array of integers or a Int32Array populated with the mesh indices.
  18278. * 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.
  18279. * Returns an empty array if the mesh has no geometry.
  18280. */
  18281. Mesh.prototype.getIndices = function (copyWhenShared) {
  18282. if (!this._geometry) {
  18283. return [];
  18284. }
  18285. return this._geometry.getIndices(copyWhenShared);
  18286. };
  18287. Object.defineProperty(Mesh.prototype, "isBlocked", {
  18288. get: function () {
  18289. return this._masterMesh !== null && this._masterMesh !== undefined;
  18290. },
  18291. enumerable: true,
  18292. configurable: true
  18293. });
  18294. /**
  18295. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  18296. */
  18297. Mesh.prototype.isReady = function () {
  18298. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18299. return false;
  18300. }
  18301. return _super.prototype.isReady.call(this);
  18302. };
  18303. /**
  18304. * Boolean : true if the mesh has been disposed.
  18305. */
  18306. Mesh.prototype.isDisposed = function () {
  18307. return this._isDisposed;
  18308. };
  18309. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  18310. get: function () {
  18311. return this._sideOrientation;
  18312. },
  18313. /**
  18314. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  18315. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  18316. */
  18317. set: function (sideO) {
  18318. this._sideOrientation = sideO;
  18319. },
  18320. enumerable: true,
  18321. configurable: true
  18322. });
  18323. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  18324. /**
  18325. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  18326. * This property is pertinent only for updatable parametric shapes.
  18327. */
  18328. get: function () {
  18329. return this._areNormalsFrozen;
  18330. },
  18331. enumerable: true,
  18332. configurable: true
  18333. });
  18334. /**
  18335. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18336. * It has no effect at all on other shapes.
  18337. * It prevents the mesh normals from being recomputed on next `positions` array update.
  18338. */
  18339. Mesh.prototype.freezeNormals = function () {
  18340. this._areNormalsFrozen = true;
  18341. };
  18342. /**
  18343. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18344. * It has no effect at all on other shapes.
  18345. * It reactivates the mesh normals computation if it was previously frozen.
  18346. */
  18347. Mesh.prototype.unfreezeNormals = function () {
  18348. this._areNormalsFrozen = false;
  18349. };
  18350. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  18351. /**
  18352. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  18353. */
  18354. set: function (count) {
  18355. this._overridenInstanceCount = count;
  18356. },
  18357. enumerable: true,
  18358. configurable: true
  18359. });
  18360. // Methods
  18361. Mesh.prototype._preActivate = function () {
  18362. var sceneRenderId = this.getScene().getRenderId();
  18363. if (this._preActivateId === sceneRenderId) {
  18364. return;
  18365. }
  18366. this._preActivateId = sceneRenderId;
  18367. this._visibleInstances = null;
  18368. };
  18369. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18370. if (this._visibleInstances) {
  18371. this._visibleInstances.intermediateDefaultRenderId = renderId;
  18372. }
  18373. };
  18374. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  18375. if (!this._visibleInstances) {
  18376. this._visibleInstances = {};
  18377. this._visibleInstances.defaultRenderId = renderId;
  18378. this._visibleInstances.selfDefaultRenderId = this._renderId;
  18379. }
  18380. if (!this._visibleInstances[renderId]) {
  18381. this._visibleInstances[renderId] = new Array();
  18382. }
  18383. this._visibleInstances[renderId].push(instance);
  18384. };
  18385. /**
  18386. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  18387. * This means the mesh underlying bounding box and sphere are recomputed.
  18388. */
  18389. Mesh.prototype.refreshBoundingInfo = function () {
  18390. if (this._boundingInfo.isLocked) {
  18391. return;
  18392. }
  18393. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18394. if (data) {
  18395. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  18396. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18397. }
  18398. if (this.subMeshes) {
  18399. for (var index = 0; index < this.subMeshes.length; index++) {
  18400. this.subMeshes[index].refreshBoundingInfo();
  18401. }
  18402. }
  18403. this._updateBoundingInfo();
  18404. };
  18405. Mesh.prototype._createGlobalSubMesh = function () {
  18406. var totalVertices = this.getTotalVertices();
  18407. if (!totalVertices || !this.getIndices()) {
  18408. return null;
  18409. }
  18410. this.releaseSubMeshes();
  18411. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  18412. };
  18413. Mesh.prototype.subdivide = function (count) {
  18414. if (count < 1) {
  18415. return;
  18416. }
  18417. var totalIndices = this.getTotalIndices();
  18418. var subdivisionSize = (totalIndices / count) | 0;
  18419. var offset = 0;
  18420. // Ensure that subdivisionSize is a multiple of 3
  18421. while (subdivisionSize % 3 !== 0) {
  18422. subdivisionSize++;
  18423. }
  18424. this.releaseSubMeshes();
  18425. for (var index = 0; index < count; index++) {
  18426. if (offset >= totalIndices) {
  18427. break;
  18428. }
  18429. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  18430. offset += subdivisionSize;
  18431. }
  18432. this.synchronizeInstances();
  18433. };
  18434. /**
  18435. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18436. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18437. * The `data` are either a numeric array either a Float32Array.
  18438. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18439. * 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).
  18440. * Note that a new underlying VertexBuffer object is created each call.
  18441. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18442. *
  18443. * Possible `kind` values :
  18444. * - BABYLON.VertexBuffer.PositionKind
  18445. * - BABYLON.VertexBuffer.UVKind
  18446. * - BABYLON.VertexBuffer.UV2Kind
  18447. * - BABYLON.VertexBuffer.UV3Kind
  18448. * - BABYLON.VertexBuffer.UV4Kind
  18449. * - BABYLON.VertexBuffer.UV5Kind
  18450. * - BABYLON.VertexBuffer.UV6Kind
  18451. * - BABYLON.VertexBuffer.ColorKind
  18452. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18453. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18454. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18455. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18456. */
  18457. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18458. if (!this._geometry) {
  18459. var vertexData = new BABYLON.VertexData();
  18460. vertexData.set(data, kind);
  18461. var scene = this.getScene();
  18462. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  18463. }
  18464. else {
  18465. this._geometry.setVerticesData(kind, data, updatable, stride);
  18466. }
  18467. };
  18468. Mesh.prototype.setVerticesBuffer = function (buffer) {
  18469. if (!this._geometry) {
  18470. var scene = this.getScene();
  18471. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  18472. }
  18473. this._geometry.setVerticesBuffer(buffer);
  18474. };
  18475. /**
  18476. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18477. * If the mesh has no geometry, it is simply returned as it is.
  18478. * The `data` are either a numeric array either a Float32Array.
  18479. * No new underlying VertexBuffer object is created.
  18480. * 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.
  18481. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18482. *
  18483. * Possible `kind` values :
  18484. * - BABYLON.VertexBuffer.PositionKind
  18485. * - BABYLON.VertexBuffer.UVKind
  18486. * - BABYLON.VertexBuffer.UV2Kind
  18487. * - BABYLON.VertexBuffer.UV3Kind
  18488. * - BABYLON.VertexBuffer.UV4Kind
  18489. * - BABYLON.VertexBuffer.UV5Kind
  18490. * - BABYLON.VertexBuffer.UV6Kind
  18491. * - BABYLON.VertexBuffer.ColorKind
  18492. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18493. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18494. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18495. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18496. */
  18497. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18498. if (!this._geometry) {
  18499. return;
  18500. }
  18501. if (!makeItUnique) {
  18502. this._geometry.updateVerticesData(kind, data, updateExtends);
  18503. }
  18504. else {
  18505. this.makeGeometryUnique();
  18506. this.updateVerticesData(kind, data, updateExtends, false);
  18507. }
  18508. };
  18509. /**
  18510. * Deprecated since BabylonJS v2.3
  18511. */
  18512. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  18513. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  18514. if (!this._geometry) {
  18515. return;
  18516. }
  18517. if (!makeItUnique) {
  18518. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  18519. }
  18520. else {
  18521. this.makeGeometryUnique();
  18522. this.updateVerticesDataDirectly(kind, data, offset, false);
  18523. }
  18524. };
  18525. /**
  18526. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  18527. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  18528. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  18529. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  18530. */
  18531. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  18532. if (computeNormals === void 0) { computeNormals = true; }
  18533. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18534. positionFunction(positions);
  18535. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  18536. if (computeNormals) {
  18537. var indices = this.getIndices();
  18538. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18539. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  18540. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  18541. }
  18542. };
  18543. Mesh.prototype.makeGeometryUnique = function () {
  18544. if (!this._geometry) {
  18545. return;
  18546. }
  18547. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  18548. geometry.applyToMesh(this);
  18549. };
  18550. /**
  18551. * Sets the mesh indices.
  18552. * Expects an array populated with integers or a Int32Array.
  18553. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18554. * This method creates a new index buffer each call.
  18555. */
  18556. Mesh.prototype.setIndices = function (indices, totalVertices) {
  18557. if (!this._geometry) {
  18558. var vertexData = new BABYLON.VertexData();
  18559. vertexData.indices = indices;
  18560. var scene = this.getScene();
  18561. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  18562. }
  18563. else {
  18564. this._geometry.setIndices(indices, totalVertices);
  18565. }
  18566. };
  18567. /**
  18568. * Invert the geometry to move from a right handed system to a left handed one.
  18569. */
  18570. Mesh.prototype.toLeftHanded = function () {
  18571. if (!this._geometry) {
  18572. return;
  18573. }
  18574. this._geometry.toLeftHanded();
  18575. };
  18576. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  18577. var engine = this.getScene().getEngine();
  18578. // Wireframe
  18579. var indexToBind;
  18580. if (this._unIndexed) {
  18581. indexToBind = null;
  18582. }
  18583. else {
  18584. switch (fillMode) {
  18585. case BABYLON.Material.PointFillMode:
  18586. indexToBind = null;
  18587. break;
  18588. case BABYLON.Material.WireFrameFillMode:
  18589. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  18590. break;
  18591. default:
  18592. case BABYLON.Material.TriangleFillMode:
  18593. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  18594. break;
  18595. }
  18596. }
  18597. // VBOs
  18598. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  18599. };
  18600. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  18601. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  18602. return;
  18603. }
  18604. this.onBeforeDrawObservable.notifyObservers(this);
  18605. var engine = this.getScene().getEngine();
  18606. // Draw order
  18607. switch (fillMode) {
  18608. case BABYLON.Material.PointFillMode:
  18609. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  18610. break;
  18611. case BABYLON.Material.WireFrameFillMode:
  18612. if (this._unIndexed) {
  18613. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  18614. }
  18615. else {
  18616. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  18617. }
  18618. break;
  18619. default:
  18620. if (this._unIndexed) {
  18621. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  18622. }
  18623. else {
  18624. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  18625. }
  18626. }
  18627. };
  18628. /**
  18629. * Registers for this mesh a javascript function called just before the rendering process.
  18630. * This function is passed the current mesh and doesn't return anything.
  18631. */
  18632. Mesh.prototype.registerBeforeRender = function (func) {
  18633. this.onBeforeRenderObservable.add(func);
  18634. };
  18635. /**
  18636. * Disposes a previously registered javascript function called before the rendering.
  18637. * This function is passed the current mesh and doesn't return anything.
  18638. */
  18639. Mesh.prototype.unregisterBeforeRender = function (func) {
  18640. this.onBeforeRenderObservable.removeCallback(func);
  18641. };
  18642. /**
  18643. * Registers for this mesh a javascript function called just after the rendering is complete.
  18644. * This function is passed the current mesh and doesn't return anything.
  18645. */
  18646. Mesh.prototype.registerAfterRender = function (func) {
  18647. this.onAfterRenderObservable.add(func);
  18648. };
  18649. /**
  18650. * Disposes a previously registered javascript function called after the rendering.
  18651. * This function is passed the current mesh and doesn't return anything.
  18652. */
  18653. Mesh.prototype.unregisterAfterRender = function (func) {
  18654. this.onAfterRenderObservable.removeCallback(func);
  18655. };
  18656. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  18657. var scene = this.getScene();
  18658. this._batchCache.mustReturn = false;
  18659. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  18660. this._batchCache.visibleInstances[subMeshId] = null;
  18661. if (this._visibleInstances) {
  18662. var currentRenderId = scene.getRenderId();
  18663. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  18664. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  18665. var selfRenderId = this._renderId;
  18666. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  18667. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  18668. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  18669. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  18670. }
  18671. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  18672. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  18673. this._batchCache.mustReturn = true;
  18674. return this._batchCache;
  18675. }
  18676. if (currentRenderId !== selfRenderId) {
  18677. this._batchCache.renderSelf[subMeshId] = false;
  18678. }
  18679. }
  18680. this._renderIdForInstances[subMeshId] = currentRenderId;
  18681. }
  18682. return this._batchCache;
  18683. };
  18684. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  18685. var visibleInstances = batch.visibleInstances[subMesh._id];
  18686. var matricesCount = visibleInstances.length + 1;
  18687. var bufferSize = matricesCount * 16 * 4;
  18688. var currentInstancesBufferSize = this._instancesBufferSize;
  18689. var instancesBuffer = this._instancesBuffer;
  18690. while (this._instancesBufferSize < bufferSize) {
  18691. this._instancesBufferSize *= 2;
  18692. }
  18693. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  18694. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  18695. }
  18696. var offset = 0;
  18697. var instancesCount = 0;
  18698. var world = this.getWorldMatrix();
  18699. if (batch.renderSelf[subMesh._id]) {
  18700. world.copyToArray(this._instancesData, offset);
  18701. offset += 16;
  18702. instancesCount++;
  18703. }
  18704. if (visibleInstances) {
  18705. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  18706. var instance = visibleInstances[instanceIndex];
  18707. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  18708. offset += 16;
  18709. instancesCount++;
  18710. }
  18711. }
  18712. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  18713. if (instancesBuffer) {
  18714. instancesBuffer.dispose();
  18715. }
  18716. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  18717. this._instancesBuffer = instancesBuffer;
  18718. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  18719. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  18720. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  18721. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  18722. }
  18723. else {
  18724. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  18725. }
  18726. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  18727. this._draw(subMesh, fillMode, instancesCount);
  18728. engine.unbindInstanceAttributes();
  18729. };
  18730. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  18731. var scene = this.getScene();
  18732. var engine = scene.getEngine();
  18733. if (hardwareInstancedRendering) {
  18734. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  18735. }
  18736. else {
  18737. if (batch.renderSelf[subMesh._id]) {
  18738. // Draw
  18739. if (onBeforeDraw) {
  18740. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  18741. }
  18742. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  18743. }
  18744. if (batch.visibleInstances[subMesh._id]) {
  18745. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  18746. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  18747. // World
  18748. var world = instance.getWorldMatrix();
  18749. if (onBeforeDraw) {
  18750. onBeforeDraw(true, world, effectiveMaterial);
  18751. }
  18752. // Draw
  18753. this._draw(subMesh, fillMode);
  18754. }
  18755. }
  18756. }
  18757. };
  18758. /**
  18759. * Triggers the draw call for the mesh.
  18760. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  18761. */
  18762. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  18763. var scene = this.getScene();
  18764. // Managing instances
  18765. var batch = this._getInstancesRenderList(subMesh._id);
  18766. if (batch.mustReturn) {
  18767. return;
  18768. }
  18769. // Checking geometry state
  18770. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  18771. return;
  18772. }
  18773. var callbackIndex;
  18774. this.onBeforeRenderObservable.notifyObservers(this);
  18775. var engine = scene.getEngine();
  18776. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  18777. // Material
  18778. var effectiveMaterial = subMesh.getMaterial();
  18779. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  18780. return;
  18781. }
  18782. // Outline - step 1
  18783. var savedDepthWrite = engine.getDepthWrite();
  18784. if (this.renderOutline) {
  18785. engine.setDepthWrite(false);
  18786. scene.getOutlineRenderer().render(subMesh, batch);
  18787. engine.setDepthWrite(savedDepthWrite);
  18788. }
  18789. effectiveMaterial._preBind();
  18790. var effect = effectiveMaterial.getEffect();
  18791. // Bind
  18792. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  18793. this._bind(subMesh, effect, fillMode);
  18794. var world = this.getWorldMatrix();
  18795. effectiveMaterial.bind(world, this);
  18796. // Alpha mode
  18797. if (enableAlphaMode) {
  18798. engine.setAlphaMode(effectiveMaterial.alphaMode);
  18799. }
  18800. // Draw
  18801. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw);
  18802. // Unbind
  18803. effectiveMaterial.unbind();
  18804. // Outline - step 2
  18805. if (this.renderOutline && savedDepthWrite) {
  18806. engine.setDepthWrite(true);
  18807. engine.setColorWrite(false);
  18808. scene.getOutlineRenderer().render(subMesh, batch);
  18809. engine.setColorWrite(true);
  18810. }
  18811. // Overlay
  18812. if (this.renderOverlay) {
  18813. var currentMode = engine.getAlphaMode();
  18814. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  18815. scene.getOutlineRenderer().render(subMesh, batch, true);
  18816. engine.setAlphaMode(currentMode);
  18817. }
  18818. this.onAfterRenderObservable.notifyObservers(this);
  18819. };
  18820. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  18821. if (isInstance) {
  18822. effectiveMaterial.bindOnlyWorldMatrix(world);
  18823. }
  18824. };
  18825. /**
  18826. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  18827. */
  18828. Mesh.prototype.getEmittedParticleSystems = function () {
  18829. var results = new Array();
  18830. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  18831. var particleSystem = this.getScene().particleSystems[index];
  18832. if (particleSystem.emitter === this) {
  18833. results.push(particleSystem);
  18834. }
  18835. }
  18836. return results;
  18837. };
  18838. /**
  18839. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  18840. */
  18841. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  18842. var results = new Array();
  18843. var descendants = this.getDescendants();
  18844. descendants.push(this);
  18845. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  18846. var particleSystem = this.getScene().particleSystems[index];
  18847. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  18848. results.push(particleSystem);
  18849. }
  18850. }
  18851. return results;
  18852. };
  18853. Mesh.prototype._checkDelayState = function () {
  18854. var scene = this.getScene();
  18855. if (this._geometry) {
  18856. this._geometry.load(scene);
  18857. }
  18858. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18859. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  18860. this._queueLoad(this, scene);
  18861. }
  18862. };
  18863. Mesh.prototype._queueLoad = function (mesh, scene) {
  18864. var _this = this;
  18865. scene._addPendingData(mesh);
  18866. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  18867. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  18868. if (data instanceof ArrayBuffer) {
  18869. _this._delayLoadingFunction(data, _this);
  18870. }
  18871. else {
  18872. _this._delayLoadingFunction(JSON.parse(data), _this);
  18873. }
  18874. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18875. scene._removePendingData(_this);
  18876. }, function () { }, scene.database, getBinaryData);
  18877. };
  18878. /**
  18879. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  18880. */
  18881. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  18882. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18883. return false;
  18884. }
  18885. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  18886. return false;
  18887. }
  18888. this._checkDelayState();
  18889. return true;
  18890. };
  18891. /**
  18892. * Sets the mesh material by the material or multiMaterial `id` property.
  18893. * The material `id` is a string identifying the material or the multiMaterial.
  18894. * This method returns nothing.
  18895. */
  18896. Mesh.prototype.setMaterialByID = function (id) {
  18897. var materials = this.getScene().materials;
  18898. var index;
  18899. for (index = 0; index < materials.length; index++) {
  18900. if (materials[index].id === id) {
  18901. this.material = materials[index];
  18902. return;
  18903. }
  18904. }
  18905. // Multi
  18906. var multiMaterials = this.getScene().multiMaterials;
  18907. for (index = 0; index < multiMaterials.length; index++) {
  18908. if (multiMaterials[index].id === id) {
  18909. this.material = multiMaterials[index];
  18910. return;
  18911. }
  18912. }
  18913. };
  18914. /**
  18915. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  18916. */
  18917. Mesh.prototype.getAnimatables = function () {
  18918. var results = [];
  18919. if (this.material) {
  18920. results.push(this.material);
  18921. }
  18922. if (this.skeleton) {
  18923. results.push(this.skeleton);
  18924. }
  18925. return results;
  18926. };
  18927. /**
  18928. * Modifies the mesh geometry according to the passed transformation matrix.
  18929. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  18930. * The mesh normals are modified accordingly the same transformation.
  18931. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  18932. * Note that, under the hood, this method sets a new VertexBuffer each call.
  18933. */
  18934. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  18935. // Position
  18936. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18937. return;
  18938. }
  18939. var submeshes = this.subMeshes.splice(0);
  18940. this._resetPointsArrayCache();
  18941. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18942. var temp = [];
  18943. var index;
  18944. for (index = 0; index < data.length; index += 3) {
  18945. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  18946. }
  18947. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  18948. // Normals
  18949. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18950. return;
  18951. }
  18952. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18953. temp = [];
  18954. for (index = 0; index < data.length; index += 3) {
  18955. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  18956. }
  18957. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  18958. // flip faces?
  18959. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  18960. this.flipFaces();
  18961. }
  18962. // Restore submeshes
  18963. this.releaseSubMeshes();
  18964. this.subMeshes = submeshes;
  18965. };
  18966. /**
  18967. * Modifies the mesh geometry according to its own current World Matrix.
  18968. * The mesh World Matrix is then reset.
  18969. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  18970. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  18971. * Note that, under the hood, this method sets a new VertexBuffer each call.
  18972. */
  18973. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  18974. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  18975. this.scaling.copyFromFloats(1, 1, 1);
  18976. this.position.copyFromFloats(0, 0, 0);
  18977. this.rotation.copyFromFloats(0, 0, 0);
  18978. //only if quaternion is already set
  18979. if (this.rotationQuaternion) {
  18980. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  18981. }
  18982. this._worldMatrix = BABYLON.Matrix.Identity();
  18983. };
  18984. // Cache
  18985. Mesh.prototype._resetPointsArrayCache = function () {
  18986. this._positions = null;
  18987. };
  18988. Mesh.prototype._generatePointsArray = function () {
  18989. if (this._positions)
  18990. return true;
  18991. this._positions = [];
  18992. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18993. if (!data) {
  18994. return false;
  18995. }
  18996. for (var index = 0; index < data.length; index += 3) {
  18997. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  18998. }
  18999. return true;
  19000. };
  19001. /**
  19002. * Returns a new Mesh object generated from the current mesh properties.
  19003. * This method must not get confused with createInstance().
  19004. * The parameter `name` is a string, the name given to the new mesh.
  19005. * The optional parameter `newParent` can be any Node object (default `null`).
  19006. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  19007. * 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.
  19008. */
  19009. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  19010. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19011. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  19012. };
  19013. /**
  19014. * Disposes the mesh.
  19015. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  19016. */
  19017. Mesh.prototype.dispose = function (doNotRecurse) {
  19018. if (this._geometry) {
  19019. this._geometry.releaseForMesh(this, true);
  19020. }
  19021. // Instances
  19022. if (this._instancesBuffer) {
  19023. this._instancesBuffer.dispose();
  19024. this._instancesBuffer = null;
  19025. }
  19026. while (this.instances.length) {
  19027. this.instances[0].dispose();
  19028. }
  19029. _super.prototype.dispose.call(this, doNotRecurse);
  19030. };
  19031. /**
  19032. * Modifies the mesh geometry according to a displacement map.
  19033. * 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.
  19034. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19035. * This method returns nothing.
  19036. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  19037. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19038. * 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.
  19039. */
  19040. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  19041. var _this = this;
  19042. var scene = this.getScene();
  19043. var onload = function (img) {
  19044. // Getting height map data
  19045. var canvas = document.createElement("canvas");
  19046. var context = canvas.getContext("2d");
  19047. var heightMapWidth = img.width;
  19048. var heightMapHeight = img.height;
  19049. canvas.width = heightMapWidth;
  19050. canvas.height = heightMapHeight;
  19051. context.drawImage(img, 0, 0);
  19052. // Create VertexData from map data
  19053. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  19054. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  19055. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  19056. //execute success callback, if set
  19057. if (onSuccess) {
  19058. onSuccess(_this);
  19059. }
  19060. };
  19061. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  19062. };
  19063. /**
  19064. * Modifies the mesh geometry according to a displacementMap buffer.
  19065. * 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.
  19066. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19067. * This method returns nothing.
  19068. * 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.
  19069. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  19070. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19071. */
  19072. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  19073. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  19074. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  19075. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19076. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  19077. return;
  19078. }
  19079. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19080. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19081. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19082. var position = BABYLON.Vector3.Zero();
  19083. var normal = BABYLON.Vector3.Zero();
  19084. var uv = BABYLON.Vector2.Zero();
  19085. for (var index = 0; index < positions.length; index += 3) {
  19086. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  19087. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  19088. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  19089. // Compute height
  19090. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  19091. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  19092. var pos = (u + v * heightMapWidth) * 4;
  19093. var r = buffer[pos] / 255.0;
  19094. var g = buffer[pos + 1] / 255.0;
  19095. var b = buffer[pos + 2] / 255.0;
  19096. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  19097. normal.normalize();
  19098. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  19099. position = position.add(normal);
  19100. position.toArray(positions, index);
  19101. }
  19102. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  19103. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  19104. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19105. };
  19106. /**
  19107. * Modify the mesh to get a flat shading rendering.
  19108. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  19109. * This method returns nothing.
  19110. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  19111. */
  19112. Mesh.prototype.convertToFlatShadedMesh = function () {
  19113. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  19114. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19115. var kinds = this.getVerticesDataKinds();
  19116. var vbs = [];
  19117. var data = [];
  19118. var newdata = [];
  19119. var updatableNormals = false;
  19120. var kindIndex;
  19121. var kind;
  19122. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19123. kind = kinds[kindIndex];
  19124. var vertexBuffer = this.getVertexBuffer(kind);
  19125. if (kind === BABYLON.VertexBuffer.NormalKind) {
  19126. updatableNormals = vertexBuffer.isUpdatable();
  19127. kinds.splice(kindIndex, 1);
  19128. kindIndex--;
  19129. continue;
  19130. }
  19131. vbs[kind] = vertexBuffer;
  19132. data[kind] = vbs[kind].getData();
  19133. newdata[kind] = [];
  19134. }
  19135. // Save previous submeshes
  19136. var previousSubmeshes = this.subMeshes.slice(0);
  19137. var indices = this.getIndices();
  19138. var totalIndices = this.getTotalIndices();
  19139. // Generating unique vertices per face
  19140. var index;
  19141. for (index = 0; index < totalIndices; index++) {
  19142. var vertexIndex = indices[index];
  19143. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19144. kind = kinds[kindIndex];
  19145. var stride = vbs[kind].getStrideSize();
  19146. for (var offset = 0; offset < stride; offset++) {
  19147. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19148. }
  19149. }
  19150. }
  19151. // Updating faces & normal
  19152. var normals = [];
  19153. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  19154. for (index = 0; index < totalIndices; index += 3) {
  19155. indices[index] = index;
  19156. indices[index + 1] = index + 1;
  19157. indices[index + 2] = index + 2;
  19158. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  19159. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  19160. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  19161. var p1p2 = p1.subtract(p2);
  19162. var p3p2 = p3.subtract(p2);
  19163. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  19164. // Store same normals for every vertex
  19165. for (var localIndex = 0; localIndex < 3; localIndex++) {
  19166. normals.push(normal.x);
  19167. normals.push(normal.y);
  19168. normals.push(normal.z);
  19169. }
  19170. }
  19171. this.setIndices(indices);
  19172. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  19173. // Updating vertex buffers
  19174. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19175. kind = kinds[kindIndex];
  19176. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19177. }
  19178. // Updating submeshes
  19179. this.releaseSubMeshes();
  19180. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19181. var previousOne = previousSubmeshes[submeshIndex];
  19182. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19183. }
  19184. this.synchronizeInstances();
  19185. };
  19186. /**
  19187. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  19188. * In other words, more vertices, no more indices and a single bigger VBO.
  19189. * This method returns nothing.
  19190. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  19191. *
  19192. */
  19193. Mesh.prototype.convertToUnIndexedMesh = function () {
  19194. /// <summary>Remove indices by unfolding faces into buffers</summary>
  19195. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19196. var kinds = this.getVerticesDataKinds();
  19197. var vbs = [];
  19198. var data = [];
  19199. var newdata = [];
  19200. var updatableNormals = false;
  19201. var kindIndex;
  19202. var kind;
  19203. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19204. kind = kinds[kindIndex];
  19205. var vertexBuffer = this.getVertexBuffer(kind);
  19206. vbs[kind] = vertexBuffer;
  19207. data[kind] = vbs[kind].getData();
  19208. newdata[kind] = [];
  19209. }
  19210. // Save previous submeshes
  19211. var previousSubmeshes = this.subMeshes.slice(0);
  19212. var indices = this.getIndices();
  19213. var totalIndices = this.getTotalIndices();
  19214. // Generating unique vertices per face
  19215. var index;
  19216. for (index = 0; index < totalIndices; index++) {
  19217. var vertexIndex = indices[index];
  19218. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19219. kind = kinds[kindIndex];
  19220. var stride = vbs[kind].getStrideSize();
  19221. for (var offset = 0; offset < stride; offset++) {
  19222. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19223. }
  19224. }
  19225. }
  19226. // Updating indices
  19227. for (index = 0; index < totalIndices; index += 3) {
  19228. indices[index] = index;
  19229. indices[index + 1] = index + 1;
  19230. indices[index + 2] = index + 2;
  19231. }
  19232. this.setIndices(indices);
  19233. // Updating vertex buffers
  19234. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19235. kind = kinds[kindIndex];
  19236. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19237. }
  19238. // Updating submeshes
  19239. this.releaseSubMeshes();
  19240. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19241. var previousOne = previousSubmeshes[submeshIndex];
  19242. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19243. }
  19244. this._unIndexed = true;
  19245. this.synchronizeInstances();
  19246. };
  19247. /**
  19248. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  19249. * This method returns nothing.
  19250. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  19251. */
  19252. Mesh.prototype.flipFaces = function (flipNormals) {
  19253. if (flipNormals === void 0) { flipNormals = false; }
  19254. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  19255. var i;
  19256. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19257. for (i = 0; i < vertex_data.normals.length; i++) {
  19258. vertex_data.normals[i] *= -1;
  19259. }
  19260. }
  19261. var temp;
  19262. for (i = 0; i < vertex_data.indices.length; i += 3) {
  19263. // reassign indices
  19264. temp = vertex_data.indices[i + 1];
  19265. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  19266. vertex_data.indices[i + 2] = temp;
  19267. }
  19268. vertex_data.applyToMesh(this);
  19269. };
  19270. // Instances
  19271. /**
  19272. * Creates a new InstancedMesh object from the mesh model.
  19273. * An instance shares the same properties and the same material than its model.
  19274. * Only these properties of each instance can then be set individually :
  19275. * - position
  19276. * - rotation
  19277. * - rotationQuaternion
  19278. * - setPivotMatrix
  19279. * - scaling
  19280. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  19281. * Warning : this method is not supported for Line mesh and LineSystem
  19282. */
  19283. Mesh.prototype.createInstance = function (name) {
  19284. return new BABYLON.InstancedMesh(name, this);
  19285. };
  19286. /**
  19287. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  19288. * After this call, all the mesh instances have the same submeshes than the current mesh.
  19289. * This method returns nothing.
  19290. */
  19291. Mesh.prototype.synchronizeInstances = function () {
  19292. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  19293. var instance = this.instances[instanceIndex];
  19294. instance._syncSubMeshes();
  19295. }
  19296. };
  19297. /**
  19298. * Simplify the mesh according to the given array of settings.
  19299. * Function will return immediately and will simplify async. It returns nothing.
  19300. * @param settings a collection of simplification settings.
  19301. * @param parallelProcessing should all levels calculate parallel or one after the other.
  19302. * @param type the type of simplification to run.
  19303. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  19304. */
  19305. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  19306. if (parallelProcessing === void 0) { parallelProcessing = true; }
  19307. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  19308. this.getScene().simplificationQueue.addTask({
  19309. settings: settings,
  19310. parallelProcessing: parallelProcessing,
  19311. mesh: this,
  19312. simplificationType: simplificationType,
  19313. successCallback: successCallback
  19314. });
  19315. };
  19316. /**
  19317. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  19318. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  19319. * This should be used together with the simplification to avoid disappearing triangles.
  19320. * @param successCallback an optional success callback to be called after the optimization finished.
  19321. */
  19322. Mesh.prototype.optimizeIndices = function (successCallback) {
  19323. var _this = this;
  19324. var indices = this.getIndices();
  19325. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19326. var vectorPositions = [];
  19327. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  19328. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  19329. }
  19330. var dupes = [];
  19331. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  19332. var realPos = vectorPositions.length - 1 - iteration;
  19333. var testedPosition = vectorPositions[realPos];
  19334. for (var j = 0; j < realPos; ++j) {
  19335. var againstPosition = vectorPositions[j];
  19336. if (testedPosition.equals(againstPosition)) {
  19337. dupes[realPos] = j;
  19338. break;
  19339. }
  19340. }
  19341. }, function () {
  19342. for (var i = 0; i < indices.length; ++i) {
  19343. indices[i] = dupes[indices[i]] || indices[i];
  19344. }
  19345. //indices are now reordered
  19346. var originalSubMeshes = _this.subMeshes.slice(0);
  19347. _this.setIndices(indices);
  19348. _this.subMeshes = originalSubMeshes;
  19349. if (successCallback) {
  19350. successCallback(_this);
  19351. }
  19352. });
  19353. };
  19354. // Statics
  19355. /**
  19356. * Returns a new Mesh object what is a deep copy of the passed mesh.
  19357. * The parameter `parsedMesh` is the mesh to be copied.
  19358. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19359. */
  19360. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  19361. var mesh = new Mesh(parsedMesh.name, scene);
  19362. mesh.id = parsedMesh.id;
  19363. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19364. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19365. if (parsedMesh.rotationQuaternion) {
  19366. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19367. }
  19368. else if (parsedMesh.rotation) {
  19369. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19370. }
  19371. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19372. if (parsedMesh.localMatrix) {
  19373. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19374. }
  19375. else if (parsedMesh.pivotMatrix) {
  19376. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19377. }
  19378. mesh.setEnabled(parsedMesh.isEnabled);
  19379. mesh.isVisible = parsedMesh.isVisible;
  19380. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19381. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19382. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19383. if (parsedMesh.applyFog !== undefined) {
  19384. mesh.applyFog = parsedMesh.applyFog;
  19385. }
  19386. if (parsedMesh.pickable !== undefined) {
  19387. mesh.isPickable = parsedMesh.pickable;
  19388. }
  19389. if (parsedMesh.alphaIndex !== undefined) {
  19390. mesh.alphaIndex = parsedMesh.alphaIndex;
  19391. }
  19392. mesh.receiveShadows = parsedMesh.receiveShadows;
  19393. mesh.billboardMode = parsedMesh.billboardMode;
  19394. if (parsedMesh.visibility !== undefined) {
  19395. mesh.visibility = parsedMesh.visibility;
  19396. }
  19397. mesh.checkCollisions = parsedMesh.checkCollisions;
  19398. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19399. // freezeWorldMatrix
  19400. if (parsedMesh.freezeWorldMatrix) {
  19401. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  19402. }
  19403. // Parent
  19404. if (parsedMesh.parentId) {
  19405. mesh._waitingParentId = parsedMesh.parentId;
  19406. }
  19407. // Actions
  19408. if (parsedMesh.actions !== undefined) {
  19409. mesh._waitingActions = parsedMesh.actions;
  19410. }
  19411. // Geometry
  19412. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19413. if (parsedMesh.delayLoadingFile) {
  19414. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19415. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19416. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19417. if (parsedMesh._binaryInfo) {
  19418. mesh._binaryInfo = parsedMesh._binaryInfo;
  19419. }
  19420. mesh._delayInfo = [];
  19421. if (parsedMesh.hasUVs) {
  19422. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19423. }
  19424. if (parsedMesh.hasUVs2) {
  19425. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19426. }
  19427. if (parsedMesh.hasUVs3) {
  19428. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  19429. }
  19430. if (parsedMesh.hasUVs4) {
  19431. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  19432. }
  19433. if (parsedMesh.hasUVs5) {
  19434. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  19435. }
  19436. if (parsedMesh.hasUVs6) {
  19437. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  19438. }
  19439. if (parsedMesh.hasColors) {
  19440. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19441. }
  19442. if (parsedMesh.hasMatricesIndices) {
  19443. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19444. }
  19445. if (parsedMesh.hasMatricesWeights) {
  19446. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19447. }
  19448. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  19449. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19450. mesh._checkDelayState();
  19451. }
  19452. }
  19453. else {
  19454. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  19455. }
  19456. // Material
  19457. if (parsedMesh.materialId) {
  19458. mesh.setMaterialByID(parsedMesh.materialId);
  19459. }
  19460. else {
  19461. mesh.material = null;
  19462. }
  19463. // Skeleton
  19464. if (parsedMesh.skeletonId > -1) {
  19465. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19466. if (parsedMesh.numBoneInfluencers) {
  19467. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  19468. }
  19469. }
  19470. // Animations
  19471. if (parsedMesh.animations) {
  19472. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19473. var parsedAnimation = parsedMesh.animations[animationIndex];
  19474. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19475. }
  19476. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  19477. }
  19478. if (parsedMesh.autoAnimate) {
  19479. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  19480. }
  19481. // Layer Mask
  19482. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19483. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19484. }
  19485. else {
  19486. mesh.layerMask = 0x0FFFFFFF;
  19487. }
  19488. //(Deprecated) physics
  19489. if (parsedMesh.physicsImpostor) {
  19490. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  19491. mass: parsedMesh.physicsMass,
  19492. friction: parsedMesh.physicsFriction,
  19493. restitution: parsedMesh.physicsRestitution
  19494. }, scene);
  19495. }
  19496. // Instances
  19497. if (parsedMesh.instances) {
  19498. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19499. var parsedInstance = parsedMesh.instances[index];
  19500. var instance = mesh.createInstance(parsedInstance.name);
  19501. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19502. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19503. if (parsedInstance.rotationQuaternion) {
  19504. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19505. }
  19506. else if (parsedInstance.rotation) {
  19507. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19508. }
  19509. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19510. instance.checkCollisions = mesh.checkCollisions;
  19511. if (parsedMesh.animations) {
  19512. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19513. parsedAnimation = parsedMesh.animations[animationIndex];
  19514. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19515. }
  19516. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  19517. }
  19518. }
  19519. }
  19520. return mesh;
  19521. };
  19522. /**
  19523. * Creates a ribbon mesh.
  19524. * Please consider using the same method from the MeshBuilder class instead.
  19525. * 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.
  19526. *
  19527. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  19528. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  19529. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  19530. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  19531. * 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.
  19532. * 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.
  19533. * 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
  19534. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19535. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19536. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19537. */
  19538. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  19539. return BABYLON.MeshBuilder.CreateRibbon(name, {
  19540. pathArray: pathArray,
  19541. closeArray: closeArray,
  19542. closePath: closePath,
  19543. offset: offset,
  19544. updatable: updatable,
  19545. sideOrientation: sideOrientation,
  19546. instance: instance
  19547. }, scene);
  19548. };
  19549. /**
  19550. * Creates a plane polygonal mesh. By default, this is a disc.
  19551. * Please consider using the same method from the MeshBuilder class instead.
  19552. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  19553. * 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.
  19554. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19555. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19556. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19557. */
  19558. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  19559. var options = {
  19560. radius: radius,
  19561. tessellation: tessellation,
  19562. sideOrientation: sideOrientation,
  19563. updatable: updatable
  19564. };
  19565. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  19566. };
  19567. /**
  19568. * Creates a box mesh.
  19569. * Please consider using the same method from the MeshBuilder class instead.
  19570. * The parameter `size` sets the size (float) of each box side (default 1).
  19571. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19572. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19573. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19574. */
  19575. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  19576. var options = {
  19577. size: size,
  19578. sideOrientation: sideOrientation,
  19579. updatable: updatable
  19580. };
  19581. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  19582. };
  19583. /**
  19584. * Creates a sphere mesh.
  19585. * Please consider using the same method from the MeshBuilder class instead.
  19586. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  19587. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  19588. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19589. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19590. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19591. */
  19592. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  19593. var options = {
  19594. segments: segments,
  19595. diameterX: diameter,
  19596. diameterY: diameter,
  19597. diameterZ: diameter,
  19598. sideOrientation: sideOrientation,
  19599. updatable: updatable
  19600. };
  19601. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  19602. };
  19603. /**
  19604. * Creates a cylinder or a cone mesh.
  19605. * Please consider using the same method from the MeshBuilder class instead.
  19606. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  19607. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  19608. * 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.
  19609. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  19610. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  19611. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19612. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19613. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19614. */
  19615. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  19616. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  19617. if (scene !== undefined) {
  19618. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  19619. updatable = scene;
  19620. }
  19621. scene = subdivisions;
  19622. subdivisions = 1;
  19623. }
  19624. var options = {
  19625. height: height,
  19626. diameterTop: diameterTop,
  19627. diameterBottom: diameterBottom,
  19628. tessellation: tessellation,
  19629. subdivisions: subdivisions,
  19630. sideOrientation: sideOrientation,
  19631. updatable: updatable
  19632. };
  19633. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  19634. };
  19635. // Torus (Code from SharpDX.org)
  19636. /**
  19637. * Creates a torus mesh.
  19638. * Please consider using the same method from the MeshBuilder class instead.
  19639. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  19640. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  19641. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  19642. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19643. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19644. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19645. */
  19646. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  19647. var options = {
  19648. diameter: diameter,
  19649. thickness: thickness,
  19650. tessellation: tessellation,
  19651. sideOrientation: sideOrientation,
  19652. updatable: updatable
  19653. };
  19654. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  19655. };
  19656. /**
  19657. * Creates a torus knot mesh.
  19658. * Please consider using the same method from the MeshBuilder class instead.
  19659. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  19660. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  19661. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  19662. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  19663. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19664. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19665. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19666. */
  19667. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  19668. var options = {
  19669. radius: radius,
  19670. tube: tube,
  19671. radialSegments: radialSegments,
  19672. tubularSegments: tubularSegments,
  19673. p: p,
  19674. q: q,
  19675. sideOrientation: sideOrientation,
  19676. updatable: updatable
  19677. };
  19678. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  19679. };
  19680. /**
  19681. * Creates a line mesh.
  19682. * Please consider using the same method from the MeshBuilder class instead.
  19683. * 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.
  19684. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19685. * The parameter `points` is an array successive Vector3.
  19686. * 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
  19687. * When updating an instance, remember that only point positions can change, not the number of points.
  19688. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19689. */
  19690. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  19691. var options = {
  19692. points: points,
  19693. updatable: updatable,
  19694. instance: instance
  19695. };
  19696. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  19697. };
  19698. /**
  19699. * Creates a dashed line mesh.
  19700. * Please consider using the same method from the MeshBuilder class instead.
  19701. * 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.
  19702. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19703. * The parameter `points` is an array successive Vector3.
  19704. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  19705. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  19706. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  19707. * 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
  19708. * When updating an instance, remember that only point positions can change, not the number of points.
  19709. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19710. */
  19711. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  19712. var options = {
  19713. points: points,
  19714. dashSize: dashSize,
  19715. gapSize: gapSize,
  19716. dashNb: dashNb,
  19717. updatable: updatable,
  19718. instance: instance
  19719. };
  19720. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  19721. };
  19722. /**
  19723. * Creates an extruded shape mesh.
  19724. * 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.
  19725. * Please consider using the same method from the MeshBuilder class instead.
  19726. *
  19727. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19728. * 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
  19729. * extruded along the Z axis.
  19730. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19731. * 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.
  19732. * The parameter `scale` (float, default 1) is the value to scale the shape.
  19733. * 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
  19734. * 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
  19735. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19736. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19737. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19738. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19739. */
  19740. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  19741. var options = {
  19742. shape: shape,
  19743. path: path,
  19744. scale: scale,
  19745. rotation: rotation,
  19746. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  19747. sideOrientation: sideOrientation,
  19748. instance: instance,
  19749. updatable: updatable
  19750. };
  19751. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  19752. };
  19753. /**
  19754. * Creates an custom extruded shape mesh.
  19755. * 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.
  19756. * Please consider using the same method from the MeshBuilder class instead.
  19757. *
  19758. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19759. * 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
  19760. * extruded along the Z axis.
  19761. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19762. * 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
  19763. * and the distance of this point from the begining of the path :
  19764. * ```javascript
  19765. * var rotationFunction = function(i, distance) {
  19766. * // do things
  19767. * return rotationValue; }
  19768. * ```
  19769. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  19770. * 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
  19771. * and the distance of this point from the begining of the path :
  19772. * ```javascript
  19773. * var scaleFunction = function(i, distance) {
  19774. * // do things
  19775. * return scaleValue;}
  19776. * ```
  19777. * It must returns a float value that will be the scale value applied to the shape on each path point.
  19778. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  19779. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  19780. * 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
  19781. * 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
  19782. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19783. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19784. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19785. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19786. */
  19787. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  19788. var options = {
  19789. shape: shape,
  19790. path: path,
  19791. scaleFunction: scaleFunction,
  19792. rotationFunction: rotationFunction,
  19793. ribbonCloseArray: ribbonCloseArray,
  19794. ribbonClosePath: ribbonClosePath,
  19795. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  19796. sideOrientation: sideOrientation,
  19797. instance: instance,
  19798. updatable: updatable
  19799. };
  19800. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  19801. };
  19802. /**
  19803. * Creates lathe mesh.
  19804. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  19805. * Please consider using the same method from the MeshBuilder class instead.
  19806. * 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
  19807. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  19808. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  19809. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  19810. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19811. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19812. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19813. */
  19814. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  19815. var options = {
  19816. shape: shape,
  19817. radius: radius,
  19818. tessellation: tessellation,
  19819. sideOrientation: sideOrientation,
  19820. updatable: updatable
  19821. };
  19822. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  19823. };
  19824. /**
  19825. * Creates a plane mesh.
  19826. * Please consider using the same method from the MeshBuilder class instead.
  19827. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  19828. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19829. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19830. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19831. */
  19832. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  19833. var options = {
  19834. size: size,
  19835. width: size,
  19836. height: size,
  19837. sideOrientation: sideOrientation,
  19838. updatable: updatable
  19839. };
  19840. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  19841. };
  19842. /**
  19843. * Creates a ground mesh.
  19844. * Please consider using the same method from the MeshBuilder class instead.
  19845. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  19846. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  19847. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19848. */
  19849. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  19850. var options = {
  19851. width: width,
  19852. height: height,
  19853. subdivisions: subdivisions,
  19854. updatable: updatable
  19855. };
  19856. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  19857. };
  19858. /**
  19859. * Creates a tiled ground mesh.
  19860. * Please consider using the same method from the MeshBuilder class instead.
  19861. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  19862. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  19863. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  19864. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  19865. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  19866. * numbers of subdivisions on the ground width and height of each tile.
  19867. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19868. */
  19869. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  19870. var options = {
  19871. xmin: xmin,
  19872. zmin: zmin,
  19873. xmax: xmax,
  19874. zmax: zmax,
  19875. subdivisions: subdivisions,
  19876. precision: precision,
  19877. updatable: updatable
  19878. };
  19879. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  19880. };
  19881. /**
  19882. * Creates a ground mesh from a height map.
  19883. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  19884. * Please consider using the same method from the MeshBuilder class instead.
  19885. * The parameter `url` sets the URL of the height map image resource.
  19886. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  19887. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  19888. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  19889. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  19890. * 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).
  19891. * This function is passed the newly built mesh :
  19892. * ```javascript
  19893. * function(mesh) { // do things
  19894. * return; }
  19895. * ```
  19896. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19897. */
  19898. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  19899. var options = {
  19900. width: width,
  19901. height: height,
  19902. subdivisions: subdivisions,
  19903. minHeight: minHeight,
  19904. maxHeight: maxHeight,
  19905. updatable: updatable,
  19906. onReady: onReady
  19907. };
  19908. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  19909. };
  19910. /**
  19911. * Creates a tube mesh.
  19912. * 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.
  19913. * Please consider using the same method from the MeshBuilder class instead.
  19914. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  19915. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  19916. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  19917. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  19918. * 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.
  19919. * It must return a radius value (positive float) :
  19920. * ```javascript
  19921. * var radiusFunction = function(i, distance) {
  19922. * // do things
  19923. * return radius; }
  19924. * ```
  19925. * 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
  19926. * 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
  19927. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19928. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19929. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19930. */
  19931. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  19932. var options = {
  19933. path: path,
  19934. radius: radius,
  19935. tessellation: tessellation,
  19936. radiusFunction: radiusFunction,
  19937. arc: 1,
  19938. cap: cap,
  19939. updatable: updatable,
  19940. sideOrientation: sideOrientation,
  19941. instance: instance
  19942. };
  19943. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  19944. };
  19945. /**
  19946. * Creates a polyhedron mesh.
  19947. * Please consider using the same method from the MeshBuilder class instead.
  19948. * 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
  19949. * to choose the wanted type.
  19950. * The parameter `size` (positive float, default 1) sets the polygon size.
  19951. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  19952. * 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`.
  19953. * 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
  19954. * 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)`).
  19955. * 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
  19956. * 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.
  19957. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19958. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19959. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19960. */
  19961. Mesh.CreatePolyhedron = function (name, options, scene) {
  19962. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  19963. };
  19964. /**
  19965. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  19966. * Please consider using the same method from the MeshBuilder class instead.
  19967. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  19968. * 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`).
  19969. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  19970. * 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.
  19971. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19972. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19973. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19974. */
  19975. Mesh.CreateIcoSphere = function (name, options, scene) {
  19976. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  19977. };
  19978. /**
  19979. * Creates a decal mesh.
  19980. * Please consider using the same method from the MeshBuilder class instead.
  19981. * 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.
  19982. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  19983. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  19984. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  19985. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  19986. */
  19987. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  19988. var options = {
  19989. position: position,
  19990. normal: normal,
  19991. size: size,
  19992. angle: angle
  19993. };
  19994. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  19995. };
  19996. // Skeletons
  19997. /**
  19998. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  19999. */
  20000. Mesh.prototype.setPositionsForCPUSkinning = function () {
  20001. var source;
  20002. if (!this._sourcePositions) {
  20003. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20004. this._sourcePositions = new Float32Array(source);
  20005. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  20006. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  20007. }
  20008. }
  20009. return this._sourcePositions;
  20010. };
  20011. /**
  20012. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20013. */
  20014. Mesh.prototype.setNormalsForCPUSkinning = function () {
  20015. var source;
  20016. if (!this._sourceNormals) {
  20017. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20018. this._sourceNormals = new Float32Array(source);
  20019. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  20020. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  20021. }
  20022. }
  20023. return this._sourceNormals;
  20024. };
  20025. /**
  20026. * Update the vertex buffers by applying transformation from the bones
  20027. * @param {skeleton} skeleton to apply
  20028. */
  20029. Mesh.prototype.applySkeleton = function (skeleton) {
  20030. if (!this.geometry) {
  20031. return;
  20032. }
  20033. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  20034. return;
  20035. }
  20036. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  20037. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20038. return this;
  20039. }
  20040. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20041. return this;
  20042. }
  20043. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20044. return this;
  20045. }
  20046. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20047. return this;
  20048. }
  20049. if (!this._sourcePositions) {
  20050. this.setPositionsForCPUSkinning();
  20051. }
  20052. if (!this._sourceNormals) {
  20053. this.setNormalsForCPUSkinning();
  20054. }
  20055. // positionsData checks for not being Float32Array will only pass at most once
  20056. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20057. if (!(positionsData instanceof Float32Array)) {
  20058. positionsData = new Float32Array(positionsData);
  20059. }
  20060. // normalsData checks for not being Float32Array will only pass at most once
  20061. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20062. if (!(normalsData instanceof Float32Array)) {
  20063. normalsData = new Float32Array(normalsData);
  20064. }
  20065. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20066. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20067. var needExtras = this.numBoneInfluencers > 4;
  20068. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  20069. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  20070. var skeletonMatrices = skeleton.getTransformMatrices(this);
  20071. var tempVector3 = BABYLON.Vector3.Zero();
  20072. var finalMatrix = new BABYLON.Matrix();
  20073. var tempMatrix = new BABYLON.Matrix();
  20074. var matWeightIdx = 0;
  20075. var inf;
  20076. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  20077. var weight;
  20078. for (inf = 0; inf < 4; inf++) {
  20079. weight = matricesWeightsData[matWeightIdx + inf];
  20080. if (weight > 0) {
  20081. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20082. finalMatrix.addToSelf(tempMatrix);
  20083. }
  20084. else
  20085. break;
  20086. }
  20087. if (needExtras) {
  20088. for (inf = 0; inf < 4; inf++) {
  20089. weight = matricesWeightsExtraData[matWeightIdx + inf];
  20090. if (weight > 0) {
  20091. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20092. finalMatrix.addToSelf(tempMatrix);
  20093. }
  20094. else
  20095. break;
  20096. }
  20097. }
  20098. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  20099. tempVector3.toArray(positionsData, index);
  20100. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  20101. tempVector3.toArray(normalsData, index);
  20102. finalMatrix.reset();
  20103. }
  20104. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  20105. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  20106. return this;
  20107. };
  20108. // Tools
  20109. /**
  20110. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  20111. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  20112. */
  20113. Mesh.MinMax = function (meshes) {
  20114. var minVector = null;
  20115. var maxVector = null;
  20116. for (var i in meshes) {
  20117. var mesh = meshes[i];
  20118. var boundingBox = mesh.getBoundingInfo().boundingBox;
  20119. if (!minVector) {
  20120. minVector = boundingBox.minimumWorld;
  20121. maxVector = boundingBox.maximumWorld;
  20122. continue;
  20123. }
  20124. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  20125. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  20126. }
  20127. return {
  20128. min: minVector,
  20129. max: maxVector
  20130. };
  20131. };
  20132. /**
  20133. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  20134. */
  20135. Mesh.Center = function (meshesOrMinMaxVector) {
  20136. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  20137. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  20138. };
  20139. /**
  20140. * Merge the array of meshes into a single mesh for performance reasons.
  20141. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  20142. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  20143. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  20144. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  20145. */
  20146. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  20147. if (disposeSource === void 0) { disposeSource = true; }
  20148. var index;
  20149. if (!allow32BitsIndices) {
  20150. var totalVertices = 0;
  20151. // Counting vertices
  20152. for (index = 0; index < meshes.length; index++) {
  20153. if (meshes[index]) {
  20154. totalVertices += meshes[index].getTotalVertices();
  20155. if (totalVertices > 65536) {
  20156. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  20157. return null;
  20158. }
  20159. }
  20160. }
  20161. }
  20162. // Merge
  20163. var vertexData;
  20164. var otherVertexData;
  20165. var source;
  20166. for (index = 0; index < meshes.length; index++) {
  20167. if (meshes[index]) {
  20168. meshes[index].computeWorldMatrix(true);
  20169. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  20170. otherVertexData.transform(meshes[index].getWorldMatrix());
  20171. if (vertexData) {
  20172. vertexData.merge(otherVertexData);
  20173. }
  20174. else {
  20175. vertexData = otherVertexData;
  20176. source = meshes[index];
  20177. }
  20178. }
  20179. }
  20180. if (!meshSubclass) {
  20181. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  20182. }
  20183. vertexData.applyToMesh(meshSubclass);
  20184. // Setting properties
  20185. meshSubclass.material = source.material;
  20186. meshSubclass.checkCollisions = source.checkCollisions;
  20187. // Cleaning
  20188. if (disposeSource) {
  20189. for (index = 0; index < meshes.length; index++) {
  20190. if (meshes[index]) {
  20191. meshes[index].dispose();
  20192. }
  20193. }
  20194. }
  20195. return meshSubclass;
  20196. };
  20197. // Consts
  20198. Mesh._FRONTSIDE = 0;
  20199. Mesh._BACKSIDE = 1;
  20200. Mesh._DOUBLESIDE = 2;
  20201. Mesh._DEFAULTSIDE = 0;
  20202. Mesh._NO_CAP = 0;
  20203. Mesh._CAP_START = 1;
  20204. Mesh._CAP_END = 2;
  20205. Mesh._CAP_ALL = 3;
  20206. return Mesh;
  20207. }(BABYLON.AbstractMesh));
  20208. BABYLON.Mesh = Mesh;
  20209. })(BABYLON || (BABYLON = {}));
  20210. var BABYLON;
  20211. (function (BABYLON) {
  20212. var SubMesh = (function () {
  20213. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  20214. if (createBoundingBox === void 0) { createBoundingBox = true; }
  20215. this.materialIndex = materialIndex;
  20216. this.verticesStart = verticesStart;
  20217. this.verticesCount = verticesCount;
  20218. this.indexStart = indexStart;
  20219. this.indexCount = indexCount;
  20220. this._renderId = 0;
  20221. this._mesh = mesh;
  20222. this._renderingMesh = renderingMesh || mesh;
  20223. mesh.subMeshes.push(this);
  20224. this._trianglePlanes = [];
  20225. this._id = mesh.subMeshes.length - 1;
  20226. if (createBoundingBox) {
  20227. this.refreshBoundingInfo();
  20228. mesh.computeWorldMatrix(true);
  20229. }
  20230. }
  20231. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  20232. get: function () {
  20233. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  20234. },
  20235. enumerable: true,
  20236. configurable: true
  20237. });
  20238. SubMesh.prototype.getBoundingInfo = function () {
  20239. if (this.IsGlobal) {
  20240. return this._mesh.getBoundingInfo();
  20241. }
  20242. return this._boundingInfo;
  20243. };
  20244. SubMesh.prototype.getMesh = function () {
  20245. return this._mesh;
  20246. };
  20247. SubMesh.prototype.getRenderingMesh = function () {
  20248. return this._renderingMesh;
  20249. };
  20250. SubMesh.prototype.getMaterial = function () {
  20251. var rootMaterial = this._renderingMesh.material;
  20252. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  20253. var multiMaterial = rootMaterial;
  20254. return multiMaterial.getSubMaterial(this.materialIndex);
  20255. }
  20256. if (!rootMaterial) {
  20257. return this._mesh.getScene().defaultMaterial;
  20258. }
  20259. return rootMaterial;
  20260. };
  20261. // Methods
  20262. SubMesh.prototype.refreshBoundingInfo = function () {
  20263. this._lastColliderWorldVertices = null;
  20264. if (this.IsGlobal) {
  20265. return;
  20266. }
  20267. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20268. if (!data) {
  20269. this._boundingInfo = this._mesh._boundingInfo;
  20270. return;
  20271. }
  20272. var indices = this._renderingMesh.getIndices();
  20273. var extend;
  20274. //is this the only submesh?
  20275. if (this.indexStart === 0 && this.indexCount === indices.length) {
  20276. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  20277. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  20278. }
  20279. else {
  20280. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  20281. }
  20282. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20283. };
  20284. SubMesh.prototype._checkCollision = function (collider) {
  20285. return this.getBoundingInfo()._checkCollision(collider);
  20286. };
  20287. SubMesh.prototype.updateBoundingInfo = function (world) {
  20288. if (!this.getBoundingInfo()) {
  20289. this.refreshBoundingInfo();
  20290. }
  20291. this.getBoundingInfo().update(world);
  20292. };
  20293. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  20294. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  20295. };
  20296. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20297. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  20298. };
  20299. SubMesh.prototype.render = function (enableAlphaMode) {
  20300. this._renderingMesh.render(this, enableAlphaMode);
  20301. };
  20302. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  20303. if (!this._linesIndexBuffer) {
  20304. var linesIndices = [];
  20305. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  20306. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  20307. }
  20308. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  20309. this.linesIndexCount = linesIndices.length;
  20310. }
  20311. return this._linesIndexBuffer;
  20312. };
  20313. SubMesh.prototype.canIntersects = function (ray) {
  20314. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  20315. };
  20316. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  20317. var intersectInfo = null;
  20318. // LineMesh first as it's also a Mesh...
  20319. if (this._mesh instanceof BABYLON.LinesMesh) {
  20320. var lineMesh = this._mesh;
  20321. // Line test
  20322. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  20323. var p0 = positions[indices[index]];
  20324. var p1 = positions[indices[index + 1]];
  20325. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  20326. if (length < 0) {
  20327. continue;
  20328. }
  20329. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  20330. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  20331. if (fastCheck) {
  20332. break;
  20333. }
  20334. }
  20335. }
  20336. }
  20337. else {
  20338. // Triangles test
  20339. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  20340. var p0 = positions[indices[index]];
  20341. var p1 = positions[indices[index + 1]];
  20342. var p2 = positions[indices[index + 2]];
  20343. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  20344. if (currentIntersectInfo) {
  20345. if (currentIntersectInfo.distance < 0) {
  20346. continue;
  20347. }
  20348. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20349. intersectInfo = currentIntersectInfo;
  20350. intersectInfo.faceId = index / 3;
  20351. if (fastCheck) {
  20352. break;
  20353. }
  20354. }
  20355. }
  20356. }
  20357. }
  20358. return intersectInfo;
  20359. };
  20360. // Clone
  20361. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  20362. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  20363. if (!this.IsGlobal) {
  20364. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  20365. }
  20366. return result;
  20367. };
  20368. // Dispose
  20369. SubMesh.prototype.dispose = function () {
  20370. if (this._linesIndexBuffer) {
  20371. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  20372. this._linesIndexBuffer = null;
  20373. }
  20374. // Remove from mesh
  20375. var index = this._mesh.subMeshes.indexOf(this);
  20376. this._mesh.subMeshes.splice(index, 1);
  20377. };
  20378. // Statics
  20379. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  20380. var minVertexIndex = Number.MAX_VALUE;
  20381. var maxVertexIndex = -Number.MAX_VALUE;
  20382. renderingMesh = renderingMesh || mesh;
  20383. var indices = renderingMesh.getIndices();
  20384. for (var index = startIndex; index < startIndex + indexCount; index++) {
  20385. var vertexIndex = indices[index];
  20386. if (vertexIndex < minVertexIndex)
  20387. minVertexIndex = vertexIndex;
  20388. if (vertexIndex > maxVertexIndex)
  20389. maxVertexIndex = vertexIndex;
  20390. }
  20391. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  20392. };
  20393. return SubMesh;
  20394. }());
  20395. BABYLON.SubMesh = SubMesh;
  20396. })(BABYLON || (BABYLON = {}));
  20397. var BABYLON;
  20398. (function (BABYLON) {
  20399. var MeshBuilder = (function () {
  20400. function MeshBuilder() {
  20401. }
  20402. /**
  20403. * Creates a box mesh.
  20404. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  20405. * The parameter `size` sets the size (float) of each box side (default 1).
  20406. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  20407. * 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).
  20408. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  20409. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20410. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20411. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20412. */
  20413. MeshBuilder.CreateBox = function (name, options, scene) {
  20414. var box = new BABYLON.Mesh(name, scene);
  20415. var vertexData = BABYLON.VertexData.CreateBox(options);
  20416. vertexData.applyToMesh(box, options.updatable);
  20417. return box;
  20418. };
  20419. /**
  20420. * Creates a sphere mesh.
  20421. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  20422. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20423. * 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`).
  20424. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20425. * 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
  20426. * 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).
  20427. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20428. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20429. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20430. */
  20431. MeshBuilder.CreateSphere = function (name, options, scene) {
  20432. var sphere = new BABYLON.Mesh(name, scene);
  20433. var vertexData = BABYLON.VertexData.CreateSphere(options);
  20434. vertexData.applyToMesh(sphere, options.updatable);
  20435. return sphere;
  20436. };
  20437. /**
  20438. * Creates a plane polygonal mesh. By default, this is a disc.
  20439. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  20440. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20441. * 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.
  20442. * 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
  20443. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20444. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20445. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20446. */
  20447. MeshBuilder.CreateDisc = function (name, options, scene) {
  20448. var disc = new BABYLON.Mesh(name, scene);
  20449. var vertexData = BABYLON.VertexData.CreateDisc(options);
  20450. vertexData.applyToMesh(disc, options.updatable);
  20451. return disc;
  20452. };
  20453. /**
  20454. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  20455. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  20456. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  20457. * 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`).
  20458. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  20459. * 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.
  20460. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20461. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20462. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20463. */
  20464. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  20465. var sphere = new BABYLON.Mesh(name, scene);
  20466. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  20467. vertexData.applyToMesh(sphere, options.updatable);
  20468. return sphere;
  20469. };
  20470. ;
  20471. /**
  20472. * Creates a ribbon mesh.
  20473. * 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.
  20474. *
  20475. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20476. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20477. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20478. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20479. * 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.
  20480. * 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.
  20481. * 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
  20482. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20483. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20484. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  20485. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20486. */
  20487. MeshBuilder.CreateRibbon = function (name, options, scene) {
  20488. var pathArray = options.pathArray;
  20489. var closeArray = options.closeArray;
  20490. var closePath = options.closePath;
  20491. var offset = options.offset;
  20492. var sideOrientation = options.sideOrientation;
  20493. var instance = options.instance;
  20494. var updatable = options.updatable;
  20495. if (instance) {
  20496. // positionFunction : ribbon case
  20497. // only pathArray and sideOrientation parameters are taken into account for positions update
  20498. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  20499. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  20500. var positionFunction = function (positions) {
  20501. var minlg = pathArray[0].length;
  20502. var i = 0;
  20503. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  20504. for (var si = 1; si <= ns; si++) {
  20505. for (var p = 0; p < pathArray.length; p++) {
  20506. var path = pathArray[p];
  20507. var l = path.length;
  20508. minlg = (minlg < l) ? minlg : l;
  20509. var j = 0;
  20510. while (j < minlg) {
  20511. positions[i] = path[j].x;
  20512. positions[i + 1] = path[j].y;
  20513. positions[i + 2] = path[j].z;
  20514. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  20515. BABYLON.Tmp.Vector3[0].x = path[j].x;
  20516. }
  20517. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  20518. BABYLON.Tmp.Vector3[1].x = path[j].x;
  20519. }
  20520. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  20521. BABYLON.Tmp.Vector3[0].y = path[j].y;
  20522. }
  20523. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  20524. BABYLON.Tmp.Vector3[1].y = path[j].y;
  20525. }
  20526. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  20527. BABYLON.Tmp.Vector3[0].z = path[j].z;
  20528. }
  20529. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  20530. BABYLON.Tmp.Vector3[1].z = path[j].z;
  20531. }
  20532. j++;
  20533. i += 3;
  20534. }
  20535. if (instance._closePath) {
  20536. positions[i] = path[0].x;
  20537. positions[i + 1] = path[0].y;
  20538. positions[i + 2] = path[0].z;
  20539. i += 3;
  20540. }
  20541. }
  20542. }
  20543. };
  20544. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20545. positionFunction(positions);
  20546. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  20547. instance._boundingInfo.update(instance._worldMatrix);
  20548. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20549. if (!(instance.areNormalsFrozen)) {
  20550. var indices = instance.getIndices();
  20551. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20552. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20553. if (instance._closePath) {
  20554. var indexFirst = 0;
  20555. var indexLast = 0;
  20556. for (var p = 0; p < pathArray.length; p++) {
  20557. indexFirst = instance._idx[p] * 3;
  20558. if (p + 1 < pathArray.length) {
  20559. indexLast = (instance._idx[p + 1] - 1) * 3;
  20560. }
  20561. else {
  20562. indexLast = normals.length - 3;
  20563. }
  20564. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  20565. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  20566. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  20567. normals[indexLast] = normals[indexFirst];
  20568. normals[indexLast + 1] = normals[indexFirst + 1];
  20569. normals[indexLast + 2] = normals[indexFirst + 2];
  20570. }
  20571. }
  20572. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20573. }
  20574. return instance;
  20575. }
  20576. else {
  20577. var ribbon = new BABYLON.Mesh(name, scene);
  20578. ribbon.sideOrientation = sideOrientation;
  20579. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  20580. if (closePath) {
  20581. ribbon._idx = vertexData._idx;
  20582. }
  20583. ribbon._closePath = closePath;
  20584. ribbon._closeArray = closeArray;
  20585. vertexData.applyToMesh(ribbon, updatable);
  20586. return ribbon;
  20587. }
  20588. };
  20589. /**
  20590. * Creates a cylinder or a cone mesh.
  20591. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  20592. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20593. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20594. * 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.
  20595. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20596. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20597. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  20598. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  20599. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  20600. * 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).
  20601. * 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
  20602. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  20603. * 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
  20604. * 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.
  20605. * If `enclose` is false, a ring surface is one element.
  20606. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  20607. * 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
  20608. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20609. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20610. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20611. */
  20612. MeshBuilder.CreateCylinder = function (name, options, scene) {
  20613. var cylinder = new BABYLON.Mesh(name, scene);
  20614. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  20615. vertexData.applyToMesh(cylinder, options.updatable);
  20616. return cylinder;
  20617. };
  20618. /**
  20619. * Creates a torus mesh.
  20620. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  20621. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  20622. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  20623. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  20624. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20625. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20626. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20627. */
  20628. MeshBuilder.CreateTorus = function (name, options, scene) {
  20629. var torus = new BABYLON.Mesh(name, scene);
  20630. var vertexData = BABYLON.VertexData.CreateTorus(options);
  20631. vertexData.applyToMesh(torus, options.updatable);
  20632. return torus;
  20633. };
  20634. /**
  20635. * Creates a torus knot mesh.
  20636. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  20637. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  20638. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  20639. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  20640. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  20641. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20642. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20643. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20644. */
  20645. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  20646. var torusKnot = new BABYLON.Mesh(name, scene);
  20647. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  20648. vertexData.applyToMesh(torusKnot, options.updatable);
  20649. return torusKnot;
  20650. };
  20651. /**
  20652. * Creates a line system mesh.
  20653. * A line system is a pool of many lines gathered in a single mesh.
  20654. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  20655. * 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.
  20656. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  20657. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  20658. * 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
  20659. * 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
  20660. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  20661. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20662. */
  20663. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  20664. var instance = options.instance;
  20665. var lines = options.lines;
  20666. if (instance) {
  20667. var positionFunction = function (positions) {
  20668. var i = 0;
  20669. for (var l = 0; l < lines.length; l++) {
  20670. var points = lines[l];
  20671. for (var p = 0; p < points.length; p++) {
  20672. positions[i] = points[p].x;
  20673. positions[i + 1] = points[p].y;
  20674. positions[i + 2] = points[p].z;
  20675. i += 3;
  20676. }
  20677. }
  20678. };
  20679. instance.updateMeshPositions(positionFunction, false);
  20680. return instance;
  20681. }
  20682. // line system creation
  20683. var lineSystem = new BABYLON.LinesMesh(name, scene);
  20684. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  20685. vertexData.applyToMesh(lineSystem, options.updatable);
  20686. return lineSystem;
  20687. };
  20688. /**
  20689. * Creates a line mesh.
  20690. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  20691. * 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.
  20692. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20693. * The parameter `points` is an array successive Vector3.
  20694. * 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
  20695. * When updating an instance, remember that only point positions can change, not the number of points.
  20696. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20697. */
  20698. MeshBuilder.CreateLines = function (name, options, scene) {
  20699. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  20700. return lines;
  20701. };
  20702. /**
  20703. * Creates a dashed line mesh.
  20704. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  20705. * 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.
  20706. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20707. * The parameter `points` is an array successive Vector3.
  20708. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  20709. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  20710. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  20711. * 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
  20712. * When updating an instance, remember that only point positions can change, not the number of points.
  20713. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20714. */
  20715. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  20716. var points = options.points;
  20717. var instance = options.instance;
  20718. var gapSize = options.gapSize;
  20719. var dashNb = options.dashNb;
  20720. var dashSize = options.dashSize;
  20721. if (instance) {
  20722. var positionFunction = function (positions) {
  20723. var curvect = BABYLON.Vector3.Zero();
  20724. var nbSeg = positions.length / 6;
  20725. var lg = 0;
  20726. var nb = 0;
  20727. var shft = 0;
  20728. var dashshft = 0;
  20729. var curshft = 0;
  20730. var p = 0;
  20731. var i = 0;
  20732. var j = 0;
  20733. for (i = 0; i < points.length - 1; i++) {
  20734. points[i + 1].subtractToRef(points[i], curvect);
  20735. lg += curvect.length();
  20736. }
  20737. shft = lg / nbSeg;
  20738. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  20739. for (i = 0; i < points.length - 1; i++) {
  20740. points[i + 1].subtractToRef(points[i], curvect);
  20741. nb = Math.floor(curvect.length() / shft);
  20742. curvect.normalize();
  20743. j = 0;
  20744. while (j < nb && p < positions.length) {
  20745. curshft = shft * j;
  20746. positions[p] = points[i].x + curshft * curvect.x;
  20747. positions[p + 1] = points[i].y + curshft * curvect.y;
  20748. positions[p + 2] = points[i].z + curshft * curvect.z;
  20749. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  20750. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  20751. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  20752. p += 6;
  20753. j++;
  20754. }
  20755. }
  20756. while (p < positions.length) {
  20757. positions[p] = points[i].x;
  20758. positions[p + 1] = points[i].y;
  20759. positions[p + 2] = points[i].z;
  20760. p += 3;
  20761. }
  20762. };
  20763. instance.updateMeshPositions(positionFunction, false);
  20764. return instance;
  20765. }
  20766. // dashed lines creation
  20767. var dashedLines = new BABYLON.LinesMesh(name, scene);
  20768. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  20769. vertexData.applyToMesh(dashedLines, options.updatable);
  20770. dashedLines.dashSize = dashSize;
  20771. dashedLines.gapSize = gapSize;
  20772. return dashedLines;
  20773. };
  20774. /**
  20775. * Creates an extruded shape mesh.
  20776. * 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.
  20777. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  20778. *
  20779. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20780. * 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
  20781. * extruded along the Z axis.
  20782. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20783. * 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.
  20784. * The parameter `scale` (float, default 1) is the value to scale the shape.
  20785. * 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
  20786. * 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
  20787. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20788. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20789. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20790. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  20791. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20792. */
  20793. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  20794. var path = options.path;
  20795. var shape = options.shape;
  20796. var scale = options.scale || 1;
  20797. var rotation = options.rotation || 0;
  20798. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  20799. var updatable = options.updatable;
  20800. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20801. var instance = options.instance;
  20802. var invertUV = options.invertUV || false;
  20803. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  20804. };
  20805. /**
  20806. * Creates an custom extruded shape mesh.
  20807. * 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.
  20808. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  20809. *
  20810. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20811. * 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
  20812. * extruded along the Z axis.
  20813. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20814. * 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
  20815. * and the distance of this point from the begining of the path :
  20816. * ```javascript
  20817. * var rotationFunction = function(i, distance) {
  20818. * // do things
  20819. * return rotationValue; }
  20820. * ```
  20821. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  20822. * 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
  20823. * and the distance of this point from the begining of the path :
  20824. * ```javascript
  20825. * var scaleFunction = function(i, distance) {
  20826. * // do things
  20827. * return scaleValue;}
  20828. * ```
  20829. * It must returns a float value that will be the scale value applied to the shape on each path point.
  20830. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  20831. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  20832. * 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
  20833. * 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
  20834. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20835. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20836. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20837. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  20838. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20839. */
  20840. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  20841. var path = options.path;
  20842. var shape = options.shape;
  20843. var scaleFunction = options.scaleFunction || (function () { return 1; });
  20844. var rotationFunction = options.rotationFunction || (function () { return 0; });
  20845. var ribbonCloseArray = options.ribbonCloseArray || false;
  20846. var ribbonClosePath = options.ribbonClosePath || false;
  20847. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  20848. var updatable = options.updatable;
  20849. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20850. var instance = options.instance;
  20851. var invertUV = options.invertUV || false;
  20852. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  20853. };
  20854. /**
  20855. * Creates lathe mesh.
  20856. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  20857. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  20858. *
  20859. * 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
  20860. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  20861. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  20862. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  20863. * 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.
  20864. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  20865. * 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
  20866. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20867. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20868. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  20869. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20870. */
  20871. MeshBuilder.CreateLathe = function (name, options, scene) {
  20872. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  20873. var closed = (options.closed === undefined) ? true : options.closed;
  20874. var shape = options.shape;
  20875. var radius = options.radius || 1;
  20876. var tessellation = options.tessellation || 64;
  20877. var updatable = options.updatable;
  20878. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20879. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  20880. var pi2 = Math.PI * 2;
  20881. var paths = new Array();
  20882. var invertUV = options.invertUV || false;
  20883. var i = 0;
  20884. var p = 0;
  20885. var step = pi2 / tessellation * arc;
  20886. var rotated;
  20887. var path = new Array();
  20888. ;
  20889. for (i = 0; i <= tessellation; i++) {
  20890. var path = [];
  20891. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  20892. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  20893. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  20894. }
  20895. for (p = 0; p < shape.length; p++) {
  20896. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  20897. path.push(rotated);
  20898. }
  20899. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  20900. 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));
  20901. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  20902. }
  20903. paths.push(path);
  20904. }
  20905. // lathe ribbon
  20906. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  20907. return lathe;
  20908. };
  20909. /**
  20910. * Creates a plane mesh.
  20911. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  20912. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  20913. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  20914. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  20915. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20916. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20917. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20918. */
  20919. MeshBuilder.CreatePlane = function (name, options, scene) {
  20920. var plane = new BABYLON.Mesh(name, scene);
  20921. var vertexData = BABYLON.VertexData.CreatePlane(options);
  20922. vertexData.applyToMesh(plane, options.updatable);
  20923. if (options.sourcePlane) {
  20924. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  20925. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  20926. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  20927. plane.rotate(vectorProduct, product);
  20928. }
  20929. return plane;
  20930. };
  20931. /**
  20932. * Creates a ground mesh.
  20933. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  20934. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  20935. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  20936. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20937. */
  20938. MeshBuilder.CreateGround = function (name, options, scene) {
  20939. var ground = new BABYLON.GroundMesh(name, scene);
  20940. ground._setReady(false);
  20941. ground._subdivisions = options.subdivisions || 1;
  20942. ground._width = options.width || 1;
  20943. ground._height = options.height || 1;
  20944. ground._maxX = ground._width / 2;
  20945. ground._maxZ = ground._height / 2;
  20946. ground._minX = -ground._maxX;
  20947. ground._minZ = -ground._maxZ;
  20948. var vertexData = BABYLON.VertexData.CreateGround(options);
  20949. vertexData.applyToMesh(ground, options.updatable);
  20950. ground._setReady(true);
  20951. return ground;
  20952. };
  20953. /**
  20954. * Creates a tiled ground mesh.
  20955. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  20956. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  20957. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  20958. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  20959. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  20960. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  20961. * numbers of subdivisions on the ground width and height of each tile.
  20962. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20963. */
  20964. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  20965. var tiledGround = new BABYLON.Mesh(name, scene);
  20966. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  20967. vertexData.applyToMesh(tiledGround, options.updatable);
  20968. return tiledGround;
  20969. };
  20970. /**
  20971. * Creates a ground mesh from a height map.
  20972. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  20973. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  20974. * The parameter `url` sets the URL of the height map image resource.
  20975. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  20976. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  20977. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  20978. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  20979. * 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).
  20980. * This function is passed the newly built mesh :
  20981. * ```javascript
  20982. * function(mesh) { // do things
  20983. * return; }
  20984. * ```
  20985. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20986. */
  20987. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  20988. var width = options.width || 10.0;
  20989. var height = options.height || 10.0;
  20990. var subdivisions = options.subdivisions || 1 | 0;
  20991. var minHeight = options.minHeight || 0.0;
  20992. var maxHeight = options.maxHeight || 10.0;
  20993. var updatable = options.updatable;
  20994. var onReady = options.onReady;
  20995. var ground = new BABYLON.GroundMesh(name, scene);
  20996. ground._subdivisions = subdivisions;
  20997. ground._width = width;
  20998. ground._height = height;
  20999. ground._maxX = ground._width / 2.0;
  21000. ground._maxZ = ground._height / 2.0;
  21001. ground._minX = -ground._maxX;
  21002. ground._minZ = -ground._maxZ;
  21003. ground._setReady(false);
  21004. var onload = function (img) {
  21005. // Getting height map data
  21006. var canvas = document.createElement("canvas");
  21007. var context = canvas.getContext("2d");
  21008. var bufferWidth = img.width;
  21009. var bufferHeight = img.height;
  21010. canvas.width = bufferWidth;
  21011. canvas.height = bufferHeight;
  21012. context.drawImage(img, 0, 0);
  21013. // Create VertexData from map data
  21014. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  21015. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  21016. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  21017. width: width, height: height,
  21018. subdivisions: subdivisions,
  21019. minHeight: minHeight, maxHeight: maxHeight,
  21020. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  21021. });
  21022. vertexData.applyToMesh(ground, updatable);
  21023. ground._setReady(true);
  21024. //execute ready callback, if set
  21025. if (onReady) {
  21026. onReady(ground);
  21027. }
  21028. };
  21029. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  21030. return ground;
  21031. };
  21032. /**
  21033. * Creates a tube mesh.
  21034. * 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.
  21035. *
  21036. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  21037. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21038. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21039. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21040. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21041. * 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.
  21042. * It must return a radius value (positive float) :
  21043. * ```javascript
  21044. * var radiusFunction = function(i, distance) {
  21045. * // do things
  21046. * return radius; }
  21047. * ```
  21048. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  21049. * 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
  21050. * 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
  21051. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21052. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21053. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21054. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21055. */
  21056. MeshBuilder.CreateTube = function (name, options, scene) {
  21057. var path = options.path;
  21058. var radius = options.radius || 1.0;
  21059. var tessellation = options.tessellation || 64 | 0;
  21060. var radiusFunction = options.radiusFunction;
  21061. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  21062. var invertUV = options.invertUV || false;
  21063. var updatable = options.updatable;
  21064. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  21065. var instance = options.instance;
  21066. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  21067. // tube geometry
  21068. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  21069. var tangents = path3D.getTangents();
  21070. var normals = path3D.getNormals();
  21071. var distances = path3D.getDistances();
  21072. var pi2 = Math.PI * 2;
  21073. var step = pi2 / tessellation * arc;
  21074. var returnRadius = function () { return radius; };
  21075. var radiusFunctionFinal = radiusFunction || returnRadius;
  21076. var circlePath;
  21077. var rad;
  21078. var normal;
  21079. var rotated;
  21080. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  21081. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  21082. for (var i = 0; i < path.length; i++) {
  21083. rad = radiusFunctionFinal(i, distances[i]); // current radius
  21084. circlePath = Array(); // current circle array
  21085. normal = normals[i]; // current normal
  21086. for (var t = 0; t < tessellation; t++) {
  21087. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  21088. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  21089. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  21090. rotated.scaleInPlace(rad).addInPlace(path[i]);
  21091. circlePath[t] = rotated;
  21092. }
  21093. circlePaths[index] = circlePath;
  21094. index++;
  21095. }
  21096. // cap
  21097. var capPath = function (nbPoints, pathIndex) {
  21098. var pointCap = Array();
  21099. for (var i = 0; i < nbPoints; i++) {
  21100. pointCap.push(path[pathIndex]);
  21101. }
  21102. return pointCap;
  21103. };
  21104. switch (cap) {
  21105. case BABYLON.Mesh.NO_CAP:
  21106. break;
  21107. case BABYLON.Mesh.CAP_START:
  21108. circlePaths[0] = capPath(tessellation, 0);
  21109. circlePaths[1] = circlePaths[2].slice(0);
  21110. break;
  21111. case BABYLON.Mesh.CAP_END:
  21112. circlePaths[index] = circlePaths[index - 1].slice(0);
  21113. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  21114. break;
  21115. case BABYLON.Mesh.CAP_ALL:
  21116. circlePaths[0] = capPath(tessellation, 0);
  21117. circlePaths[1] = circlePaths[2].slice(0);
  21118. circlePaths[index] = circlePaths[index - 1].slice(0);
  21119. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  21120. break;
  21121. default:
  21122. break;
  21123. }
  21124. return circlePaths;
  21125. };
  21126. var path3D;
  21127. var pathArray;
  21128. if (instance) {
  21129. var arc = options.arc || instance.arc;
  21130. path3D = (instance.path3D).update(path);
  21131. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  21132. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  21133. instance.path3D = path3D;
  21134. instance.pathArray = pathArray;
  21135. instance.arc = arc;
  21136. return instance;
  21137. }
  21138. // tube creation
  21139. path3D = new BABYLON.Path3D(path);
  21140. var newPathArray = new Array();
  21141. cap = (cap < 0 || cap > 3) ? 0 : cap;
  21142. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  21143. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  21144. tube.pathArray = pathArray;
  21145. tube.path3D = path3D;
  21146. tube.tessellation = tessellation;
  21147. tube.cap = cap;
  21148. tube.arc = options.arc;
  21149. return tube;
  21150. };
  21151. /**
  21152. * Creates a polyhedron mesh.
  21153. *
  21154. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  21155. * 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
  21156. * to choose the wanted type.
  21157. * The parameter `size` (positive float, default 1) sets the polygon size.
  21158. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21159. * 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`.
  21160. * 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
  21161. * 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)`).
  21162. * 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
  21163. * 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.
  21164. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21165. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21166. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21167. */
  21168. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  21169. var polyhedron = new BABYLON.Mesh(name, scene);
  21170. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  21171. vertexData.applyToMesh(polyhedron, options.updatable);
  21172. return polyhedron;
  21173. };
  21174. /**
  21175. * Creates a decal mesh.
  21176. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  21177. * 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.
  21178. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21179. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21180. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21181. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21182. */
  21183. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  21184. var indices = sourceMesh.getIndices();
  21185. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21186. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21187. var position = options.position || BABYLON.Vector3.Zero();
  21188. var normal = options.normal || BABYLON.Vector3.Up();
  21189. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  21190. var angle = options.angle || 0;
  21191. // Getting correct rotation
  21192. if (!normal) {
  21193. var target = new BABYLON.Vector3(0, 0, 1);
  21194. var camera = sourceMesh.getScene().activeCamera;
  21195. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  21196. normal = camera.globalPosition.subtract(cameraWorldTarget);
  21197. }
  21198. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  21199. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  21200. var pitch = Math.atan2(normal.y, len);
  21201. // Matrix
  21202. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  21203. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  21204. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  21205. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  21206. var vertexData = new BABYLON.VertexData();
  21207. vertexData.indices = [];
  21208. vertexData.positions = [];
  21209. vertexData.normals = [];
  21210. vertexData.uvs = [];
  21211. var currentVertexDataIndex = 0;
  21212. var extractDecalVector3 = function (indexId) {
  21213. var vertexId = indices[indexId];
  21214. var result = new BABYLON.PositionNormalVertex();
  21215. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  21216. // Send vector to decal local world
  21217. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  21218. // Get normal
  21219. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  21220. return result;
  21221. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  21222. var clip = function (vertices, axis) {
  21223. if (vertices.length === 0) {
  21224. return vertices;
  21225. }
  21226. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  21227. var clipVertices = function (v0, v1) {
  21228. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  21229. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  21230. };
  21231. var result = new Array();
  21232. for (var index = 0; index < vertices.length; index += 3) {
  21233. var v1Out;
  21234. var v2Out;
  21235. var v3Out;
  21236. var total = 0;
  21237. var nV1, nV2, nV3, nV4;
  21238. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  21239. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  21240. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  21241. v1Out = d1 > 0;
  21242. v2Out = d2 > 0;
  21243. v3Out = d3 > 0;
  21244. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  21245. switch (total) {
  21246. case 0:
  21247. result.push(vertices[index]);
  21248. result.push(vertices[index + 1]);
  21249. result.push(vertices[index + 2]);
  21250. break;
  21251. case 1:
  21252. if (v1Out) {
  21253. nV1 = vertices[index + 1];
  21254. nV2 = vertices[index + 2];
  21255. nV3 = clipVertices(vertices[index], nV1);
  21256. nV4 = clipVertices(vertices[index], nV2);
  21257. }
  21258. if (v2Out) {
  21259. nV1 = vertices[index];
  21260. nV2 = vertices[index + 2];
  21261. nV3 = clipVertices(vertices[index + 1], nV1);
  21262. nV4 = clipVertices(vertices[index + 1], nV2);
  21263. result.push(nV3);
  21264. result.push(nV2.clone());
  21265. result.push(nV1.clone());
  21266. result.push(nV2.clone());
  21267. result.push(nV3.clone());
  21268. result.push(nV4);
  21269. break;
  21270. }
  21271. if (v3Out) {
  21272. nV1 = vertices[index];
  21273. nV2 = vertices[index + 1];
  21274. nV3 = clipVertices(vertices[index + 2], nV1);
  21275. nV4 = clipVertices(vertices[index + 2], nV2);
  21276. }
  21277. result.push(nV1.clone());
  21278. result.push(nV2.clone());
  21279. result.push(nV3);
  21280. result.push(nV4);
  21281. result.push(nV3.clone());
  21282. result.push(nV2.clone());
  21283. break;
  21284. case 2:
  21285. if (!v1Out) {
  21286. nV1 = vertices[index].clone();
  21287. nV2 = clipVertices(nV1, vertices[index + 1]);
  21288. nV3 = clipVertices(nV1, vertices[index + 2]);
  21289. result.push(nV1);
  21290. result.push(nV2);
  21291. result.push(nV3);
  21292. }
  21293. if (!v2Out) {
  21294. nV1 = vertices[index + 1].clone();
  21295. nV2 = clipVertices(nV1, vertices[index + 2]);
  21296. nV3 = clipVertices(nV1, vertices[index]);
  21297. result.push(nV1);
  21298. result.push(nV2);
  21299. result.push(nV3);
  21300. }
  21301. if (!v3Out) {
  21302. nV1 = vertices[index + 2].clone();
  21303. nV2 = clipVertices(nV1, vertices[index]);
  21304. nV3 = clipVertices(nV1, vertices[index + 1]);
  21305. result.push(nV1);
  21306. result.push(nV2);
  21307. result.push(nV3);
  21308. }
  21309. break;
  21310. case 3:
  21311. break;
  21312. }
  21313. }
  21314. return result;
  21315. };
  21316. for (var index = 0; index < indices.length; index += 3) {
  21317. var faceVertices = new Array();
  21318. faceVertices.push(extractDecalVector3(index));
  21319. faceVertices.push(extractDecalVector3(index + 1));
  21320. faceVertices.push(extractDecalVector3(index + 2));
  21321. // Clip
  21322. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  21323. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  21324. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  21325. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  21326. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  21327. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  21328. if (faceVertices.length === 0) {
  21329. continue;
  21330. }
  21331. // Add UVs and get back to world
  21332. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  21333. var vertex = faceVertices[vIndex];
  21334. //TODO check for Int32Array
  21335. vertexData.indices.push(currentVertexDataIndex);
  21336. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  21337. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  21338. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  21339. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  21340. currentVertexDataIndex++;
  21341. }
  21342. }
  21343. // Return mesh
  21344. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  21345. vertexData.applyToMesh(decal);
  21346. decal.position = position.clone();
  21347. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  21348. return decal;
  21349. };
  21350. // Privates
  21351. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  21352. // extrusion geometry
  21353. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  21354. var tangents = path3D.getTangents();
  21355. var normals = path3D.getNormals();
  21356. var binormals = path3D.getBinormals();
  21357. var distances = path3D.getDistances();
  21358. var angle = 0;
  21359. var returnScale = function () { return scale; };
  21360. var returnRotation = function () { return rotation; };
  21361. var rotate = custom ? rotateFunction : returnRotation;
  21362. var scl = custom ? scaleFunction : returnScale;
  21363. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  21364. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  21365. for (var i = 0; i < curve.length; i++) {
  21366. var shapePath = new Array();
  21367. var angleStep = rotate(i, distances[i]);
  21368. var scaleRatio = scl(i, distances[i]);
  21369. for (var p = 0; p < shape.length; p++) {
  21370. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  21371. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  21372. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  21373. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  21374. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  21375. shapePath[p] = rotated;
  21376. }
  21377. shapePaths[index] = shapePath;
  21378. angle += angleStep;
  21379. index++;
  21380. }
  21381. // cap
  21382. var capPath = function (shapePath) {
  21383. var pointCap = Array();
  21384. var barycenter = BABYLON.Vector3.Zero();
  21385. var i;
  21386. for (i = 0; i < shapePath.length; i++) {
  21387. barycenter.addInPlace(shapePath[i]);
  21388. }
  21389. barycenter.scaleInPlace(1 / shapePath.length);
  21390. for (i = 0; i < shapePath.length; i++) {
  21391. pointCap.push(barycenter);
  21392. }
  21393. return pointCap;
  21394. };
  21395. switch (cap) {
  21396. case BABYLON.Mesh.NO_CAP:
  21397. break;
  21398. case BABYLON.Mesh.CAP_START:
  21399. shapePaths[0] = capPath(shapePaths[2]);
  21400. shapePaths[1] = shapePaths[2].slice(0);
  21401. break;
  21402. case BABYLON.Mesh.CAP_END:
  21403. shapePaths[index] = shapePaths[index - 1];
  21404. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  21405. break;
  21406. case BABYLON.Mesh.CAP_ALL:
  21407. shapePaths[0] = capPath(shapePaths[2]);
  21408. shapePaths[1] = shapePaths[2].slice(0);
  21409. shapePaths[index] = shapePaths[index - 1];
  21410. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  21411. break;
  21412. default:
  21413. break;
  21414. }
  21415. return shapePaths;
  21416. };
  21417. var path3D;
  21418. var pathArray;
  21419. if (instance) {
  21420. path3D = (instance.path3D).update(curve);
  21421. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  21422. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  21423. return instance;
  21424. }
  21425. // extruded shape creation
  21426. path3D = new BABYLON.Path3D(curve);
  21427. var newShapePaths = new Array();
  21428. cap = (cap < 0 || cap > 3) ? 0 : cap;
  21429. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  21430. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  21431. extrudedGeneric.pathArray = pathArray;
  21432. extrudedGeneric.path3D = path3D;
  21433. extrudedGeneric.cap = cap;
  21434. return extrudedGeneric;
  21435. };
  21436. return MeshBuilder;
  21437. }());
  21438. BABYLON.MeshBuilder = MeshBuilder;
  21439. })(BABYLON || (BABYLON = {}));
  21440. var BABYLON;
  21441. (function (BABYLON) {
  21442. var BaseTexture = (function () {
  21443. function BaseTexture(scene) {
  21444. this.hasAlpha = false;
  21445. this.getAlphaFromRGB = false;
  21446. this.level = 1;
  21447. this.coordinatesIndex = 0;
  21448. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  21449. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21450. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21451. this.anisotropicFilteringLevel = 4;
  21452. this.isCube = false;
  21453. this.isRenderTarget = false;
  21454. this.animations = new Array();
  21455. /**
  21456. * An event triggered when the texture is disposed.
  21457. * @type {BABYLON.Observable}
  21458. */
  21459. this.onDisposeObservable = new BABYLON.Observable();
  21460. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21461. this._scene = scene;
  21462. this._scene.textures.push(this);
  21463. }
  21464. BaseTexture.prototype.toString = function () {
  21465. return this.name;
  21466. };
  21467. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  21468. set: function (callback) {
  21469. if (this._onDisposeObserver) {
  21470. this.onDisposeObservable.remove(this._onDisposeObserver);
  21471. }
  21472. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21473. },
  21474. enumerable: true,
  21475. configurable: true
  21476. });
  21477. BaseTexture.prototype.getScene = function () {
  21478. return this._scene;
  21479. };
  21480. BaseTexture.prototype.getTextureMatrix = function () {
  21481. return null;
  21482. };
  21483. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  21484. return null;
  21485. };
  21486. BaseTexture.prototype.getInternalTexture = function () {
  21487. return this._texture;
  21488. };
  21489. BaseTexture.prototype.isReady = function () {
  21490. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21491. return true;
  21492. }
  21493. if (this._texture) {
  21494. return this._texture.isReady;
  21495. }
  21496. return false;
  21497. };
  21498. BaseTexture.prototype.getSize = function () {
  21499. if (this._texture._width) {
  21500. return new BABYLON.Size(this._texture._width, this._texture._height);
  21501. }
  21502. if (this._texture._size) {
  21503. return new BABYLON.Size(this._texture._size, this._texture._size);
  21504. }
  21505. return BABYLON.Size.Zero();
  21506. };
  21507. BaseTexture.prototype.getBaseSize = function () {
  21508. if (!this.isReady() || !this._texture)
  21509. return BABYLON.Size.Zero();
  21510. if (this._texture._size) {
  21511. return new BABYLON.Size(this._texture._size, this._texture._size);
  21512. }
  21513. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  21514. };
  21515. BaseTexture.prototype.scale = function (ratio) {
  21516. };
  21517. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  21518. get: function () {
  21519. return false;
  21520. },
  21521. enumerable: true,
  21522. configurable: true
  21523. });
  21524. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  21525. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  21526. for (var index = 0; index < texturesCache.length; index++) {
  21527. var texturesCacheEntry = texturesCache[index];
  21528. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  21529. texturesCache.splice(index, 1);
  21530. return;
  21531. }
  21532. }
  21533. };
  21534. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  21535. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  21536. for (var index = 0; index < texturesCache.length; index++) {
  21537. var texturesCacheEntry = texturesCache[index];
  21538. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  21539. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  21540. texturesCacheEntry.references++;
  21541. return texturesCacheEntry;
  21542. }
  21543. }
  21544. }
  21545. return null;
  21546. };
  21547. BaseTexture.prototype.delayLoad = function () {
  21548. };
  21549. BaseTexture.prototype.clone = function () {
  21550. return null;
  21551. };
  21552. BaseTexture.prototype.releaseInternalTexture = function () {
  21553. if (this._texture) {
  21554. this._scene.getEngine().releaseInternalTexture(this._texture);
  21555. delete this._texture;
  21556. }
  21557. };
  21558. BaseTexture.prototype.dispose = function () {
  21559. // Animations
  21560. this.getScene().stopAnimation(this);
  21561. // Remove from scene
  21562. var index = this._scene.textures.indexOf(this);
  21563. if (index >= 0) {
  21564. this._scene.textures.splice(index, 1);
  21565. }
  21566. if (this._texture === undefined) {
  21567. return;
  21568. }
  21569. // Release
  21570. this.releaseInternalTexture();
  21571. // Callback
  21572. this.onDisposeObservable.notifyObservers(this);
  21573. this.onDisposeObservable.clear();
  21574. };
  21575. BaseTexture.prototype.serialize = function () {
  21576. if (!this.name) {
  21577. return null;
  21578. }
  21579. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21580. // Animations
  21581. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21582. return serializationObject;
  21583. };
  21584. __decorate([
  21585. BABYLON.serialize()
  21586. ], BaseTexture.prototype, "name", void 0);
  21587. __decorate([
  21588. BABYLON.serialize()
  21589. ], BaseTexture.prototype, "hasAlpha", void 0);
  21590. __decorate([
  21591. BABYLON.serialize()
  21592. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  21593. __decorate([
  21594. BABYLON.serialize()
  21595. ], BaseTexture.prototype, "level", void 0);
  21596. __decorate([
  21597. BABYLON.serialize()
  21598. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  21599. __decorate([
  21600. BABYLON.serialize()
  21601. ], BaseTexture.prototype, "coordinatesMode", void 0);
  21602. __decorate([
  21603. BABYLON.serialize()
  21604. ], BaseTexture.prototype, "wrapU", void 0);
  21605. __decorate([
  21606. BABYLON.serialize()
  21607. ], BaseTexture.prototype, "wrapV", void 0);
  21608. __decorate([
  21609. BABYLON.serialize()
  21610. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  21611. __decorate([
  21612. BABYLON.serialize()
  21613. ], BaseTexture.prototype, "isCube", void 0);
  21614. __decorate([
  21615. BABYLON.serialize()
  21616. ], BaseTexture.prototype, "isRenderTarget", void 0);
  21617. return BaseTexture;
  21618. }());
  21619. BABYLON.BaseTexture = BaseTexture;
  21620. })(BABYLON || (BABYLON = {}));
  21621. var BABYLON;
  21622. (function (BABYLON) {
  21623. var Texture = (function (_super) {
  21624. __extends(Texture, _super);
  21625. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  21626. var _this = this;
  21627. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21628. if (onLoad === void 0) { onLoad = null; }
  21629. if (onError === void 0) { onError = null; }
  21630. if (buffer === void 0) { buffer = null; }
  21631. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21632. _super.call(this, scene);
  21633. this.uOffset = 0;
  21634. this.vOffset = 0;
  21635. this.uScale = 1.0;
  21636. this.vScale = 1.0;
  21637. this.uAng = 0;
  21638. this.vAng = 0;
  21639. this.wAng = 0;
  21640. this.name = url;
  21641. this.url = url;
  21642. this._noMipmap = noMipmap;
  21643. this._invertY = invertY;
  21644. this._samplingMode = samplingMode;
  21645. this._buffer = buffer;
  21646. this._deleteBuffer = deleteBuffer;
  21647. if (!url) {
  21648. return;
  21649. }
  21650. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  21651. var load = function () {
  21652. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  21653. _this.onLoadObservable.notifyObservers(true);
  21654. }
  21655. if (onLoad) {
  21656. onLoad();
  21657. }
  21658. };
  21659. if (!this._texture) {
  21660. if (!scene.useDelayedTextureLoading) {
  21661. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, load, onError, this._buffer);
  21662. if (deleteBuffer) {
  21663. delete this._buffer;
  21664. }
  21665. }
  21666. else {
  21667. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21668. this._delayedOnLoad = load;
  21669. this._delayedOnError = onError;
  21670. }
  21671. }
  21672. else {
  21673. BABYLON.Tools.SetImmediate(function () { return load(); });
  21674. }
  21675. }
  21676. Object.defineProperty(Texture.prototype, "noMipmap", {
  21677. get: function () {
  21678. return this._noMipmap;
  21679. },
  21680. enumerable: true,
  21681. configurable: true
  21682. });
  21683. Texture.prototype.delayLoad = function () {
  21684. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21685. return;
  21686. }
  21687. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21688. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  21689. if (!this._texture) {
  21690. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  21691. if (this._deleteBuffer) {
  21692. delete this._buffer;
  21693. }
  21694. }
  21695. };
  21696. Texture.prototype.updateSamplingMode = function (samplingMode) {
  21697. if (!this._texture) {
  21698. return;
  21699. }
  21700. this._samplingMode = samplingMode;
  21701. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  21702. };
  21703. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  21704. x *= this.uScale;
  21705. y *= this.vScale;
  21706. x -= 0.5 * this.uScale;
  21707. y -= 0.5 * this.vScale;
  21708. z -= 0.5;
  21709. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  21710. t.x += 0.5 * this.uScale + this.uOffset;
  21711. t.y += 0.5 * this.vScale + this.vOffset;
  21712. t.z += 0.5;
  21713. };
  21714. Texture.prototype.getTextureMatrix = function () {
  21715. if (this.uOffset === this._cachedUOffset &&
  21716. this.vOffset === this._cachedVOffset &&
  21717. this.uScale === this._cachedUScale &&
  21718. this.vScale === this._cachedVScale &&
  21719. this.uAng === this._cachedUAng &&
  21720. this.vAng === this._cachedVAng &&
  21721. this.wAng === this._cachedWAng) {
  21722. return this._cachedTextureMatrix;
  21723. }
  21724. this._cachedUOffset = this.uOffset;
  21725. this._cachedVOffset = this.vOffset;
  21726. this._cachedUScale = this.uScale;
  21727. this._cachedVScale = this.vScale;
  21728. this._cachedUAng = this.uAng;
  21729. this._cachedVAng = this.vAng;
  21730. this._cachedWAng = this.wAng;
  21731. if (!this._cachedTextureMatrix) {
  21732. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21733. this._rowGenerationMatrix = new BABYLON.Matrix();
  21734. this._t0 = BABYLON.Vector3.Zero();
  21735. this._t1 = BABYLON.Vector3.Zero();
  21736. this._t2 = BABYLON.Vector3.Zero();
  21737. }
  21738. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  21739. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  21740. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  21741. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  21742. this._t1.subtractInPlace(this._t0);
  21743. this._t2.subtractInPlace(this._t0);
  21744. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21745. this._cachedTextureMatrix.m[0] = this._t1.x;
  21746. this._cachedTextureMatrix.m[1] = this._t1.y;
  21747. this._cachedTextureMatrix.m[2] = this._t1.z;
  21748. this._cachedTextureMatrix.m[4] = this._t2.x;
  21749. this._cachedTextureMatrix.m[5] = this._t2.y;
  21750. this._cachedTextureMatrix.m[6] = this._t2.z;
  21751. this._cachedTextureMatrix.m[8] = this._t0.x;
  21752. this._cachedTextureMatrix.m[9] = this._t0.y;
  21753. this._cachedTextureMatrix.m[10] = this._t0.z;
  21754. return this._cachedTextureMatrix;
  21755. };
  21756. Texture.prototype.getReflectionTextureMatrix = function () {
  21757. if (this.uOffset === this._cachedUOffset &&
  21758. this.vOffset === this._cachedVOffset &&
  21759. this.uScale === this._cachedUScale &&
  21760. this.vScale === this._cachedVScale &&
  21761. this.coordinatesMode === this._cachedCoordinatesMode) {
  21762. return this._cachedTextureMatrix;
  21763. }
  21764. if (!this._cachedTextureMatrix) {
  21765. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21766. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  21767. }
  21768. this._cachedCoordinatesMode = this.coordinatesMode;
  21769. switch (this.coordinatesMode) {
  21770. case Texture.PLANAR_MODE:
  21771. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21772. this._cachedTextureMatrix[0] = this.uScale;
  21773. this._cachedTextureMatrix[5] = this.vScale;
  21774. this._cachedTextureMatrix[12] = this.uOffset;
  21775. this._cachedTextureMatrix[13] = this.vOffset;
  21776. break;
  21777. case Texture.PROJECTION_MODE:
  21778. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  21779. this._projectionModeMatrix.m[0] = 0.5;
  21780. this._projectionModeMatrix.m[5] = -0.5;
  21781. this._projectionModeMatrix.m[10] = 0.0;
  21782. this._projectionModeMatrix.m[12] = 0.5;
  21783. this._projectionModeMatrix.m[13] = 0.5;
  21784. this._projectionModeMatrix.m[14] = 1.0;
  21785. this._projectionModeMatrix.m[15] = 1.0;
  21786. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  21787. break;
  21788. default:
  21789. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21790. break;
  21791. }
  21792. return this._cachedTextureMatrix;
  21793. };
  21794. Texture.prototype.clone = function () {
  21795. var _this = this;
  21796. return BABYLON.SerializationHelper.Clone(function () {
  21797. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  21798. }, this);
  21799. };
  21800. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  21801. get: function () {
  21802. if (!this._onLoadObservarble) {
  21803. this._onLoadObservarble = new BABYLON.Observable();
  21804. }
  21805. return this._onLoadObservarble;
  21806. },
  21807. enumerable: true,
  21808. configurable: true
  21809. });
  21810. // Statics
  21811. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  21812. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21813. if (onLoad === void 0) { onLoad = null; }
  21814. if (onError === void 0) { onError = null; }
  21815. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  21816. };
  21817. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  21818. if (parsedTexture.isCube) {
  21819. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  21820. }
  21821. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  21822. return null;
  21823. }
  21824. var texture = BABYLON.SerializationHelper.Parse(function () {
  21825. if (parsedTexture.mirrorPlane) {
  21826. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21827. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  21828. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  21829. return mirrorTexture;
  21830. }
  21831. else if (parsedTexture.isRenderTarget) {
  21832. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21833. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  21834. return renderTargetTexture;
  21835. }
  21836. else {
  21837. var texture;
  21838. if (parsedTexture.base64String) {
  21839. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  21840. }
  21841. else {
  21842. texture = new Texture(rootUrl + parsedTexture.name, scene);
  21843. }
  21844. return texture;
  21845. }
  21846. }, parsedTexture, scene);
  21847. // Animations
  21848. if (parsedTexture.animations) {
  21849. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21850. var parsedAnimation = parsedTexture.animations[animationIndex];
  21851. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21852. }
  21853. }
  21854. return texture;
  21855. };
  21856. // Constants
  21857. Texture.NEAREST_SAMPLINGMODE = 1;
  21858. Texture.BILINEAR_SAMPLINGMODE = 2;
  21859. Texture.TRILINEAR_SAMPLINGMODE = 3;
  21860. Texture.EXPLICIT_MODE = 0;
  21861. Texture.SPHERICAL_MODE = 1;
  21862. Texture.PLANAR_MODE = 2;
  21863. Texture.CUBIC_MODE = 3;
  21864. Texture.PROJECTION_MODE = 4;
  21865. Texture.SKYBOX_MODE = 5;
  21866. Texture.INVCUBIC_MODE = 6;
  21867. Texture.EQUIRECTANGULAR_MODE = 7;
  21868. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  21869. Texture.CLAMP_ADDRESSMODE = 0;
  21870. Texture.WRAP_ADDRESSMODE = 1;
  21871. Texture.MIRROR_ADDRESSMODE = 2;
  21872. __decorate([
  21873. BABYLON.serialize()
  21874. ], Texture.prototype, "url", void 0);
  21875. __decorate([
  21876. BABYLON.serialize()
  21877. ], Texture.prototype, "uOffset", void 0);
  21878. __decorate([
  21879. BABYLON.serialize()
  21880. ], Texture.prototype, "vOffset", void 0);
  21881. __decorate([
  21882. BABYLON.serialize()
  21883. ], Texture.prototype, "uScale", void 0);
  21884. __decorate([
  21885. BABYLON.serialize()
  21886. ], Texture.prototype, "vScale", void 0);
  21887. __decorate([
  21888. BABYLON.serialize()
  21889. ], Texture.prototype, "uAng", void 0);
  21890. __decorate([
  21891. BABYLON.serialize()
  21892. ], Texture.prototype, "vAng", void 0);
  21893. __decorate([
  21894. BABYLON.serialize()
  21895. ], Texture.prototype, "wAng", void 0);
  21896. return Texture;
  21897. }(BABYLON.BaseTexture));
  21898. BABYLON.Texture = Texture;
  21899. })(BABYLON || (BABYLON = {}));
  21900. var BABYLON;
  21901. (function (BABYLON) {
  21902. var CubeTexture = (function (_super) {
  21903. __extends(CubeTexture, _super);
  21904. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  21905. _super.call(this, scene);
  21906. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  21907. this.name = rootUrl;
  21908. this.url = rootUrl;
  21909. this._noMipmap = noMipmap;
  21910. this.hasAlpha = false;
  21911. if (!rootUrl && !files) {
  21912. return;
  21913. }
  21914. this._texture = this._getFromCache(rootUrl, noMipmap);
  21915. if (!files) {
  21916. if (!extensions) {
  21917. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  21918. }
  21919. files = [];
  21920. for (var index = 0; index < extensions.length; index++) {
  21921. files.push(rootUrl + extensions[index]);
  21922. }
  21923. this._extensions = extensions;
  21924. }
  21925. this._files = files;
  21926. if (!this._texture) {
  21927. if (!scene.useDelayedTextureLoading) {
  21928. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  21929. }
  21930. else {
  21931. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21932. }
  21933. }
  21934. this.isCube = true;
  21935. this._textureMatrix = BABYLON.Matrix.Identity();
  21936. }
  21937. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  21938. return new CubeTexture("", scene, null, noMipmap, files);
  21939. };
  21940. // Methods
  21941. CubeTexture.prototype.delayLoad = function () {
  21942. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21943. return;
  21944. }
  21945. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21946. this._texture = this._getFromCache(this.url, this._noMipmap);
  21947. if (!this._texture) {
  21948. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  21949. }
  21950. };
  21951. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  21952. return this._textureMatrix;
  21953. };
  21954. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  21955. var texture = BABYLON.SerializationHelper.Parse(function () {
  21956. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  21957. }, parsedTexture, scene);
  21958. // Animations
  21959. if (parsedTexture.animations) {
  21960. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21961. var parsedAnimation = parsedTexture.animations[animationIndex];
  21962. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21963. }
  21964. }
  21965. return texture;
  21966. };
  21967. CubeTexture.prototype.clone = function () {
  21968. var _this = this;
  21969. return BABYLON.SerializationHelper.Clone(function () {
  21970. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  21971. }, this);
  21972. };
  21973. return CubeTexture;
  21974. }(BABYLON.BaseTexture));
  21975. BABYLON.CubeTexture = CubeTexture;
  21976. })(BABYLON || (BABYLON = {}));
  21977. var BABYLON;
  21978. (function (BABYLON) {
  21979. var RenderTargetTexture = (function (_super) {
  21980. __extends(RenderTargetTexture, _super);
  21981. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode) {
  21982. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  21983. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  21984. if (isCube === void 0) { isCube = false; }
  21985. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21986. _super.call(this, null, scene, !generateMipMaps);
  21987. this.isCube = isCube;
  21988. /**
  21989. * Use this list to define the list of mesh you want to render.
  21990. */
  21991. this.renderList = new Array();
  21992. this.renderParticles = true;
  21993. this.renderSprites = false;
  21994. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  21995. // Events
  21996. /**
  21997. * An event triggered when the texture is unbind.
  21998. * @type {BABYLON.Observable}
  21999. */
  22000. this.onAfterUnbindObservable = new BABYLON.Observable();
  22001. /**
  22002. * An event triggered before rendering the texture
  22003. * @type {BABYLON.Observable}
  22004. */
  22005. this.onBeforeRenderObservable = new BABYLON.Observable();
  22006. /**
  22007. * An event triggered after rendering the texture
  22008. * @type {BABYLON.Observable}
  22009. */
  22010. this.onAfterRenderObservable = new BABYLON.Observable();
  22011. /**
  22012. * An event triggered after the texture clear
  22013. * @type {BABYLON.Observable}
  22014. */
  22015. this.onClearObservable = new BABYLON.Observable();
  22016. this._currentRefreshId = -1;
  22017. this._refreshRate = 1;
  22018. this.name = name;
  22019. this.isRenderTarget = true;
  22020. this._size = size;
  22021. this._generateMipMaps = generateMipMaps;
  22022. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  22023. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  22024. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22025. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22026. }
  22027. if (isCube) {
  22028. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps, samplingMode: samplingMode });
  22029. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  22030. this._textureMatrix = BABYLON.Matrix.Identity();
  22031. }
  22032. else {
  22033. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type, samplingMode: samplingMode });
  22034. }
  22035. // Rendering groups
  22036. this._renderingManager = new BABYLON.RenderingManager(scene);
  22037. }
  22038. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  22039. get: function () {
  22040. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  22041. },
  22042. enumerable: true,
  22043. configurable: true
  22044. });
  22045. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  22046. get: function () {
  22047. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  22048. },
  22049. enumerable: true,
  22050. configurable: true
  22051. });
  22052. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  22053. get: function () {
  22054. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  22055. },
  22056. enumerable: true,
  22057. configurable: true
  22058. });
  22059. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  22060. set: function (callback) {
  22061. if (this._onAfterUnbindObserver) {
  22062. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  22063. }
  22064. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  22065. },
  22066. enumerable: true,
  22067. configurable: true
  22068. });
  22069. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  22070. set: function (callback) {
  22071. if (this._onBeforeRenderObserver) {
  22072. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22073. }
  22074. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22075. },
  22076. enumerable: true,
  22077. configurable: true
  22078. });
  22079. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  22080. set: function (callback) {
  22081. if (this._onAfterRenderObserver) {
  22082. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22083. }
  22084. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22085. },
  22086. enumerable: true,
  22087. configurable: true
  22088. });
  22089. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  22090. set: function (callback) {
  22091. if (this._onClearObserver) {
  22092. this.onClearObservable.remove(this._onClearObserver);
  22093. }
  22094. this._onClearObserver = this.onClearObservable.add(callback);
  22095. },
  22096. enumerable: true,
  22097. configurable: true
  22098. });
  22099. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  22100. this._currentRefreshId = -1;
  22101. };
  22102. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  22103. get: function () {
  22104. return this._refreshRate;
  22105. },
  22106. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  22107. set: function (value) {
  22108. this._refreshRate = value;
  22109. this.resetRefreshCounter();
  22110. },
  22111. enumerable: true,
  22112. configurable: true
  22113. });
  22114. RenderTargetTexture.prototype._shouldRender = function () {
  22115. if (this._currentRefreshId === -1) {
  22116. this._currentRefreshId = 1;
  22117. return true;
  22118. }
  22119. if (this.refreshRate === this._currentRefreshId) {
  22120. this._currentRefreshId = 1;
  22121. return true;
  22122. }
  22123. this._currentRefreshId++;
  22124. return false;
  22125. };
  22126. RenderTargetTexture.prototype.isReady = function () {
  22127. if (!this.getScene().renderTargetsEnabled) {
  22128. return false;
  22129. }
  22130. return _super.prototype.isReady.call(this);
  22131. };
  22132. RenderTargetTexture.prototype.getRenderSize = function () {
  22133. return this._size;
  22134. };
  22135. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  22136. get: function () {
  22137. return true;
  22138. },
  22139. enumerable: true,
  22140. configurable: true
  22141. });
  22142. RenderTargetTexture.prototype.scale = function (ratio) {
  22143. var newSize = this._size * ratio;
  22144. this.resize(newSize, this._generateMipMaps);
  22145. };
  22146. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  22147. if (this.isCube) {
  22148. return this._textureMatrix;
  22149. }
  22150. return _super.prototype.getReflectionTextureMatrix.call(this);
  22151. };
  22152. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  22153. this.releaseInternalTexture();
  22154. if (this.isCube) {
  22155. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  22156. }
  22157. else {
  22158. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  22159. }
  22160. };
  22161. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  22162. var scene = this.getScene();
  22163. if (this.useCameraPostProcesses !== undefined) {
  22164. useCameraPostProcess = this.useCameraPostProcesses;
  22165. }
  22166. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  22167. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  22168. }
  22169. if (this._waitingRenderList) {
  22170. this.renderList = [];
  22171. for (var index = 0; index < this._waitingRenderList.length; index++) {
  22172. var id = this._waitingRenderList[index];
  22173. this.renderList.push(scene.getMeshByID(id));
  22174. }
  22175. delete this._waitingRenderList;
  22176. }
  22177. // Is predicate defined?
  22178. if (this.renderListPredicate) {
  22179. this.renderList.splice(0); // Clear previous renderList
  22180. var sceneMeshes = this.getScene().meshes;
  22181. for (var index = 0; index < sceneMeshes.length; index++) {
  22182. var mesh = sceneMeshes[index];
  22183. if (this.renderListPredicate(mesh)) {
  22184. this.renderList.push(mesh);
  22185. }
  22186. }
  22187. }
  22188. if (this.renderList && this.renderList.length === 0) {
  22189. return;
  22190. }
  22191. // Prepare renderingManager
  22192. this._renderingManager.reset();
  22193. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  22194. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  22195. var sceneRenderId = scene.getRenderId();
  22196. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  22197. var mesh = currentRenderList[meshIndex];
  22198. if (mesh) {
  22199. if (!mesh.isReady()) {
  22200. // Reset _currentRefreshId
  22201. this.resetRefreshCounter();
  22202. continue;
  22203. }
  22204. mesh._preActivateForIntermediateRendering(sceneRenderId);
  22205. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  22206. mesh._activate(sceneRenderId);
  22207. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  22208. var subMesh = mesh.subMeshes[subIndex];
  22209. scene._activeIndices.addCount(subMesh.indexCount, false);
  22210. this._renderingManager.dispatch(subMesh);
  22211. }
  22212. }
  22213. }
  22214. }
  22215. if (this.isCube) {
  22216. for (var face = 0; face < 6; face++) {
  22217. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  22218. scene.incrementRenderId();
  22219. scene.resetCachedMaterial();
  22220. }
  22221. }
  22222. else {
  22223. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  22224. }
  22225. this.onAfterUnbindObservable.notifyObservers(this);
  22226. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  22227. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  22228. }
  22229. scene.resetCachedMaterial();
  22230. };
  22231. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  22232. var scene = this.getScene();
  22233. var engine = scene.getEngine();
  22234. // Bind
  22235. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  22236. if (this.isCube) {
  22237. engine.bindFramebuffer(this._texture, faceIndex);
  22238. }
  22239. else {
  22240. engine.bindFramebuffer(this._texture);
  22241. }
  22242. }
  22243. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  22244. // Clear
  22245. if (this.onClearObservable.hasObservers()) {
  22246. this.onClearObservable.notifyObservers(engine);
  22247. }
  22248. else {
  22249. engine.clear(scene.clearColor, true, true);
  22250. }
  22251. if (!this._doNotChangeAspectRatio) {
  22252. scene.updateTransformMatrix(true);
  22253. }
  22254. // Render
  22255. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  22256. if (useCameraPostProcess) {
  22257. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  22258. }
  22259. if (!this._doNotChangeAspectRatio) {
  22260. scene.updateTransformMatrix(true);
  22261. }
  22262. this.onAfterRenderObservable.notifyObservers(faceIndex);
  22263. // Dump ?
  22264. if (dumpForDebug) {
  22265. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  22266. }
  22267. // Unbind
  22268. if (!this.isCube || faceIndex === 5) {
  22269. if (this.isCube) {
  22270. if (faceIndex === 5) {
  22271. engine.generateMipMapsForCubemap(this._texture);
  22272. }
  22273. }
  22274. engine.unBindFramebuffer(this._texture, this.isCube);
  22275. }
  22276. };
  22277. RenderTargetTexture.prototype.clone = function () {
  22278. var textureSize = this.getSize();
  22279. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22280. // Base texture
  22281. newTexture.hasAlpha = this.hasAlpha;
  22282. newTexture.level = this.level;
  22283. // RenderTarget Texture
  22284. newTexture.coordinatesMode = this.coordinatesMode;
  22285. newTexture.renderList = this.renderList.slice(0);
  22286. return newTexture;
  22287. };
  22288. RenderTargetTexture.prototype.serialize = function () {
  22289. if (!this.name) {
  22290. return null;
  22291. }
  22292. var serializationObject = _super.prototype.serialize.call(this);
  22293. serializationObject.renderTargetSize = this.getRenderSize();
  22294. serializationObject.renderList = [];
  22295. for (var index = 0; index < this.renderList.length; index++) {
  22296. serializationObject.renderList.push(this.renderList[index].id);
  22297. }
  22298. return serializationObject;
  22299. };
  22300. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  22301. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  22302. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  22303. return RenderTargetTexture;
  22304. }(BABYLON.Texture));
  22305. BABYLON.RenderTargetTexture = RenderTargetTexture;
  22306. })(BABYLON || (BABYLON = {}));
  22307. var BABYLON;
  22308. (function (BABYLON) {
  22309. var ProceduralTexture = (function (_super) {
  22310. __extends(ProceduralTexture, _super);
  22311. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  22312. if (generateMipMaps === void 0) { generateMipMaps = true; }
  22313. if (isCube === void 0) { isCube = false; }
  22314. _super.call(this, null, scene, !generateMipMaps);
  22315. this.isCube = isCube;
  22316. this.isEnabled = true;
  22317. this._currentRefreshId = -1;
  22318. this._refreshRate = 1;
  22319. this._vertexBuffers = {};
  22320. this._uniforms = new Array();
  22321. this._samplers = new Array();
  22322. this._textures = new Array();
  22323. this._floats = new Array();
  22324. this._floatsArrays = {};
  22325. this._colors3 = new Array();
  22326. this._colors4 = new Array();
  22327. this._vectors2 = new Array();
  22328. this._vectors3 = new Array();
  22329. this._matrices = new Array();
  22330. this._fallbackTextureUsed = false;
  22331. scene._proceduralTextures.push(this);
  22332. this.name = name;
  22333. this.isRenderTarget = true;
  22334. this._size = size;
  22335. this._generateMipMaps = generateMipMaps;
  22336. this.setFragment(fragment);
  22337. this._fallbackTexture = fallbackTexture;
  22338. var engine = scene.getEngine();
  22339. if (isCube) {
  22340. this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  22341. this.setFloat("face", 0);
  22342. }
  22343. else {
  22344. this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  22345. }
  22346. // VBO
  22347. var vertices = [];
  22348. vertices.push(1, 1);
  22349. vertices.push(-1, 1);
  22350. vertices.push(-1, -1);
  22351. vertices.push(1, -1);
  22352. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  22353. // Indices
  22354. var indices = [];
  22355. indices.push(0);
  22356. indices.push(1);
  22357. indices.push(2);
  22358. indices.push(0);
  22359. indices.push(2);
  22360. indices.push(3);
  22361. this._indexBuffer = engine.createIndexBuffer(indices);
  22362. }
  22363. ProceduralTexture.prototype.reset = function () {
  22364. if (this._effect === undefined) {
  22365. return;
  22366. }
  22367. var engine = this.getScene().getEngine();
  22368. engine._releaseEffect(this._effect);
  22369. };
  22370. ProceduralTexture.prototype.isReady = function () {
  22371. var _this = this;
  22372. var engine = this.getScene().getEngine();
  22373. var shaders;
  22374. if (!this._fragment) {
  22375. return false;
  22376. }
  22377. if (this._fallbackTextureUsed) {
  22378. return true;
  22379. }
  22380. if (this._fragment.fragmentElement !== undefined) {
  22381. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  22382. }
  22383. else {
  22384. shaders = { vertex: "procedural", fragment: this._fragment };
  22385. }
  22386. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  22387. _this.releaseInternalTexture();
  22388. if (_this._fallbackTexture) {
  22389. _this._texture = _this._fallbackTexture._texture;
  22390. _this._texture.references++;
  22391. }
  22392. _this._fallbackTextureUsed = true;
  22393. });
  22394. return this._effect.isReady();
  22395. };
  22396. ProceduralTexture.prototype.resetRefreshCounter = function () {
  22397. this._currentRefreshId = -1;
  22398. };
  22399. ProceduralTexture.prototype.setFragment = function (fragment) {
  22400. this._fragment = fragment;
  22401. };
  22402. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  22403. get: function () {
  22404. return this._refreshRate;
  22405. },
  22406. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  22407. set: function (value) {
  22408. this._refreshRate = value;
  22409. this.resetRefreshCounter();
  22410. },
  22411. enumerable: true,
  22412. configurable: true
  22413. });
  22414. ProceduralTexture.prototype._shouldRender = function () {
  22415. if (!this.isEnabled || !this.isReady() || !this._texture) {
  22416. return false;
  22417. }
  22418. if (this._fallbackTextureUsed) {
  22419. return false;
  22420. }
  22421. if (this._currentRefreshId === -1) {
  22422. this._currentRefreshId = 1;
  22423. return true;
  22424. }
  22425. if (this.refreshRate === this._currentRefreshId) {
  22426. this._currentRefreshId = 1;
  22427. return true;
  22428. }
  22429. this._currentRefreshId++;
  22430. return false;
  22431. };
  22432. ProceduralTexture.prototype.getRenderSize = function () {
  22433. return this._size;
  22434. };
  22435. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  22436. if (this._fallbackTextureUsed) {
  22437. return;
  22438. }
  22439. this.releaseInternalTexture();
  22440. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  22441. };
  22442. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  22443. if (this._uniforms.indexOf(uniformName) === -1) {
  22444. this._uniforms.push(uniformName);
  22445. }
  22446. };
  22447. ProceduralTexture.prototype.setTexture = function (name, texture) {
  22448. if (this._samplers.indexOf(name) === -1) {
  22449. this._samplers.push(name);
  22450. }
  22451. this._textures[name] = texture;
  22452. return this;
  22453. };
  22454. ProceduralTexture.prototype.setFloat = function (name, value) {
  22455. this._checkUniform(name);
  22456. this._floats[name] = value;
  22457. return this;
  22458. };
  22459. ProceduralTexture.prototype.setFloats = function (name, value) {
  22460. this._checkUniform(name);
  22461. this._floatsArrays[name] = value;
  22462. return this;
  22463. };
  22464. ProceduralTexture.prototype.setColor3 = function (name, value) {
  22465. this._checkUniform(name);
  22466. this._colors3[name] = value;
  22467. return this;
  22468. };
  22469. ProceduralTexture.prototype.setColor4 = function (name, value) {
  22470. this._checkUniform(name);
  22471. this._colors4[name] = value;
  22472. return this;
  22473. };
  22474. ProceduralTexture.prototype.setVector2 = function (name, value) {
  22475. this._checkUniform(name);
  22476. this._vectors2[name] = value;
  22477. return this;
  22478. };
  22479. ProceduralTexture.prototype.setVector3 = function (name, value) {
  22480. this._checkUniform(name);
  22481. this._vectors3[name] = value;
  22482. return this;
  22483. };
  22484. ProceduralTexture.prototype.setMatrix = function (name, value) {
  22485. this._checkUniform(name);
  22486. this._matrices[name] = value;
  22487. return this;
  22488. };
  22489. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  22490. var scene = this.getScene();
  22491. var engine = scene.getEngine();
  22492. // Render
  22493. engine.enableEffect(this._effect);
  22494. engine.setState(false);
  22495. // Texture
  22496. for (var name in this._textures) {
  22497. this._effect.setTexture(name, this._textures[name]);
  22498. }
  22499. // Float
  22500. for (name in this._floats) {
  22501. this._effect.setFloat(name, this._floats[name]);
  22502. }
  22503. // Floats
  22504. for (name in this._floatsArrays) {
  22505. this._effect.setArray(name, this._floatsArrays[name]);
  22506. }
  22507. // Color3
  22508. for (name in this._colors3) {
  22509. this._effect.setColor3(name, this._colors3[name]);
  22510. }
  22511. // Color4
  22512. for (name in this._colors4) {
  22513. var color = this._colors4[name];
  22514. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  22515. }
  22516. // Vector2
  22517. for (name in this._vectors2) {
  22518. this._effect.setVector2(name, this._vectors2[name]);
  22519. }
  22520. // Vector3
  22521. for (name in this._vectors3) {
  22522. this._effect.setVector3(name, this._vectors3[name]);
  22523. }
  22524. // Matrix
  22525. for (name in this._matrices) {
  22526. this._effect.setMatrix(name, this._matrices[name]);
  22527. }
  22528. // VBOs
  22529. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  22530. if (this.isCube) {
  22531. for (var face = 0; face < 6; face++) {
  22532. engine.bindFramebuffer(this._texture, face);
  22533. this._effect.setFloat("face", face);
  22534. // Clear
  22535. engine.clear(scene.clearColor, true, true);
  22536. // Draw order
  22537. engine.draw(true, 0, 6);
  22538. // Mipmaps
  22539. if (face === 5) {
  22540. engine.generateMipMapsForCubemap(this._texture);
  22541. }
  22542. }
  22543. }
  22544. else {
  22545. engine.bindFramebuffer(this._texture);
  22546. // Clear
  22547. engine.clear(scene.clearColor, true, true);
  22548. // Draw order
  22549. engine.draw(true, 0, 6);
  22550. }
  22551. // Unbind
  22552. engine.unBindFramebuffer(this._texture, this.isCube);
  22553. if (this.onGenerated) {
  22554. this.onGenerated();
  22555. }
  22556. };
  22557. ProceduralTexture.prototype.clone = function () {
  22558. var textureSize = this.getSize();
  22559. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  22560. // Base texture
  22561. newTexture.hasAlpha = this.hasAlpha;
  22562. newTexture.level = this.level;
  22563. // RenderTarget Texture
  22564. newTexture.coordinatesMode = this.coordinatesMode;
  22565. return newTexture;
  22566. };
  22567. ProceduralTexture.prototype.dispose = function () {
  22568. var index = this.getScene()._proceduralTextures.indexOf(this);
  22569. if (index >= 0) {
  22570. this.getScene()._proceduralTextures.splice(index, 1);
  22571. }
  22572. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  22573. if (vertexBuffer) {
  22574. vertexBuffer.dispose();
  22575. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  22576. }
  22577. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  22578. this._indexBuffer = null;
  22579. }
  22580. _super.prototype.dispose.call(this);
  22581. };
  22582. return ProceduralTexture;
  22583. }(BABYLON.Texture));
  22584. BABYLON.ProceduralTexture = ProceduralTexture;
  22585. })(BABYLON || (BABYLON = {}));
  22586. var BABYLON;
  22587. (function (BABYLON) {
  22588. var MirrorTexture = (function (_super) {
  22589. __extends(MirrorTexture, _super);
  22590. function MirrorTexture(name, size, scene, generateMipMaps) {
  22591. var _this = this;
  22592. _super.call(this, name, size, scene, generateMipMaps, true);
  22593. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  22594. this._transformMatrix = BABYLON.Matrix.Zero();
  22595. this._mirrorMatrix = BABYLON.Matrix.Zero();
  22596. this.onBeforeRenderObservable.add(function () {
  22597. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  22598. _this._savedViewMatrix = scene.getViewMatrix();
  22599. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  22600. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  22601. scene.clipPlane = _this.mirrorPlane;
  22602. scene.getEngine().cullBackFaces = false;
  22603. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  22604. });
  22605. this.onAfterRenderObservable.add(function () {
  22606. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  22607. scene.getEngine().cullBackFaces = true;
  22608. scene._mirroredCameraPosition = null;
  22609. delete scene.clipPlane;
  22610. });
  22611. }
  22612. MirrorTexture.prototype.clone = function () {
  22613. var textureSize = this.getSize();
  22614. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22615. // Base texture
  22616. newTexture.hasAlpha = this.hasAlpha;
  22617. newTexture.level = this.level;
  22618. // Mirror Texture
  22619. newTexture.mirrorPlane = this.mirrorPlane.clone();
  22620. newTexture.renderList = this.renderList.slice(0);
  22621. return newTexture;
  22622. };
  22623. MirrorTexture.prototype.serialize = function () {
  22624. if (!this.name) {
  22625. return null;
  22626. }
  22627. var serializationObject = _super.prototype.serialize.call(this);
  22628. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  22629. return serializationObject;
  22630. };
  22631. return MirrorTexture;
  22632. }(BABYLON.RenderTargetTexture));
  22633. BABYLON.MirrorTexture = MirrorTexture;
  22634. })(BABYLON || (BABYLON = {}));
  22635. var BABYLON;
  22636. (function (BABYLON) {
  22637. /**
  22638. * Creates a refraction texture used by refraction channel of the standard material.
  22639. * @param name the texture name
  22640. * @param size size of the underlying texture
  22641. * @param scene root scene
  22642. */
  22643. var RefractionTexture = (function (_super) {
  22644. __extends(RefractionTexture, _super);
  22645. function RefractionTexture(name, size, scene, generateMipMaps) {
  22646. var _this = this;
  22647. _super.call(this, name, size, scene, generateMipMaps, true);
  22648. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  22649. this.depth = 2.0;
  22650. this.onBeforeRenderObservable.add(function () {
  22651. scene.clipPlane = _this.refractionPlane;
  22652. });
  22653. this.onAfterRenderObservable.add(function () {
  22654. delete scene.clipPlane;
  22655. });
  22656. }
  22657. RefractionTexture.prototype.clone = function () {
  22658. var textureSize = this.getSize();
  22659. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22660. // Base texture
  22661. newTexture.hasAlpha = this.hasAlpha;
  22662. newTexture.level = this.level;
  22663. // Refraction Texture
  22664. newTexture.refractionPlane = this.refractionPlane.clone();
  22665. newTexture.renderList = this.renderList.slice(0);
  22666. newTexture.depth = this.depth;
  22667. return newTexture;
  22668. };
  22669. RefractionTexture.prototype.serialize = function () {
  22670. if (!this.name) {
  22671. return null;
  22672. }
  22673. var serializationObject = _super.prototype.serialize.call(this);
  22674. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  22675. serializationObject.depth = this.depth;
  22676. return serializationObject;
  22677. };
  22678. return RefractionTexture;
  22679. }(BABYLON.RenderTargetTexture));
  22680. BABYLON.RefractionTexture = RefractionTexture;
  22681. })(BABYLON || (BABYLON = {}));
  22682. var BABYLON;
  22683. (function (BABYLON) {
  22684. var DynamicTexture = (function (_super) {
  22685. __extends(DynamicTexture, _super);
  22686. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  22687. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22688. _super.call(this, null, scene, !generateMipMaps);
  22689. this.name = name;
  22690. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22691. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22692. this._generateMipMaps = generateMipMaps;
  22693. if (options.getContext) {
  22694. this._canvas = options;
  22695. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  22696. }
  22697. else {
  22698. this._canvas = document.createElement("canvas");
  22699. if (options.width) {
  22700. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  22701. }
  22702. else {
  22703. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  22704. }
  22705. }
  22706. var textureSize = this.getSize();
  22707. this._canvas.width = textureSize.width;
  22708. this._canvas.height = textureSize.height;
  22709. this._context = this._canvas.getContext("2d");
  22710. }
  22711. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  22712. get: function () {
  22713. return true;
  22714. },
  22715. enumerable: true,
  22716. configurable: true
  22717. });
  22718. DynamicTexture.prototype.scale = function (ratio) {
  22719. var textureSize = this.getSize();
  22720. textureSize.width *= ratio;
  22721. textureSize.height *= ratio;
  22722. this._canvas.width = textureSize.width;
  22723. this._canvas.height = textureSize.height;
  22724. this.releaseInternalTexture();
  22725. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  22726. };
  22727. DynamicTexture.prototype.getContext = function () {
  22728. return this._context;
  22729. };
  22730. DynamicTexture.prototype.clear = function () {
  22731. var size = this.getSize();
  22732. this._context.fillRect(0, 0, size.width, size.height);
  22733. };
  22734. DynamicTexture.prototype.update = function (invertY) {
  22735. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  22736. };
  22737. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  22738. if (update === void 0) { update = true; }
  22739. var size = this.getSize();
  22740. if (clearColor) {
  22741. this._context.fillStyle = clearColor;
  22742. this._context.fillRect(0, 0, size.width, size.height);
  22743. }
  22744. this._context.font = font;
  22745. if (x === null) {
  22746. var textSize = this._context.measureText(text);
  22747. x = (size.width - textSize.width) / 2;
  22748. }
  22749. this._context.fillStyle = color;
  22750. this._context.fillText(text, x, y);
  22751. if (update) {
  22752. this.update(invertY);
  22753. }
  22754. };
  22755. DynamicTexture.prototype.clone = function () {
  22756. var textureSize = this.getSize();
  22757. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  22758. // Base texture
  22759. newTexture.hasAlpha = this.hasAlpha;
  22760. newTexture.level = this.level;
  22761. // Dynamic Texture
  22762. newTexture.wrapU = this.wrapU;
  22763. newTexture.wrapV = this.wrapV;
  22764. return newTexture;
  22765. };
  22766. return DynamicTexture;
  22767. }(BABYLON.Texture));
  22768. BABYLON.DynamicTexture = DynamicTexture;
  22769. })(BABYLON || (BABYLON = {}));
  22770. var BABYLON;
  22771. (function (BABYLON) {
  22772. var VideoTexture = (function (_super) {
  22773. __extends(VideoTexture, _super);
  22774. /**
  22775. * Creates a video texture.
  22776. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  22777. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  22778. * @param {BABYLON.Scene} scene is obviously the current scene.
  22779. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  22780. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  22781. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  22782. */
  22783. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  22784. var _this = this;
  22785. if (generateMipMaps === void 0) { generateMipMaps = false; }
  22786. if (invertY === void 0) { invertY = false; }
  22787. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22788. _super.call(this, null, scene, !generateMipMaps, invertY);
  22789. this._autoLaunch = true;
  22790. var urls;
  22791. this.name = name;
  22792. if (urlsOrVideo instanceof HTMLVideoElement) {
  22793. this.video = urlsOrVideo;
  22794. }
  22795. else {
  22796. urls = urlsOrVideo;
  22797. this.video = document.createElement("video");
  22798. this.video.autoplay = false;
  22799. this.video.loop = true;
  22800. }
  22801. this._generateMipMaps = generateMipMaps;
  22802. this._samplingMode = samplingMode;
  22803. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  22804. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22805. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22806. }
  22807. else {
  22808. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22809. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22810. this._generateMipMaps = false;
  22811. }
  22812. if (urls) {
  22813. this.video.addEventListener("canplaythrough", function () {
  22814. _this._createTexture();
  22815. });
  22816. urls.forEach(function (url) {
  22817. var source = document.createElement("source");
  22818. source.src = url;
  22819. _this.video.appendChild(source);
  22820. });
  22821. }
  22822. else {
  22823. this._createTexture();
  22824. }
  22825. this._lastUpdate = BABYLON.Tools.Now;
  22826. }
  22827. VideoTexture.prototype._createTexture = function () {
  22828. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  22829. this._texture.isReady = true;
  22830. };
  22831. VideoTexture.prototype.update = function () {
  22832. if (this._autoLaunch) {
  22833. this._autoLaunch = false;
  22834. this.video.play();
  22835. }
  22836. var now = BABYLON.Tools.Now;
  22837. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  22838. return false;
  22839. }
  22840. this._lastUpdate = now;
  22841. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  22842. return true;
  22843. };
  22844. return VideoTexture;
  22845. }(BABYLON.Texture));
  22846. BABYLON.VideoTexture = VideoTexture;
  22847. })(BABYLON || (BABYLON = {}));
  22848. var BABYLON;
  22849. (function (BABYLON) {
  22850. var CustomProceduralTexture = (function (_super) {
  22851. __extends(CustomProceduralTexture, _super);
  22852. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  22853. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  22854. this._animate = true;
  22855. this._time = 0;
  22856. this._texturePath = texturePath;
  22857. //Try to load json
  22858. this.loadJson(texturePath);
  22859. this.refreshRate = 1;
  22860. }
  22861. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  22862. var _this = this;
  22863. var that = this;
  22864. function noConfigFile() {
  22865. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  22866. try {
  22867. that.setFragment(that._texturePath);
  22868. }
  22869. catch (ex) {
  22870. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  22871. }
  22872. }
  22873. var configFileUrl = jsonUrl + "/config.json";
  22874. var xhr = new XMLHttpRequest();
  22875. xhr.open("GET", configFileUrl, true);
  22876. xhr.addEventListener("load", function () {
  22877. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  22878. try {
  22879. _this._config = JSON.parse(xhr.response);
  22880. _this.updateShaderUniforms();
  22881. _this.updateTextures();
  22882. _this.setFragment(_this._texturePath + "/custom");
  22883. _this._animate = _this._config.animate;
  22884. _this.refreshRate = _this._config.refreshrate;
  22885. }
  22886. catch (ex) {
  22887. noConfigFile();
  22888. }
  22889. }
  22890. else {
  22891. noConfigFile();
  22892. }
  22893. }, false);
  22894. xhr.addEventListener("error", function () {
  22895. noConfigFile();
  22896. }, false);
  22897. try {
  22898. xhr.send();
  22899. }
  22900. catch (ex) {
  22901. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  22902. }
  22903. };
  22904. CustomProceduralTexture.prototype.isReady = function () {
  22905. if (!_super.prototype.isReady.call(this)) {
  22906. return false;
  22907. }
  22908. for (var name in this._textures) {
  22909. var texture = this._textures[name];
  22910. if (!texture.isReady()) {
  22911. return false;
  22912. }
  22913. }
  22914. return true;
  22915. };
  22916. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  22917. if (this._animate) {
  22918. this._time += this.getScene().getAnimationRatio() * 0.03;
  22919. this.updateShaderUniforms();
  22920. }
  22921. _super.prototype.render.call(this, useCameraPostProcess);
  22922. };
  22923. CustomProceduralTexture.prototype.updateTextures = function () {
  22924. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  22925. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  22926. }
  22927. };
  22928. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  22929. if (this._config) {
  22930. for (var j = 0; j < this._config.uniforms.length; j++) {
  22931. var uniform = this._config.uniforms[j];
  22932. switch (uniform.type) {
  22933. case "float":
  22934. this.setFloat(uniform.name, uniform.value);
  22935. break;
  22936. case "color3":
  22937. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  22938. break;
  22939. case "color4":
  22940. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  22941. break;
  22942. case "vector2":
  22943. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  22944. break;
  22945. case "vector3":
  22946. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  22947. break;
  22948. }
  22949. }
  22950. }
  22951. this.setFloat("time", this._time);
  22952. };
  22953. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  22954. get: function () {
  22955. return this._animate;
  22956. },
  22957. set: function (value) {
  22958. this._animate = value;
  22959. },
  22960. enumerable: true,
  22961. configurable: true
  22962. });
  22963. return CustomProceduralTexture;
  22964. }(BABYLON.ProceduralTexture));
  22965. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  22966. })(BABYLON || (BABYLON = {}));
  22967. var BABYLON;
  22968. (function (BABYLON) {
  22969. var EffectFallbacks = (function () {
  22970. function EffectFallbacks() {
  22971. this._defines = {};
  22972. this._currentRank = 32;
  22973. this._maxRank = -1;
  22974. }
  22975. EffectFallbacks.prototype.addFallback = function (rank, define) {
  22976. if (!this._defines[rank]) {
  22977. if (rank < this._currentRank) {
  22978. this._currentRank = rank;
  22979. }
  22980. if (rank > this._maxRank) {
  22981. this._maxRank = rank;
  22982. }
  22983. this._defines[rank] = new Array();
  22984. }
  22985. this._defines[rank].push(define);
  22986. };
  22987. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  22988. this._meshRank = rank;
  22989. this._mesh = mesh;
  22990. if (rank > this._maxRank) {
  22991. this._maxRank = rank;
  22992. }
  22993. };
  22994. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  22995. get: function () {
  22996. return this._currentRank <= this._maxRank;
  22997. },
  22998. enumerable: true,
  22999. configurable: true
  23000. });
  23001. EffectFallbacks.prototype.reduce = function (currentDefines) {
  23002. var currentFallbacks = this._defines[this._currentRank];
  23003. for (var index = 0; index < currentFallbacks.length; index++) {
  23004. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  23005. }
  23006. if (this._mesh && this._currentRank === this._meshRank) {
  23007. this._mesh.computeBonesUsingShaders = false;
  23008. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  23009. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  23010. }
  23011. this._currentRank++;
  23012. return currentDefines;
  23013. };
  23014. return EffectFallbacks;
  23015. }());
  23016. BABYLON.EffectFallbacks = EffectFallbacks;
  23017. var Effect = (function () {
  23018. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  23019. var _this = this;
  23020. this._isReady = false;
  23021. this._compilationError = "";
  23022. this._valueCache = {};
  23023. this._engine = engine;
  23024. this.name = baseName;
  23025. this.defines = defines;
  23026. this._uniformsNames = uniformsNames.concat(samplers);
  23027. this._samplers = samplers;
  23028. this._attributesNames = attributesNames;
  23029. this.onError = onError;
  23030. this.onCompiled = onCompiled;
  23031. this._indexParameters = indexParameters;
  23032. var vertexSource;
  23033. var fragmentSource;
  23034. if (baseName.vertexElement) {
  23035. vertexSource = document.getElementById(baseName.vertexElement);
  23036. if (!vertexSource) {
  23037. vertexSource = baseName.vertexElement;
  23038. }
  23039. }
  23040. else {
  23041. vertexSource = baseName.vertex || baseName;
  23042. }
  23043. if (baseName.fragmentElement) {
  23044. fragmentSource = document.getElementById(baseName.fragmentElement);
  23045. if (!fragmentSource) {
  23046. fragmentSource = baseName.fragmentElement;
  23047. }
  23048. }
  23049. else {
  23050. fragmentSource = baseName.fragment || baseName;
  23051. }
  23052. this._loadVertexShader(vertexSource, function (vertexCode) {
  23053. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  23054. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  23055. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  23056. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  23057. });
  23058. });
  23059. });
  23060. });
  23061. }
  23062. // Properties
  23063. Effect.prototype.isReady = function () {
  23064. return this._isReady;
  23065. };
  23066. Effect.prototype.getProgram = function () {
  23067. return this._program;
  23068. };
  23069. Effect.prototype.getAttributesNames = function () {
  23070. return this._attributesNames;
  23071. };
  23072. Effect.prototype.getAttributeLocation = function (index) {
  23073. return this._attributes[index];
  23074. };
  23075. Effect.prototype.getAttributeLocationByName = function (name) {
  23076. var index = this._attributesNames.indexOf(name);
  23077. return this._attributes[index];
  23078. };
  23079. Effect.prototype.getAttributesCount = function () {
  23080. return this._attributes.length;
  23081. };
  23082. Effect.prototype.getUniformIndex = function (uniformName) {
  23083. return this._uniformsNames.indexOf(uniformName);
  23084. };
  23085. Effect.prototype.getUniform = function (uniformName) {
  23086. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  23087. };
  23088. Effect.prototype.getSamplers = function () {
  23089. return this._samplers;
  23090. };
  23091. Effect.prototype.getCompilationError = function () {
  23092. return this._compilationError;
  23093. };
  23094. // Methods
  23095. Effect.prototype._loadVertexShader = function (vertex, callback) {
  23096. // DOM element ?
  23097. if (vertex instanceof HTMLElement) {
  23098. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  23099. callback(vertexCode);
  23100. return;
  23101. }
  23102. // Is in local store ?
  23103. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  23104. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  23105. return;
  23106. }
  23107. var vertexShaderUrl;
  23108. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  23109. vertexShaderUrl = vertex;
  23110. }
  23111. else {
  23112. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  23113. }
  23114. // Vertex shader
  23115. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  23116. };
  23117. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  23118. // DOM element ?
  23119. if (fragment instanceof HTMLElement) {
  23120. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  23121. callback(fragmentCode);
  23122. return;
  23123. }
  23124. // Is in local store ?
  23125. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  23126. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  23127. return;
  23128. }
  23129. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  23130. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  23131. return;
  23132. }
  23133. var fragmentShaderUrl;
  23134. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  23135. fragmentShaderUrl = fragment;
  23136. }
  23137. else {
  23138. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  23139. }
  23140. // Fragment shader
  23141. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  23142. };
  23143. Effect.prototype._dumpShadersName = function () {
  23144. if (this.name.vertexElement) {
  23145. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  23146. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  23147. }
  23148. else if (this.name.vertex) {
  23149. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  23150. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  23151. }
  23152. else {
  23153. BABYLON.Tools.Error("Vertex shader:" + this.name);
  23154. BABYLON.Tools.Error("Fragment shader:" + this.name);
  23155. }
  23156. };
  23157. Effect.prototype._processIncludes = function (sourceCode, callback) {
  23158. var _this = this;
  23159. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  23160. var match = regex.exec(sourceCode);
  23161. var returnValue = new String(sourceCode);
  23162. while (match != null) {
  23163. var includeFile = match[1];
  23164. if (Effect.IncludesShadersStore[includeFile]) {
  23165. // Substitution
  23166. var includeContent = Effect.IncludesShadersStore[includeFile];
  23167. if (match[2]) {
  23168. var splits = match[3].split(",");
  23169. for (var index = 0; index < splits.length; index += 2) {
  23170. var source = new RegExp(splits[index], "g");
  23171. var dest = splits[index + 1];
  23172. includeContent = includeContent.replace(source, dest);
  23173. }
  23174. }
  23175. if (match[4]) {
  23176. var indexString = match[5];
  23177. if (indexString.indexOf("..") !== -1) {
  23178. var indexSplits = indexString.split("..");
  23179. var minIndex = parseInt(indexSplits[0]);
  23180. var maxIndex = parseInt(indexSplits[1]);
  23181. var sourceIncludeContent = includeContent.slice(0);
  23182. includeContent = "";
  23183. if (isNaN(maxIndex)) {
  23184. maxIndex = this._indexParameters[indexSplits[1]];
  23185. }
  23186. for (var i = minIndex; i <= maxIndex; i++) {
  23187. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  23188. }
  23189. }
  23190. else {
  23191. includeContent = includeContent.replace(/\{X\}/g, indexString);
  23192. }
  23193. }
  23194. // Replace
  23195. returnValue = returnValue.replace(match[0], includeContent);
  23196. }
  23197. else {
  23198. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  23199. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  23200. Effect.IncludesShadersStore[includeFile] = fileContent;
  23201. _this._processIncludes(returnValue, callback);
  23202. });
  23203. return;
  23204. }
  23205. match = regex.exec(sourceCode);
  23206. }
  23207. callback(returnValue);
  23208. };
  23209. Effect.prototype._processPrecision = function (source) {
  23210. if (source.indexOf("precision highp float") === -1) {
  23211. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23212. source = "precision mediump float;\n" + source;
  23213. }
  23214. else {
  23215. source = "precision highp float;\n" + source;
  23216. }
  23217. }
  23218. else {
  23219. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23220. source = source.replace("precision highp float", "precision mediump float");
  23221. }
  23222. }
  23223. return source;
  23224. };
  23225. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  23226. try {
  23227. var engine = this._engine;
  23228. // Precision
  23229. vertexSourceCode = this._processPrecision(vertexSourceCode);
  23230. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  23231. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  23232. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  23233. this._attributes = engine.getAttributes(this._program, attributesNames);
  23234. var index;
  23235. for (index = 0; index < this._samplers.length; index++) {
  23236. var sampler = this.getUniform(this._samplers[index]);
  23237. if (sampler == null) {
  23238. this._samplers.splice(index, 1);
  23239. index--;
  23240. }
  23241. }
  23242. engine.bindSamplers(this);
  23243. this._isReady = true;
  23244. if (this.onCompiled) {
  23245. this.onCompiled(this);
  23246. }
  23247. }
  23248. catch (e) {
  23249. // Let's go through fallbacks then
  23250. if (fallbacks && fallbacks.isMoreFallbacks) {
  23251. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  23252. this._dumpShadersName();
  23253. defines = fallbacks.reduce(defines);
  23254. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  23255. }
  23256. else {
  23257. BABYLON.Tools.Error("Unable to compile effect: ");
  23258. this._dumpShadersName();
  23259. BABYLON.Tools.Error("Defines: " + defines);
  23260. BABYLON.Tools.Error("Error: " + e.message);
  23261. this._compilationError = e.message;
  23262. if (this.onError) {
  23263. this.onError(this, this._compilationError);
  23264. }
  23265. }
  23266. }
  23267. };
  23268. Object.defineProperty(Effect.prototype, "isSupported", {
  23269. get: function () {
  23270. return this._compilationError === "";
  23271. },
  23272. enumerable: true,
  23273. configurable: true
  23274. });
  23275. Effect.prototype._bindTexture = function (channel, texture) {
  23276. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  23277. };
  23278. Effect.prototype.setTexture = function (channel, texture) {
  23279. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  23280. };
  23281. Effect.prototype.setTextureArray = function (channel, textures) {
  23282. if (this._samplers.indexOf(channel + "Ex") === -1) {
  23283. var initialPos = this._samplers.indexOf(channel);
  23284. for (var index = 1; index < textures.length; index++) {
  23285. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  23286. }
  23287. }
  23288. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  23289. };
  23290. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  23291. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  23292. };
  23293. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  23294. var changed = false;
  23295. var cache = this._valueCache[uniformName];
  23296. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  23297. changed = true;
  23298. cache = new BABYLON.Matrix();
  23299. }
  23300. var tm = cache.m;
  23301. var om = matrix.m;
  23302. for (var index = 0; index < 16; index++) {
  23303. if (tm[index] !== om[index]) {
  23304. tm[index] = om[index];
  23305. changed = true;
  23306. }
  23307. }
  23308. this._valueCache[uniformName] = cache;
  23309. return changed;
  23310. };
  23311. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  23312. var cache = this._valueCache[uniformName];
  23313. if (!cache) {
  23314. cache = [x, y];
  23315. this._valueCache[uniformName] = cache;
  23316. return true;
  23317. }
  23318. var changed = false;
  23319. if (cache[0] !== x) {
  23320. cache[0] = x;
  23321. changed = true;
  23322. }
  23323. if (cache[1] !== y) {
  23324. cache[1] = y;
  23325. changed = true;
  23326. }
  23327. return changed;
  23328. };
  23329. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  23330. var cache = this._valueCache[uniformName];
  23331. if (!cache) {
  23332. cache = [x, y, z];
  23333. this._valueCache[uniformName] = cache;
  23334. return true;
  23335. }
  23336. var changed = false;
  23337. if (cache[0] !== x) {
  23338. cache[0] = x;
  23339. changed = true;
  23340. }
  23341. if (cache[1] !== y) {
  23342. cache[1] = y;
  23343. changed = true;
  23344. }
  23345. if (cache[2] !== z) {
  23346. cache[2] = z;
  23347. changed = true;
  23348. }
  23349. return changed;
  23350. };
  23351. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  23352. var cache = this._valueCache[uniformName];
  23353. if (!cache) {
  23354. cache = [x, y, z, w];
  23355. this._valueCache[uniformName] = cache;
  23356. return true;
  23357. }
  23358. var changed = false;
  23359. if (cache[0] !== x) {
  23360. cache[0] = x;
  23361. changed = true;
  23362. }
  23363. if (cache[1] !== y) {
  23364. cache[1] = y;
  23365. changed = true;
  23366. }
  23367. if (cache[2] !== z) {
  23368. cache[2] = z;
  23369. changed = true;
  23370. }
  23371. if (cache[3] !== w) {
  23372. cache[3] = w;
  23373. changed = true;
  23374. }
  23375. return changed;
  23376. };
  23377. Effect.prototype.setArray = function (uniformName, array) {
  23378. this._valueCache[uniformName] = null;
  23379. this._engine.setArray(this.getUniform(uniformName), array);
  23380. return this;
  23381. };
  23382. Effect.prototype.setArray2 = function (uniformName, array) {
  23383. this._valueCache[uniformName] = null;
  23384. this._engine.setArray2(this.getUniform(uniformName), array);
  23385. return this;
  23386. };
  23387. Effect.prototype.setArray3 = function (uniformName, array) {
  23388. this._valueCache[uniformName] = null;
  23389. this._engine.setArray3(this.getUniform(uniformName), array);
  23390. return this;
  23391. };
  23392. Effect.prototype.setArray4 = function (uniformName, array) {
  23393. this._valueCache[uniformName] = null;
  23394. this._engine.setArray4(this.getUniform(uniformName), array);
  23395. return this;
  23396. };
  23397. Effect.prototype.setMatrices = function (uniformName, matrices) {
  23398. this._valueCache[uniformName] = null;
  23399. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  23400. return this;
  23401. };
  23402. Effect.prototype.setMatrix = function (uniformName, matrix) {
  23403. if (this._cacheMatrix(uniformName, matrix)) {
  23404. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  23405. }
  23406. return this;
  23407. };
  23408. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  23409. this._valueCache[uniformName] = null;
  23410. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  23411. return this;
  23412. };
  23413. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  23414. this._valueCache[uniformName] = null;
  23415. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  23416. return this;
  23417. };
  23418. Effect.prototype.setFloat = function (uniformName, value) {
  23419. var cache = this._valueCache[uniformName];
  23420. if (cache !== undefined && cache === value)
  23421. return this;
  23422. this._valueCache[uniformName] = value;
  23423. this._engine.setFloat(this.getUniform(uniformName), value);
  23424. return this;
  23425. };
  23426. Effect.prototype.setBool = function (uniformName, bool) {
  23427. var cache = this._valueCache[uniformName];
  23428. if (cache !== undefined && cache === bool)
  23429. return this;
  23430. this._valueCache[uniformName] = bool;
  23431. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  23432. return this;
  23433. };
  23434. Effect.prototype.setVector2 = function (uniformName, vector2) {
  23435. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  23436. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  23437. }
  23438. return this;
  23439. };
  23440. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  23441. if (this._cacheFloat2(uniformName, x, y)) {
  23442. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  23443. }
  23444. return this;
  23445. };
  23446. Effect.prototype.setVector3 = function (uniformName, vector3) {
  23447. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  23448. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  23449. }
  23450. return this;
  23451. };
  23452. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  23453. if (this._cacheFloat3(uniformName, x, y, z)) {
  23454. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  23455. }
  23456. return this;
  23457. };
  23458. Effect.prototype.setVector4 = function (uniformName, vector4) {
  23459. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  23460. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  23461. }
  23462. return this;
  23463. };
  23464. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  23465. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  23466. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  23467. }
  23468. return this;
  23469. };
  23470. Effect.prototype.setColor3 = function (uniformName, color3) {
  23471. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  23472. this._engine.setColor3(this.getUniform(uniformName), color3);
  23473. }
  23474. return this;
  23475. };
  23476. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  23477. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  23478. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  23479. }
  23480. return this;
  23481. };
  23482. // Statics
  23483. Effect.ShadersStore = {};
  23484. Effect.IncludesShadersStore = {};
  23485. return Effect;
  23486. }());
  23487. BABYLON.Effect = Effect;
  23488. })(BABYLON || (BABYLON = {}));
  23489. var BABYLON;
  23490. (function (BABYLON) {
  23491. var MaterialHelper = (function () {
  23492. function MaterialHelper() {
  23493. }
  23494. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  23495. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23496. var lightIndex = 0;
  23497. var needNormals = false;
  23498. var needRebuild = false;
  23499. var needShadows = false;
  23500. for (var index = 0; index < scene.lights.length; index++) {
  23501. var light = scene.lights[index];
  23502. if (!light.isEnabled()) {
  23503. continue;
  23504. }
  23505. // Excluded check
  23506. if (light._excludedMeshesIds.length > 0) {
  23507. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  23508. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  23509. if (excludedMesh) {
  23510. light.excludedMeshes.push(excludedMesh);
  23511. }
  23512. }
  23513. light._excludedMeshesIds = [];
  23514. }
  23515. // Included check
  23516. if (light._includedOnlyMeshesIds.length > 0) {
  23517. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  23518. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  23519. if (includedOnlyMesh) {
  23520. light.includedOnlyMeshes.push(includedOnlyMesh);
  23521. }
  23522. }
  23523. light._includedOnlyMeshesIds = [];
  23524. }
  23525. if (!light.canAffectMesh(mesh)) {
  23526. continue;
  23527. }
  23528. needNormals = true;
  23529. if (defines["LIGHT" + lightIndex] === undefined) {
  23530. needRebuild = true;
  23531. }
  23532. defines["LIGHT" + lightIndex] = true;
  23533. var type;
  23534. if (light instanceof BABYLON.SpotLight) {
  23535. type = "SPOTLIGHT" + lightIndex;
  23536. }
  23537. else if (light instanceof BABYLON.HemisphericLight) {
  23538. type = "HEMILIGHT" + lightIndex;
  23539. }
  23540. else if (light instanceof BABYLON.PointLight) {
  23541. type = "POINTLIGHT" + lightIndex;
  23542. }
  23543. else {
  23544. type = "DIRLIGHT" + lightIndex;
  23545. }
  23546. if (defines[type] === undefined) {
  23547. needRebuild = true;
  23548. }
  23549. defines[type] = true;
  23550. // Specular
  23551. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  23552. defines["SPECULARTERM"] = true;
  23553. }
  23554. // Shadows
  23555. if (scene.shadowsEnabled) {
  23556. var shadowGenerator = light.getShadowGenerator();
  23557. if (mesh && mesh.receiveShadows && shadowGenerator) {
  23558. if (defines["SHADOW" + lightIndex] === undefined) {
  23559. needRebuild = true;
  23560. }
  23561. defines["SHADOW" + lightIndex] = true;
  23562. defines["SHADOWS"] = true;
  23563. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  23564. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  23565. needRebuild = true;
  23566. }
  23567. defines["SHADOWVSM" + lightIndex] = true;
  23568. }
  23569. if (shadowGenerator.usePoissonSampling) {
  23570. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  23571. needRebuild = true;
  23572. }
  23573. defines["SHADOWPCF" + lightIndex] = true;
  23574. }
  23575. needShadows = true;
  23576. }
  23577. }
  23578. lightIndex++;
  23579. if (lightIndex === maxSimultaneousLights)
  23580. break;
  23581. }
  23582. var caps = scene.getEngine().getCaps();
  23583. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  23584. if (defines["SHADOWFULLFLOAT"] === undefined) {
  23585. needRebuild = true;
  23586. }
  23587. defines["SHADOWFULLFLOAT"] = true;
  23588. }
  23589. if (needRebuild) {
  23590. defines.rebuild();
  23591. }
  23592. return needNormals;
  23593. };
  23594. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  23595. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23596. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23597. if (!defines["LIGHT" + lightIndex]) {
  23598. break;
  23599. }
  23600. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  23601. samplersList.push("shadowSampler" + lightIndex);
  23602. }
  23603. };
  23604. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  23605. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23606. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23607. if (!defines["LIGHT" + lightIndex]) {
  23608. break;
  23609. }
  23610. if (lightIndex > 0) {
  23611. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  23612. }
  23613. if (defines["SHADOW" + lightIndex]) {
  23614. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  23615. }
  23616. if (defines["SHADOWPCF" + lightIndex]) {
  23617. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  23618. }
  23619. if (defines["SHADOWVSM" + lightIndex]) {
  23620. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  23621. }
  23622. }
  23623. };
  23624. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  23625. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  23626. fallbacks.addCPUSkinningFallback(0, mesh);
  23627. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23628. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23629. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  23630. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  23631. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  23632. }
  23633. }
  23634. };
  23635. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  23636. if (defines["INSTANCES"]) {
  23637. attribs.push("world0");
  23638. attribs.push("world1");
  23639. attribs.push("world2");
  23640. attribs.push("world3");
  23641. }
  23642. };
  23643. // Bindings
  23644. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  23645. var shadowGenerator = light.getShadowGenerator();
  23646. if (mesh.receiveShadows && shadowGenerator) {
  23647. if (!light.needCube()) {
  23648. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  23649. }
  23650. else {
  23651. if (!depthValuesAlreadySet) {
  23652. depthValuesAlreadySet = true;
  23653. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  23654. }
  23655. }
  23656. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  23657. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  23658. }
  23659. return depthValuesAlreadySet;
  23660. };
  23661. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  23662. if (light instanceof BABYLON.PointLight) {
  23663. // Point Light
  23664. light.transferToEffect(effect, "vLightData" + lightIndex);
  23665. }
  23666. else if (light instanceof BABYLON.DirectionalLight) {
  23667. // Directional Light
  23668. light.transferToEffect(effect, "vLightData" + lightIndex);
  23669. }
  23670. else if (light instanceof BABYLON.SpotLight) {
  23671. // Spot Light
  23672. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  23673. }
  23674. else if (light instanceof BABYLON.HemisphericLight) {
  23675. // Hemispheric Light
  23676. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  23677. }
  23678. };
  23679. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  23680. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23681. var lightIndex = 0;
  23682. var depthValuesAlreadySet = false;
  23683. for (var index = 0; index < scene.lights.length; index++) {
  23684. var light = scene.lights[index];
  23685. if (!light.isEnabled()) {
  23686. continue;
  23687. }
  23688. if (!light.canAffectMesh(mesh)) {
  23689. continue;
  23690. }
  23691. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  23692. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  23693. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  23694. if (defines["SPECULARTERM"]) {
  23695. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  23696. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  23697. }
  23698. // Shadows
  23699. if (scene.shadowsEnabled) {
  23700. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  23701. }
  23702. lightIndex++;
  23703. if (lightIndex === maxSimultaneousLights)
  23704. break;
  23705. }
  23706. };
  23707. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  23708. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  23709. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  23710. effect.setColor3("vFogColor", scene.fogColor);
  23711. }
  23712. };
  23713. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  23714. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  23715. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  23716. }
  23717. };
  23718. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  23719. if (defines["LOGARITHMICDEPTH"]) {
  23720. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  23721. }
  23722. };
  23723. MaterialHelper.BindClipPlane = function (effect, scene) {
  23724. if (scene.clipPlane) {
  23725. var clipPlane = scene.clipPlane;
  23726. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23727. }
  23728. };
  23729. return MaterialHelper;
  23730. }());
  23731. BABYLON.MaterialHelper = MaterialHelper;
  23732. })(BABYLON || (BABYLON = {}));
  23733. var BABYLON;
  23734. (function (BABYLON) {
  23735. var FresnelParameters = (function () {
  23736. function FresnelParameters() {
  23737. this.isEnabled = true;
  23738. this.leftColor = BABYLON.Color3.White();
  23739. this.rightColor = BABYLON.Color3.Black();
  23740. this.bias = 0;
  23741. this.power = 1;
  23742. }
  23743. FresnelParameters.prototype.clone = function () {
  23744. var newFresnelParameters = new FresnelParameters();
  23745. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  23746. return new FresnelParameters;
  23747. };
  23748. FresnelParameters.prototype.serialize = function () {
  23749. var serializationObject = {};
  23750. serializationObject.isEnabled = this.isEnabled;
  23751. serializationObject.leftColor = this.leftColor;
  23752. serializationObject.rightColor = this.rightColor;
  23753. serializationObject.bias = this.bias;
  23754. serializationObject.power = this.power;
  23755. return serializationObject;
  23756. };
  23757. FresnelParameters.Parse = function (parsedFresnelParameters) {
  23758. var fresnelParameters = new FresnelParameters();
  23759. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  23760. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  23761. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  23762. fresnelParameters.bias = parsedFresnelParameters.bias;
  23763. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  23764. return fresnelParameters;
  23765. };
  23766. return FresnelParameters;
  23767. }());
  23768. BABYLON.FresnelParameters = FresnelParameters;
  23769. })(BABYLON || (BABYLON = {}));
  23770. var BABYLON;
  23771. (function (BABYLON) {
  23772. var MaterialDefines = (function () {
  23773. function MaterialDefines() {
  23774. }
  23775. MaterialDefines.prototype.rebuild = function () {
  23776. if (this._keys) {
  23777. delete this._keys;
  23778. }
  23779. this._keys = Object.keys(this);
  23780. };
  23781. MaterialDefines.prototype.isEqual = function (other) {
  23782. if (this._keys.length !== other._keys.length) {
  23783. return false;
  23784. }
  23785. for (var index = 0; index < this._keys.length; index++) {
  23786. var prop = this._keys[index];
  23787. if (this[prop] !== other[prop]) {
  23788. return false;
  23789. }
  23790. }
  23791. return true;
  23792. };
  23793. MaterialDefines.prototype.cloneTo = function (other) {
  23794. if (this._keys.length !== other._keys.length) {
  23795. other._keys = this._keys.slice(0);
  23796. }
  23797. for (var index = 0; index < this._keys.length; index++) {
  23798. var prop = this._keys[index];
  23799. other[prop] = this[prop];
  23800. }
  23801. };
  23802. MaterialDefines.prototype.reset = function () {
  23803. for (var index = 0; index < this._keys.length; index++) {
  23804. var prop = this._keys[index];
  23805. if (typeof (this[prop]) === "number") {
  23806. this[prop] = 0;
  23807. }
  23808. else {
  23809. this[prop] = false;
  23810. }
  23811. }
  23812. };
  23813. MaterialDefines.prototype.toString = function () {
  23814. var result = "";
  23815. for (var index = 0; index < this._keys.length; index++) {
  23816. var prop = this._keys[index];
  23817. if (typeof (this[prop]) === "number") {
  23818. result += "#define " + prop + " " + this[prop] + "\n";
  23819. }
  23820. else if (this[prop]) {
  23821. result += "#define " + prop + "\n";
  23822. }
  23823. }
  23824. return result;
  23825. };
  23826. return MaterialDefines;
  23827. }());
  23828. BABYLON.MaterialDefines = MaterialDefines;
  23829. var Material = (function () {
  23830. function Material(name, scene, doNotAdd) {
  23831. this.name = name;
  23832. this.checkReadyOnEveryCall = false;
  23833. this.checkReadyOnlyOnce = false;
  23834. this.state = "";
  23835. this.alpha = 1.0;
  23836. this.backFaceCulling = true;
  23837. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  23838. /**
  23839. * An event triggered when the material is disposed.
  23840. * @type {BABYLON.Observable}
  23841. */
  23842. this.onDisposeObservable = new BABYLON.Observable();
  23843. /**
  23844. * An event triggered when the material is compiled.
  23845. * @type {BABYLON.Observable}
  23846. */
  23847. this.onBindObservable = new BABYLON.Observable();
  23848. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  23849. this.disableDepthWrite = false;
  23850. this.fogEnabled = true;
  23851. this.pointSize = 1.0;
  23852. this.zOffset = 0;
  23853. this._wasPreviouslyReady = false;
  23854. this._fillMode = Material.TriangleFillMode;
  23855. this.id = name;
  23856. this._scene = scene;
  23857. if (!doNotAdd) {
  23858. scene.materials.push(this);
  23859. }
  23860. }
  23861. Object.defineProperty(Material, "TriangleFillMode", {
  23862. get: function () {
  23863. return Material._TriangleFillMode;
  23864. },
  23865. enumerable: true,
  23866. configurable: true
  23867. });
  23868. Object.defineProperty(Material, "WireFrameFillMode", {
  23869. get: function () {
  23870. return Material._WireFrameFillMode;
  23871. },
  23872. enumerable: true,
  23873. configurable: true
  23874. });
  23875. Object.defineProperty(Material, "PointFillMode", {
  23876. get: function () {
  23877. return Material._PointFillMode;
  23878. },
  23879. enumerable: true,
  23880. configurable: true
  23881. });
  23882. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  23883. get: function () {
  23884. return Material._ClockWiseSideOrientation;
  23885. },
  23886. enumerable: true,
  23887. configurable: true
  23888. });
  23889. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  23890. get: function () {
  23891. return Material._CounterClockWiseSideOrientation;
  23892. },
  23893. enumerable: true,
  23894. configurable: true
  23895. });
  23896. Object.defineProperty(Material.prototype, "onDispose", {
  23897. set: function (callback) {
  23898. if (this._onDisposeObserver) {
  23899. this.onDisposeObservable.remove(this._onDisposeObserver);
  23900. }
  23901. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23902. },
  23903. enumerable: true,
  23904. configurable: true
  23905. });
  23906. Object.defineProperty(Material.prototype, "onBind", {
  23907. set: function (callback) {
  23908. if (this._onBindObserver) {
  23909. this.onBindObservable.remove(this._onBindObserver);
  23910. }
  23911. this._onBindObserver = this.onBindObservable.add(callback);
  23912. },
  23913. enumerable: true,
  23914. configurable: true
  23915. });
  23916. Object.defineProperty(Material.prototype, "wireframe", {
  23917. get: function () {
  23918. return this._fillMode === Material.WireFrameFillMode;
  23919. },
  23920. set: function (value) {
  23921. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  23922. },
  23923. enumerable: true,
  23924. configurable: true
  23925. });
  23926. Object.defineProperty(Material.prototype, "pointsCloud", {
  23927. get: function () {
  23928. return this._fillMode === Material.PointFillMode;
  23929. },
  23930. set: function (value) {
  23931. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  23932. },
  23933. enumerable: true,
  23934. configurable: true
  23935. });
  23936. Object.defineProperty(Material.prototype, "fillMode", {
  23937. get: function () {
  23938. return this._fillMode;
  23939. },
  23940. set: function (value) {
  23941. this._fillMode = value;
  23942. },
  23943. enumerable: true,
  23944. configurable: true
  23945. });
  23946. /**
  23947. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23948. * subclasses should override adding information pertainent to themselves
  23949. */
  23950. Material.prototype.toString = function (fullDetails) {
  23951. var ret = "Name: " + this.name;
  23952. if (fullDetails) {
  23953. }
  23954. return ret;
  23955. };
  23956. Object.defineProperty(Material.prototype, "isFrozen", {
  23957. get: function () {
  23958. return this.checkReadyOnlyOnce;
  23959. },
  23960. enumerable: true,
  23961. configurable: true
  23962. });
  23963. Material.prototype.freeze = function () {
  23964. this.checkReadyOnlyOnce = true;
  23965. };
  23966. Material.prototype.unfreeze = function () {
  23967. this.checkReadyOnlyOnce = false;
  23968. };
  23969. Material.prototype.isReady = function (mesh, useInstances) {
  23970. return true;
  23971. };
  23972. Material.prototype.getEffect = function () {
  23973. return this._effect;
  23974. };
  23975. Material.prototype.getScene = function () {
  23976. return this._scene;
  23977. };
  23978. Material.prototype.needAlphaBlending = function () {
  23979. return (this.alpha < 1.0);
  23980. };
  23981. Material.prototype.needAlphaTesting = function () {
  23982. return false;
  23983. };
  23984. Material.prototype.getAlphaTestTexture = function () {
  23985. return null;
  23986. };
  23987. Material.prototype.markDirty = function () {
  23988. this._wasPreviouslyReady = false;
  23989. };
  23990. Material.prototype._preBind = function () {
  23991. var engine = this._scene.getEngine();
  23992. engine.enableEffect(this._effect);
  23993. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  23994. };
  23995. Material.prototype.bind = function (world, mesh) {
  23996. this._scene._cachedMaterial = this;
  23997. this.onBindObservable.notifyObservers(mesh);
  23998. if (this.disableDepthWrite) {
  23999. var engine = this._scene.getEngine();
  24000. this._cachedDepthWriteState = engine.getDepthWrite();
  24001. engine.setDepthWrite(false);
  24002. }
  24003. };
  24004. Material.prototype.bindOnlyWorldMatrix = function (world) {
  24005. };
  24006. Material.prototype.unbind = function () {
  24007. if (this.disableDepthWrite) {
  24008. var engine = this._scene.getEngine();
  24009. engine.setDepthWrite(this._cachedDepthWriteState);
  24010. }
  24011. };
  24012. Material.prototype.clone = function (name) {
  24013. return null;
  24014. };
  24015. Material.prototype.getBindedMeshes = function () {
  24016. var result = new Array();
  24017. for (var index = 0; index < this._scene.meshes.length; index++) {
  24018. var mesh = this._scene.meshes[index];
  24019. if (mesh.material === this) {
  24020. result.push(mesh);
  24021. }
  24022. }
  24023. return result;
  24024. };
  24025. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24026. // Animations
  24027. this.getScene().stopAnimation(this);
  24028. // Remove from scene
  24029. var index = this._scene.materials.indexOf(this);
  24030. if (index >= 0) {
  24031. this._scene.materials.splice(index, 1);
  24032. }
  24033. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  24034. if (forceDisposeEffect && this._effect) {
  24035. this._scene.getEngine()._releaseEffect(this._effect);
  24036. this._effect = null;
  24037. }
  24038. // Remove from meshes
  24039. for (index = 0; index < this._scene.meshes.length; index++) {
  24040. var mesh = this._scene.meshes[index];
  24041. if (mesh.material === this) {
  24042. mesh.material = null;
  24043. }
  24044. }
  24045. // Callback
  24046. this.onDisposeObservable.notifyObservers(this);
  24047. this.onDisposeObservable.clear();
  24048. this.onBindObservable.clear();
  24049. };
  24050. Material.prototype.serialize = function () {
  24051. return BABYLON.SerializationHelper.Serialize(this);
  24052. };
  24053. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  24054. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  24055. multiMaterial.id = parsedMultiMaterial.id;
  24056. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  24057. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  24058. var subMatId = parsedMultiMaterial.materials[matIndex];
  24059. if (subMatId) {
  24060. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  24061. }
  24062. else {
  24063. multiMaterial.subMaterials.push(null);
  24064. }
  24065. }
  24066. return multiMaterial;
  24067. };
  24068. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  24069. if (!parsedMaterial.customType) {
  24070. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  24071. }
  24072. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  24073. return materialType.Parse(parsedMaterial, scene, rootUrl);
  24074. ;
  24075. };
  24076. Material._TriangleFillMode = 0;
  24077. Material._WireFrameFillMode = 1;
  24078. Material._PointFillMode = 2;
  24079. Material._ClockWiseSideOrientation = 0;
  24080. Material._CounterClockWiseSideOrientation = 1;
  24081. __decorate([
  24082. BABYLON.serialize()
  24083. ], Material.prototype, "id", void 0);
  24084. __decorate([
  24085. BABYLON.serialize()
  24086. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  24087. __decorate([
  24088. BABYLON.serialize()
  24089. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  24090. __decorate([
  24091. BABYLON.serialize()
  24092. ], Material.prototype, "state", void 0);
  24093. __decorate([
  24094. BABYLON.serialize()
  24095. ], Material.prototype, "alpha", void 0);
  24096. __decorate([
  24097. BABYLON.serialize()
  24098. ], Material.prototype, "backFaceCulling", void 0);
  24099. __decorate([
  24100. BABYLON.serialize()
  24101. ], Material.prototype, "sideOrientation", void 0);
  24102. __decorate([
  24103. BABYLON.serialize()
  24104. ], Material.prototype, "alphaMode", void 0);
  24105. __decorate([
  24106. BABYLON.serialize()
  24107. ], Material.prototype, "disableDepthWrite", void 0);
  24108. __decorate([
  24109. BABYLON.serialize()
  24110. ], Material.prototype, "fogEnabled", void 0);
  24111. __decorate([
  24112. BABYLON.serialize()
  24113. ], Material.prototype, "pointSize", void 0);
  24114. __decorate([
  24115. BABYLON.serialize()
  24116. ], Material.prototype, "zOffset", void 0);
  24117. __decorate([
  24118. BABYLON.serialize()
  24119. ], Material.prototype, "wireframe", null);
  24120. __decorate([
  24121. BABYLON.serialize()
  24122. ], Material.prototype, "pointsCloud", null);
  24123. __decorate([
  24124. BABYLON.serialize()
  24125. ], Material.prototype, "fillMode", null);
  24126. return Material;
  24127. }());
  24128. BABYLON.Material = Material;
  24129. })(BABYLON || (BABYLON = {}));
  24130. var BABYLON;
  24131. (function (BABYLON) {
  24132. var StandardMaterialDefines = (function (_super) {
  24133. __extends(StandardMaterialDefines, _super);
  24134. function StandardMaterialDefines() {
  24135. _super.call(this);
  24136. this.DIFFUSE = false;
  24137. this.AMBIENT = false;
  24138. this.OPACITY = false;
  24139. this.OPACITYRGB = false;
  24140. this.REFLECTION = false;
  24141. this.EMISSIVE = false;
  24142. this.SPECULAR = false;
  24143. this.BUMP = false;
  24144. this.PARALLAX = false;
  24145. this.PARALLAXOCCLUSION = false;
  24146. this.SPECULAROVERALPHA = false;
  24147. this.CLIPPLANE = false;
  24148. this.ALPHATEST = false;
  24149. this.ALPHAFROMDIFFUSE = false;
  24150. this.POINTSIZE = false;
  24151. this.FOG = false;
  24152. this.SPECULARTERM = false;
  24153. this.DIFFUSEFRESNEL = false;
  24154. this.OPACITYFRESNEL = false;
  24155. this.REFLECTIONFRESNEL = false;
  24156. this.REFRACTIONFRESNEL = false;
  24157. this.EMISSIVEFRESNEL = false;
  24158. this.FRESNEL = false;
  24159. this.NORMAL = false;
  24160. this.UV1 = false;
  24161. this.UV2 = false;
  24162. this.VERTEXCOLOR = false;
  24163. this.VERTEXALPHA = false;
  24164. this.NUM_BONE_INFLUENCERS = 0;
  24165. this.BonesPerMesh = 0;
  24166. this.INSTANCES = false;
  24167. this.GLOSSINESS = false;
  24168. this.ROUGHNESS = false;
  24169. this.EMISSIVEASILLUMINATION = false;
  24170. this.LINKEMISSIVEWITHDIFFUSE = false;
  24171. this.REFLECTIONFRESNELFROMSPECULAR = false;
  24172. this.LIGHTMAP = false;
  24173. this.USELIGHTMAPASSHADOWMAP = false;
  24174. this.REFLECTIONMAP_3D = false;
  24175. this.REFLECTIONMAP_SPHERICAL = false;
  24176. this.REFLECTIONMAP_PLANAR = false;
  24177. this.REFLECTIONMAP_CUBIC = false;
  24178. this.REFLECTIONMAP_PROJECTION = false;
  24179. this.REFLECTIONMAP_SKYBOX = false;
  24180. this.REFLECTIONMAP_EXPLICIT = false;
  24181. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  24182. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  24183. this.INVERTCUBICMAP = false;
  24184. this.LOGARITHMICDEPTH = false;
  24185. this.REFRACTION = false;
  24186. this.REFRACTIONMAP_3D = false;
  24187. this.REFLECTIONOVERALPHA = false;
  24188. this.INVERTNORMALMAPX = false;
  24189. this.INVERTNORMALMAPY = false;
  24190. this.SHADOWFULLFLOAT = false;
  24191. this.CAMERACOLORGRADING = false;
  24192. this.CAMERACOLORCURVES = false;
  24193. this.rebuild();
  24194. }
  24195. return StandardMaterialDefines;
  24196. }(BABYLON.MaterialDefines));
  24197. var StandardMaterial = (function (_super) {
  24198. __extends(StandardMaterial, _super);
  24199. function StandardMaterial(name, scene) {
  24200. var _this = this;
  24201. _super.call(this, name, scene);
  24202. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24203. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  24204. this.specularColor = new BABYLON.Color3(1, 1, 1);
  24205. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  24206. this.specularPower = 64;
  24207. this.useAlphaFromDiffuseTexture = false;
  24208. this.useEmissiveAsIllumination = false;
  24209. this.linkEmissiveWithDiffuse = false;
  24210. this.useReflectionFresnelFromSpecular = false;
  24211. this.useSpecularOverAlpha = false;
  24212. this.useReflectionOverAlpha = false;
  24213. this.disableLighting = false;
  24214. this.useParallax = false;
  24215. this.useParallaxOcclusion = false;
  24216. this.parallaxScaleBias = 0.05;
  24217. this.roughness = 0;
  24218. this.indexOfRefraction = 0.98;
  24219. this.invertRefractionY = true;
  24220. this.useLightmapAsShadowmap = false;
  24221. this.useGlossinessFromSpecularMapAlpha = false;
  24222. this.maxSimultaneousLights = 4;
  24223. /**
  24224. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  24225. */
  24226. this.invertNormalMapX = false;
  24227. /**
  24228. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  24229. */
  24230. this.invertNormalMapY = false;
  24231. /**
  24232. * Color Grading 2D Lookup Texture.
  24233. * This allows special effects like sepia, black and white to sixties rendering style.
  24234. */
  24235. this.cameraColorGradingTexture = null;
  24236. /**
  24237. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  24238. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  24239. * 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;
  24240. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  24241. */
  24242. this.cameraColorCurves = null;
  24243. this._renderTargets = new BABYLON.SmartArray(16);
  24244. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  24245. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  24246. this._defines = new StandardMaterialDefines();
  24247. this._cachedDefines = new StandardMaterialDefines();
  24248. this._cachedDefines.BonesPerMesh = -1;
  24249. this.getRenderTargetTextures = function () {
  24250. _this._renderTargets.reset();
  24251. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  24252. _this._renderTargets.push(_this.reflectionTexture);
  24253. }
  24254. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  24255. _this._renderTargets.push(_this.refractionTexture);
  24256. }
  24257. return _this._renderTargets;
  24258. };
  24259. }
  24260. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  24261. get: function () {
  24262. return this._useLogarithmicDepth;
  24263. },
  24264. set: function (value) {
  24265. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  24266. },
  24267. enumerable: true,
  24268. configurable: true
  24269. });
  24270. StandardMaterial.prototype.needAlphaBlending = function () {
  24271. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  24272. };
  24273. StandardMaterial.prototype.needAlphaTesting = function () {
  24274. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  24275. };
  24276. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  24277. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  24278. };
  24279. StandardMaterial.prototype.getAlphaTestTexture = function () {
  24280. return this.diffuseTexture;
  24281. };
  24282. // Methods
  24283. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  24284. if (!mesh) {
  24285. return true;
  24286. }
  24287. if (this._defines.INSTANCES !== useInstances) {
  24288. return false;
  24289. }
  24290. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  24291. return true;
  24292. }
  24293. return false;
  24294. };
  24295. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  24296. if (this.isFrozen) {
  24297. if (this._wasPreviouslyReady) {
  24298. return true;
  24299. }
  24300. }
  24301. var scene = this.getScene();
  24302. if (!this.checkReadyOnEveryCall) {
  24303. if (this._renderId === scene.getRenderId()) {
  24304. if (this._checkCache(scene, mesh, useInstances)) {
  24305. return true;
  24306. }
  24307. }
  24308. }
  24309. var engine = scene.getEngine();
  24310. var needNormals = false;
  24311. var needUVs = false;
  24312. this._defines.reset();
  24313. // Textures
  24314. if (scene.texturesEnabled) {
  24315. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  24316. if (!this.diffuseTexture.isReady()) {
  24317. return false;
  24318. }
  24319. else {
  24320. needUVs = true;
  24321. this._defines.DIFFUSE = true;
  24322. }
  24323. }
  24324. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  24325. if (!this.ambientTexture.isReady()) {
  24326. return false;
  24327. }
  24328. else {
  24329. needUVs = true;
  24330. this._defines.AMBIENT = true;
  24331. }
  24332. }
  24333. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  24334. if (!this.opacityTexture.isReady()) {
  24335. return false;
  24336. }
  24337. else {
  24338. needUVs = true;
  24339. this._defines.OPACITY = true;
  24340. if (this.opacityTexture.getAlphaFromRGB) {
  24341. this._defines.OPACITYRGB = true;
  24342. }
  24343. }
  24344. }
  24345. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  24346. if (!this.reflectionTexture.isReady()) {
  24347. return false;
  24348. }
  24349. else {
  24350. needNormals = true;
  24351. this._defines.REFLECTION = true;
  24352. if (this.roughness > 0) {
  24353. this._defines.ROUGHNESS = true;
  24354. }
  24355. if (this.useReflectionOverAlpha) {
  24356. this._defines.REFLECTIONOVERALPHA = true;
  24357. }
  24358. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  24359. this._defines.INVERTCUBICMAP = true;
  24360. }
  24361. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  24362. switch (this.reflectionTexture.coordinatesMode) {
  24363. case BABYLON.Texture.CUBIC_MODE:
  24364. case BABYLON.Texture.INVCUBIC_MODE:
  24365. this._defines.REFLECTIONMAP_CUBIC = true;
  24366. break;
  24367. case BABYLON.Texture.EXPLICIT_MODE:
  24368. this._defines.REFLECTIONMAP_EXPLICIT = true;
  24369. break;
  24370. case BABYLON.Texture.PLANAR_MODE:
  24371. this._defines.REFLECTIONMAP_PLANAR = true;
  24372. break;
  24373. case BABYLON.Texture.PROJECTION_MODE:
  24374. this._defines.REFLECTIONMAP_PROJECTION = true;
  24375. break;
  24376. case BABYLON.Texture.SKYBOX_MODE:
  24377. this._defines.REFLECTIONMAP_SKYBOX = true;
  24378. break;
  24379. case BABYLON.Texture.SPHERICAL_MODE:
  24380. this._defines.REFLECTIONMAP_SPHERICAL = true;
  24381. break;
  24382. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  24383. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  24384. break;
  24385. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  24386. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  24387. break;
  24388. }
  24389. }
  24390. }
  24391. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  24392. if (!this.emissiveTexture.isReady()) {
  24393. return false;
  24394. }
  24395. else {
  24396. needUVs = true;
  24397. this._defines.EMISSIVE = true;
  24398. }
  24399. }
  24400. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  24401. if (!this.lightmapTexture.isReady()) {
  24402. return false;
  24403. }
  24404. else {
  24405. needUVs = true;
  24406. this._defines.LIGHTMAP = true;
  24407. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  24408. }
  24409. }
  24410. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  24411. if (!this.specularTexture.isReady()) {
  24412. return false;
  24413. }
  24414. else {
  24415. needUVs = true;
  24416. this._defines.SPECULAR = true;
  24417. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  24418. }
  24419. }
  24420. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  24421. if (!this.bumpTexture.isReady()) {
  24422. return false;
  24423. }
  24424. else {
  24425. needUVs = true;
  24426. this._defines.BUMP = true;
  24427. if (this.useParallax) {
  24428. this._defines.PARALLAX = true;
  24429. if (this.useParallaxOcclusion) {
  24430. this._defines.PARALLAXOCCLUSION = true;
  24431. }
  24432. }
  24433. if (this.invertNormalMapX) {
  24434. this._defines.INVERTNORMALMAPX = true;
  24435. }
  24436. if (this.invertNormalMapY) {
  24437. this._defines.INVERTNORMALMAPY = true;
  24438. }
  24439. }
  24440. }
  24441. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  24442. if (!this.refractionTexture.isReady()) {
  24443. return false;
  24444. }
  24445. else {
  24446. needUVs = true;
  24447. this._defines.REFRACTION = true;
  24448. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  24449. }
  24450. }
  24451. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  24452. if (!this.cameraColorGradingTexture.isReady()) {
  24453. return false;
  24454. }
  24455. else {
  24456. this._defines.CAMERACOLORGRADING = true;
  24457. }
  24458. }
  24459. }
  24460. // Effect
  24461. if (scene.clipPlane) {
  24462. this._defines.CLIPPLANE = true;
  24463. }
  24464. if (engine.getAlphaTesting()) {
  24465. this._defines.ALPHATEST = true;
  24466. }
  24467. if (this._shouldUseAlphaFromDiffuseTexture()) {
  24468. this._defines.ALPHAFROMDIFFUSE = true;
  24469. }
  24470. if (this.useEmissiveAsIllumination) {
  24471. this._defines.EMISSIVEASILLUMINATION = true;
  24472. }
  24473. if (this.linkEmissiveWithDiffuse) {
  24474. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  24475. }
  24476. if (this.useLogarithmicDepth) {
  24477. this._defines.LOGARITHMICDEPTH = true;
  24478. }
  24479. if (this.cameraColorCurves) {
  24480. this._defines.CAMERACOLORCURVES = true;
  24481. }
  24482. // Point size
  24483. if (this.pointsCloud || scene.forcePointsCloud) {
  24484. this._defines.POINTSIZE = true;
  24485. }
  24486. // Fog
  24487. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  24488. this._defines.FOG = true;
  24489. }
  24490. if (scene.lightsEnabled && !this.disableLighting) {
  24491. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  24492. }
  24493. if (StandardMaterial.FresnelEnabled) {
  24494. // Fresnel
  24495. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  24496. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  24497. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  24498. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  24499. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  24500. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  24501. this._defines.DIFFUSEFRESNEL = true;
  24502. }
  24503. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  24504. this._defines.OPACITYFRESNEL = true;
  24505. }
  24506. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  24507. this._defines.REFLECTIONFRESNEL = true;
  24508. if (this.useReflectionFresnelFromSpecular) {
  24509. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  24510. }
  24511. }
  24512. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  24513. this._defines.REFRACTIONFRESNEL = true;
  24514. }
  24515. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  24516. this._defines.EMISSIVEFRESNEL = true;
  24517. }
  24518. needNormals = true;
  24519. this._defines.FRESNEL = true;
  24520. }
  24521. }
  24522. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  24523. this._defines.SPECULAROVERALPHA = true;
  24524. }
  24525. // Attribs
  24526. if (mesh) {
  24527. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24528. this._defines.NORMAL = true;
  24529. }
  24530. if (needUVs) {
  24531. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24532. this._defines.UV1 = true;
  24533. }
  24534. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24535. this._defines.UV2 = true;
  24536. }
  24537. }
  24538. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24539. this._defines.VERTEXCOLOR = true;
  24540. if (mesh.hasVertexAlpha) {
  24541. this._defines.VERTEXALPHA = true;
  24542. }
  24543. }
  24544. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  24545. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  24546. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  24547. }
  24548. // Instances
  24549. if (useInstances) {
  24550. this._defines.INSTANCES = true;
  24551. }
  24552. }
  24553. // Get correct effect
  24554. if (!this._defines.isEqual(this._cachedDefines)) {
  24555. this._defines.cloneTo(this._cachedDefines);
  24556. scene.resetCachedMaterial();
  24557. // Fallbacks
  24558. var fallbacks = new BABYLON.EffectFallbacks();
  24559. if (this._defines.REFLECTION) {
  24560. fallbacks.addFallback(0, "REFLECTION");
  24561. }
  24562. if (this._defines.SPECULAR) {
  24563. fallbacks.addFallback(0, "SPECULAR");
  24564. }
  24565. if (this._defines.BUMP) {
  24566. fallbacks.addFallback(0, "BUMP");
  24567. }
  24568. if (this._defines.PARALLAX) {
  24569. fallbacks.addFallback(1, "PARALLAX");
  24570. }
  24571. if (this._defines.PARALLAXOCCLUSION) {
  24572. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  24573. }
  24574. if (this._defines.SPECULAROVERALPHA) {
  24575. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  24576. }
  24577. if (this._defines.FOG) {
  24578. fallbacks.addFallback(1, "FOG");
  24579. }
  24580. if (this._defines.POINTSIZE) {
  24581. fallbacks.addFallback(0, "POINTSIZE");
  24582. }
  24583. if (this._defines.LOGARITHMICDEPTH) {
  24584. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  24585. }
  24586. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  24587. if (this._defines.SPECULARTERM) {
  24588. fallbacks.addFallback(0, "SPECULARTERM");
  24589. }
  24590. if (this._defines.DIFFUSEFRESNEL) {
  24591. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  24592. }
  24593. if (this._defines.OPACITYFRESNEL) {
  24594. fallbacks.addFallback(2, "OPACITYFRESNEL");
  24595. }
  24596. if (this._defines.REFLECTIONFRESNEL) {
  24597. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  24598. }
  24599. if (this._defines.EMISSIVEFRESNEL) {
  24600. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  24601. }
  24602. if (this._defines.FRESNEL) {
  24603. fallbacks.addFallback(4, "FRESNEL");
  24604. }
  24605. //Attributes
  24606. var attribs = [BABYLON.VertexBuffer.PositionKind];
  24607. if (this._defines.NORMAL) {
  24608. attribs.push(BABYLON.VertexBuffer.NormalKind);
  24609. }
  24610. if (this._defines.UV1) {
  24611. attribs.push(BABYLON.VertexBuffer.UVKind);
  24612. }
  24613. if (this._defines.UV2) {
  24614. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  24615. }
  24616. if (this._defines.VERTEXCOLOR) {
  24617. attribs.push(BABYLON.VertexBuffer.ColorKind);
  24618. }
  24619. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  24620. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  24621. // Legacy browser patch
  24622. var shaderName = "default";
  24623. if (!scene.getEngine().getCaps().standardDerivatives) {
  24624. shaderName = "legacydefault";
  24625. }
  24626. var join = this._defines.toString();
  24627. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  24628. "vFogInfos", "vFogColor", "pointSize",
  24629. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  24630. "mBones",
  24631. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  24632. "depthValues",
  24633. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  24634. "logarithmicDepthConstant"
  24635. ];
  24636. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  24637. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  24638. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  24639. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  24640. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  24641. }
  24642. if (!this._effect.isReady()) {
  24643. return false;
  24644. }
  24645. this._renderId = scene.getRenderId();
  24646. this._wasPreviouslyReady = true;
  24647. if (mesh) {
  24648. if (!mesh._materialDefines) {
  24649. mesh._materialDefines = new StandardMaterialDefines();
  24650. }
  24651. this._defines.cloneTo(mesh._materialDefines);
  24652. }
  24653. return true;
  24654. };
  24655. StandardMaterial.prototype.unbind = function () {
  24656. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  24657. this._effect.setTexture("reflection2DSampler", null);
  24658. }
  24659. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  24660. this._effect.setTexture("refraction2DSampler", null);
  24661. }
  24662. _super.prototype.unbind.call(this);
  24663. };
  24664. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24665. this._effect.setMatrix("world", world);
  24666. };
  24667. StandardMaterial.prototype.bind = function (world, mesh) {
  24668. var scene = this.getScene();
  24669. // Matrices
  24670. this.bindOnlyWorldMatrix(world);
  24671. // Bones
  24672. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  24673. if (scene.getCachedMaterial() !== this) {
  24674. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  24675. if (StandardMaterial.FresnelEnabled) {
  24676. // Fresnel
  24677. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  24678. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  24679. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  24680. }
  24681. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  24682. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  24683. }
  24684. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  24685. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  24686. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  24687. }
  24688. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  24689. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  24690. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  24691. }
  24692. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  24693. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  24694. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  24695. }
  24696. }
  24697. // Textures
  24698. if (scene.texturesEnabled) {
  24699. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  24700. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  24701. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  24702. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  24703. }
  24704. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  24705. this._effect.setTexture("ambientSampler", this.ambientTexture);
  24706. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  24707. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  24708. }
  24709. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  24710. this._effect.setTexture("opacitySampler", this.opacityTexture);
  24711. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  24712. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  24713. }
  24714. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  24715. if (this.reflectionTexture.isCube) {
  24716. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  24717. }
  24718. else {
  24719. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  24720. }
  24721. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  24722. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  24723. }
  24724. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  24725. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  24726. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  24727. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  24728. }
  24729. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  24730. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  24731. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  24732. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  24733. }
  24734. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  24735. this._effect.setTexture("specularSampler", this.specularTexture);
  24736. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  24737. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  24738. }
  24739. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  24740. this._effect.setTexture("bumpSampler", this.bumpTexture);
  24741. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  24742. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  24743. }
  24744. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  24745. var depth = 1.0;
  24746. if (this.refractionTexture.isCube) {
  24747. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  24748. }
  24749. else {
  24750. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  24751. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  24752. if (this.refractionTexture.depth) {
  24753. depth = this.refractionTexture.depth;
  24754. }
  24755. }
  24756. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  24757. }
  24758. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  24759. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  24760. }
  24761. }
  24762. // Clip plane
  24763. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  24764. // Point size
  24765. if (this.pointsCloud) {
  24766. this._effect.setFloat("pointSize", this.pointSize);
  24767. }
  24768. // Colors
  24769. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  24770. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  24771. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  24772. if (this._defines.SPECULARTERM) {
  24773. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  24774. }
  24775. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  24776. }
  24777. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  24778. // Diffuse
  24779. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  24780. // Lights
  24781. if (scene.lightsEnabled && !this.disableLighting) {
  24782. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  24783. }
  24784. // View
  24785. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  24786. this._effect.setMatrix("view", scene.getViewMatrix());
  24787. }
  24788. // Fog
  24789. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  24790. // Log. depth
  24791. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  24792. // Color Curves
  24793. if (this.cameraColorCurves) {
  24794. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  24795. }
  24796. }
  24797. _super.prototype.bind.call(this, world, mesh);
  24798. };
  24799. StandardMaterial.prototype.getAnimatables = function () {
  24800. var results = [];
  24801. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  24802. results.push(this.diffuseTexture);
  24803. }
  24804. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  24805. results.push(this.ambientTexture);
  24806. }
  24807. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  24808. results.push(this.opacityTexture);
  24809. }
  24810. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  24811. results.push(this.reflectionTexture);
  24812. }
  24813. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  24814. results.push(this.emissiveTexture);
  24815. }
  24816. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  24817. results.push(this.specularTexture);
  24818. }
  24819. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  24820. results.push(this.bumpTexture);
  24821. }
  24822. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  24823. results.push(this.lightmapTexture);
  24824. }
  24825. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  24826. results.push(this.refractionTexture);
  24827. }
  24828. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  24829. results.push(this.cameraColorGradingTexture);
  24830. }
  24831. return results;
  24832. };
  24833. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24834. if (forceDisposeTextures) {
  24835. if (this.diffuseTexture) {
  24836. this.diffuseTexture.dispose();
  24837. }
  24838. if (this.ambientTexture) {
  24839. this.ambientTexture.dispose();
  24840. }
  24841. if (this.opacityTexture) {
  24842. this.opacityTexture.dispose();
  24843. }
  24844. if (this.reflectionTexture) {
  24845. this.reflectionTexture.dispose();
  24846. }
  24847. if (this.emissiveTexture) {
  24848. this.emissiveTexture.dispose();
  24849. }
  24850. if (this.specularTexture) {
  24851. this.specularTexture.dispose();
  24852. }
  24853. if (this.bumpTexture) {
  24854. this.bumpTexture.dispose();
  24855. }
  24856. if (this.lightmapTexture) {
  24857. this.lightmapTexture.dispose();
  24858. }
  24859. if (this.refractionTexture) {
  24860. this.refractionTexture.dispose();
  24861. }
  24862. if (this.cameraColorGradingTexture) {
  24863. this.cameraColorGradingTexture.dispose();
  24864. }
  24865. }
  24866. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  24867. };
  24868. StandardMaterial.prototype.clone = function (name) {
  24869. var _this = this;
  24870. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  24871. };
  24872. StandardMaterial.prototype.serialize = function () {
  24873. return BABYLON.SerializationHelper.Serialize(this);
  24874. };
  24875. // Statics
  24876. StandardMaterial.Parse = function (source, scene, rootUrl) {
  24877. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  24878. };
  24879. // Flags used to enable or disable a type of texture for all Standard Materials
  24880. StandardMaterial.DiffuseTextureEnabled = true;
  24881. StandardMaterial.AmbientTextureEnabled = true;
  24882. StandardMaterial.OpacityTextureEnabled = true;
  24883. StandardMaterial.ReflectionTextureEnabled = true;
  24884. StandardMaterial.EmissiveTextureEnabled = true;
  24885. StandardMaterial.SpecularTextureEnabled = true;
  24886. StandardMaterial.BumpTextureEnabled = true;
  24887. StandardMaterial.FresnelEnabled = true;
  24888. StandardMaterial.LightmapTextureEnabled = true;
  24889. StandardMaterial.RefractionTextureEnabled = true;
  24890. StandardMaterial.ColorGradingTextureEnabled = true;
  24891. __decorate([
  24892. BABYLON.serializeAsTexture()
  24893. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  24894. __decorate([
  24895. BABYLON.serializeAsTexture()
  24896. ], StandardMaterial.prototype, "ambientTexture", void 0);
  24897. __decorate([
  24898. BABYLON.serializeAsTexture()
  24899. ], StandardMaterial.prototype, "opacityTexture", void 0);
  24900. __decorate([
  24901. BABYLON.serializeAsTexture()
  24902. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  24903. __decorate([
  24904. BABYLON.serializeAsTexture()
  24905. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  24906. __decorate([
  24907. BABYLON.serializeAsTexture()
  24908. ], StandardMaterial.prototype, "specularTexture", void 0);
  24909. __decorate([
  24910. BABYLON.serializeAsTexture()
  24911. ], StandardMaterial.prototype, "bumpTexture", void 0);
  24912. __decorate([
  24913. BABYLON.serializeAsTexture()
  24914. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  24915. __decorate([
  24916. BABYLON.serializeAsTexture()
  24917. ], StandardMaterial.prototype, "refractionTexture", void 0);
  24918. __decorate([
  24919. BABYLON.serializeAsColor3("ambient")
  24920. ], StandardMaterial.prototype, "ambientColor", void 0);
  24921. __decorate([
  24922. BABYLON.serializeAsColor3("diffuse")
  24923. ], StandardMaterial.prototype, "diffuseColor", void 0);
  24924. __decorate([
  24925. BABYLON.serializeAsColor3("specular")
  24926. ], StandardMaterial.prototype, "specularColor", void 0);
  24927. __decorate([
  24928. BABYLON.serializeAsColor3("emissive")
  24929. ], StandardMaterial.prototype, "emissiveColor", void 0);
  24930. __decorate([
  24931. BABYLON.serialize()
  24932. ], StandardMaterial.prototype, "specularPower", void 0);
  24933. __decorate([
  24934. BABYLON.serialize()
  24935. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  24936. __decorate([
  24937. BABYLON.serialize()
  24938. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  24939. __decorate([
  24940. BABYLON.serialize()
  24941. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  24942. __decorate([
  24943. BABYLON.serialize()
  24944. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  24945. __decorate([
  24946. BABYLON.serialize()
  24947. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  24948. __decorate([
  24949. BABYLON.serialize()
  24950. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  24951. __decorate([
  24952. BABYLON.serialize()
  24953. ], StandardMaterial.prototype, "disableLighting", void 0);
  24954. __decorate([
  24955. BABYLON.serialize()
  24956. ], StandardMaterial.prototype, "useParallax", void 0);
  24957. __decorate([
  24958. BABYLON.serialize()
  24959. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  24960. __decorate([
  24961. BABYLON.serialize()
  24962. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  24963. __decorate([
  24964. BABYLON.serialize()
  24965. ], StandardMaterial.prototype, "roughness", void 0);
  24966. __decorate([
  24967. BABYLON.serialize()
  24968. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  24969. __decorate([
  24970. BABYLON.serialize()
  24971. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  24972. __decorate([
  24973. BABYLON.serialize()
  24974. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  24975. __decorate([
  24976. BABYLON.serializeAsFresnelParameters()
  24977. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  24978. __decorate([
  24979. BABYLON.serializeAsFresnelParameters()
  24980. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  24981. __decorate([
  24982. BABYLON.serializeAsFresnelParameters()
  24983. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  24984. __decorate([
  24985. BABYLON.serializeAsFresnelParameters()
  24986. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  24987. __decorate([
  24988. BABYLON.serializeAsFresnelParameters()
  24989. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  24990. __decorate([
  24991. BABYLON.serialize()
  24992. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  24993. __decorate([
  24994. BABYLON.serialize()
  24995. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  24996. __decorate([
  24997. BABYLON.serialize()
  24998. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  24999. __decorate([
  25000. BABYLON.serialize()
  25001. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  25002. __decorate([
  25003. BABYLON.serializeAsTexture()
  25004. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  25005. __decorate([
  25006. BABYLON.serializeAsColorCurves()
  25007. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  25008. __decorate([
  25009. BABYLON.serialize()
  25010. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  25011. return StandardMaterial;
  25012. }(BABYLON.Material));
  25013. BABYLON.StandardMaterial = StandardMaterial;
  25014. })(BABYLON || (BABYLON = {}));
  25015. var BABYLON;
  25016. (function (BABYLON) {
  25017. var MultiMaterial = (function (_super) {
  25018. __extends(MultiMaterial, _super);
  25019. function MultiMaterial(name, scene) {
  25020. _super.call(this, name, scene, true);
  25021. this.subMaterials = new Array();
  25022. scene.multiMaterials.push(this);
  25023. }
  25024. // Properties
  25025. MultiMaterial.prototype.getSubMaterial = function (index) {
  25026. if (index < 0 || index >= this.subMaterials.length) {
  25027. return this.getScene().defaultMaterial;
  25028. }
  25029. return this.subMaterials[index];
  25030. };
  25031. // Methods
  25032. MultiMaterial.prototype.isReady = function (mesh) {
  25033. for (var index = 0; index < this.subMaterials.length; index++) {
  25034. var subMaterial = this.subMaterials[index];
  25035. if (subMaterial) {
  25036. if (!this.subMaterials[index].isReady(mesh)) {
  25037. return false;
  25038. }
  25039. }
  25040. }
  25041. return true;
  25042. };
  25043. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  25044. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  25045. for (var index = 0; index < this.subMaterials.length; index++) {
  25046. var subMaterial = null;
  25047. if (cloneChildren) {
  25048. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  25049. }
  25050. else {
  25051. subMaterial = this.subMaterials[index];
  25052. }
  25053. newMultiMaterial.subMaterials.push(subMaterial);
  25054. }
  25055. return newMultiMaterial;
  25056. };
  25057. MultiMaterial.prototype.serialize = function () {
  25058. var serializationObject = {};
  25059. serializationObject.name = this.name;
  25060. serializationObject.id = this.id;
  25061. serializationObject.tags = BABYLON.Tags.GetTags(this);
  25062. serializationObject.materials = [];
  25063. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  25064. var subMat = this.subMaterials[matIndex];
  25065. if (subMat) {
  25066. serializationObject.materials.push(subMat.id);
  25067. }
  25068. else {
  25069. serializationObject.materials.push(null);
  25070. }
  25071. }
  25072. return serializationObject;
  25073. };
  25074. return MultiMaterial;
  25075. }(BABYLON.Material));
  25076. BABYLON.MultiMaterial = MultiMaterial;
  25077. })(BABYLON || (BABYLON = {}));
  25078. var BABYLON;
  25079. (function (BABYLON) {
  25080. var SceneLoader = (function () {
  25081. function SceneLoader() {
  25082. }
  25083. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  25084. get: function () {
  25085. return 0;
  25086. },
  25087. enumerable: true,
  25088. configurable: true
  25089. });
  25090. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  25091. get: function () {
  25092. return 1;
  25093. },
  25094. enumerable: true,
  25095. configurable: true
  25096. });
  25097. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  25098. get: function () {
  25099. return 2;
  25100. },
  25101. enumerable: true,
  25102. configurable: true
  25103. });
  25104. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  25105. get: function () {
  25106. return 3;
  25107. },
  25108. enumerable: true,
  25109. configurable: true
  25110. });
  25111. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  25112. get: function () {
  25113. return SceneLoader._ForceFullSceneLoadingForIncremental;
  25114. },
  25115. set: function (value) {
  25116. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  25117. },
  25118. enumerable: true,
  25119. configurable: true
  25120. });
  25121. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  25122. get: function () {
  25123. return SceneLoader._ShowLoadingScreen;
  25124. },
  25125. set: function (value) {
  25126. SceneLoader._ShowLoadingScreen = value;
  25127. },
  25128. enumerable: true,
  25129. configurable: true
  25130. });
  25131. Object.defineProperty(SceneLoader, "loggingLevel", {
  25132. get: function () {
  25133. return SceneLoader._loggingLevel;
  25134. },
  25135. set: function (value) {
  25136. SceneLoader._loggingLevel = value;
  25137. },
  25138. enumerable: true,
  25139. configurable: true
  25140. });
  25141. SceneLoader._getPluginForFilename = function (sceneFilename) {
  25142. var dotPosition = sceneFilename.lastIndexOf(".");
  25143. var queryStringPosition = sceneFilename.indexOf("?");
  25144. if (queryStringPosition === -1) {
  25145. queryStringPosition = sceneFilename.length;
  25146. }
  25147. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  25148. for (var index = 0; index < this._registeredPlugins.length; index++) {
  25149. var plugin = this._registeredPlugins[index];
  25150. if (plugin.extensions.indexOf(extension) !== -1) {
  25151. return plugin;
  25152. }
  25153. }
  25154. return this._registeredPlugins[0];
  25155. };
  25156. // Public functions
  25157. SceneLoader.GetPluginForExtension = function (extension) {
  25158. for (var index = 0; index < this._registeredPlugins.length; index++) {
  25159. var plugin = this._registeredPlugins[index];
  25160. if (plugin.extensions.indexOf(extension) !== -1) {
  25161. return plugin;
  25162. }
  25163. }
  25164. return null;
  25165. };
  25166. SceneLoader.RegisterPlugin = function (plugin) {
  25167. plugin.extensions = plugin.extensions.toLowerCase();
  25168. SceneLoader._registeredPlugins.push(plugin);
  25169. };
  25170. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  25171. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25172. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25173. return;
  25174. }
  25175. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25176. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25177. return;
  25178. }
  25179. var loadingToken = {};
  25180. scene._addPendingData(loadingToken);
  25181. var manifestChecked = function (success) {
  25182. scene.database = database;
  25183. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  25184. var importMeshFromData = function (data) {
  25185. var meshes = [];
  25186. var particleSystems = [];
  25187. var skeletons = [];
  25188. try {
  25189. if (plugin.importMesh) {
  25190. var syncedPlugin = plugin;
  25191. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  25192. if (onerror) {
  25193. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  25194. }
  25195. scene._removePendingData(loadingToken);
  25196. return;
  25197. }
  25198. if (onsuccess) {
  25199. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  25200. onsuccess(meshes, particleSystems, skeletons);
  25201. scene._removePendingData(loadingToken);
  25202. }
  25203. }
  25204. else {
  25205. var asyncedPlugin = plugin;
  25206. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  25207. if (onsuccess) {
  25208. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  25209. onsuccess(meshes, particleSystems, skeletons);
  25210. scene._removePendingData(loadingToken);
  25211. }
  25212. }, function () {
  25213. if (onerror) {
  25214. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  25215. }
  25216. scene._removePendingData(loadingToken);
  25217. });
  25218. }
  25219. }
  25220. catch (e) {
  25221. if (onerror) {
  25222. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  25223. }
  25224. scene._removePendingData(loadingToken);
  25225. }
  25226. };
  25227. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  25228. // Direct load
  25229. importMeshFromData(sceneFilename.substr(5));
  25230. return;
  25231. }
  25232. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  25233. importMeshFromData(data);
  25234. }, progressCallBack, database);
  25235. };
  25236. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  25237. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  25238. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  25239. }
  25240. else {
  25241. // If the scene is a data stream or offline support is not enabled, it's a direct load
  25242. manifestChecked(true);
  25243. }
  25244. };
  25245. /**
  25246. * Load a scene
  25247. * @param rootUrl a string that defines the root url for scene and resources
  25248. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  25249. * @param engine is the instance of BABYLON.Engine to use to create the scene
  25250. */
  25251. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  25252. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  25253. };
  25254. /**
  25255. * Append a scene
  25256. * @param rootUrl a string that defines the root url for scene and resources
  25257. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  25258. * @param scene is the instance of BABYLON.Scene to append to
  25259. */
  25260. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  25261. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25262. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25263. return;
  25264. }
  25265. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  25266. var database;
  25267. var loadingToken = {};
  25268. scene._addPendingData(loadingToken);
  25269. if (SceneLoader.ShowLoadingScreen) {
  25270. scene.getEngine().displayLoadingUI();
  25271. }
  25272. var loadSceneFromData = function (data) {
  25273. scene.database = database;
  25274. if (plugin.load) {
  25275. var syncedPlugin = plugin;
  25276. if (!syncedPlugin.load(scene, data, rootUrl)) {
  25277. if (onerror) {
  25278. onerror(scene);
  25279. }
  25280. scene._removePendingData(loadingToken);
  25281. scene.getEngine().hideLoadingUI();
  25282. return;
  25283. }
  25284. if (onsuccess) {
  25285. onsuccess(scene);
  25286. }
  25287. scene._removePendingData(loadingToken);
  25288. }
  25289. else {
  25290. var asyncedPlugin = plugin;
  25291. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  25292. if (onsuccess) {
  25293. onsuccess(scene);
  25294. }
  25295. }, function () {
  25296. if (onerror) {
  25297. onerror(scene);
  25298. }
  25299. scene._removePendingData(loadingToken);
  25300. scene.getEngine().hideLoadingUI();
  25301. });
  25302. }
  25303. if (SceneLoader.ShowLoadingScreen) {
  25304. scene.executeWhenReady(function () {
  25305. scene.getEngine().hideLoadingUI();
  25306. });
  25307. }
  25308. };
  25309. var manifestChecked = function (success) {
  25310. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  25311. };
  25312. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  25313. // Direct load
  25314. loadSceneFromData(sceneFilename.substr(5));
  25315. return;
  25316. }
  25317. if (rootUrl.indexOf("file:") === -1) {
  25318. if (scene.getEngine().enableOfflineSupport) {
  25319. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  25320. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  25321. }
  25322. else {
  25323. manifestChecked(true);
  25324. }
  25325. }
  25326. else {
  25327. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  25328. }
  25329. };
  25330. // Flags
  25331. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  25332. SceneLoader._ShowLoadingScreen = true;
  25333. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  25334. // Members
  25335. SceneLoader._registeredPlugins = new Array();
  25336. return SceneLoader;
  25337. }());
  25338. BABYLON.SceneLoader = SceneLoader;
  25339. ;
  25340. })(BABYLON || (BABYLON = {}));
  25341. var BABYLON;
  25342. (function (BABYLON) {
  25343. var Internals;
  25344. (function (Internals) {
  25345. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  25346. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  25347. var parsedMaterial = parsedData.materials[index];
  25348. if (parsedMaterial.id === id) {
  25349. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  25350. }
  25351. }
  25352. return null;
  25353. };
  25354. var isDescendantOf = function (mesh, names, hierarchyIds) {
  25355. names = (names instanceof Array) ? names : [names];
  25356. for (var i in names) {
  25357. if (mesh.name === names[i]) {
  25358. hierarchyIds.push(mesh.id);
  25359. return true;
  25360. }
  25361. }
  25362. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  25363. hierarchyIds.push(mesh.id);
  25364. return true;
  25365. }
  25366. return false;
  25367. };
  25368. var logOperation = function (operation, producer) {
  25369. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  25370. };
  25371. BABYLON.SceneLoader.RegisterPlugin({
  25372. extensions: ".babylon",
  25373. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  25374. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  25375. // when SceneLoader.debugLogging = true (default), or exception encountered.
  25376. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  25377. // and avoid problems with multiple concurrent .babylon loads.
  25378. var log = "importMesh has failed JSON parse";
  25379. try {
  25380. var parsedData = JSON.parse(data);
  25381. log = "";
  25382. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  25383. var loadedSkeletonsIds = [];
  25384. var loadedMaterialsIds = [];
  25385. var hierarchyIds = [];
  25386. var index;
  25387. var cache;
  25388. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  25389. var parsedMesh = parsedData.meshes[index];
  25390. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  25391. if (meshesNames instanceof Array) {
  25392. // Remove found mesh name from list.
  25393. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  25394. }
  25395. //Geometry?
  25396. if (parsedMesh.geometryId) {
  25397. //does the file contain geometries?
  25398. if (parsedData.geometries) {
  25399. //find the correct geometry and add it to the scene
  25400. var found = false;
  25401. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  25402. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  25403. return;
  25404. }
  25405. else {
  25406. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  25407. if (parsedGeometryData.id === parsedMesh.geometryId) {
  25408. switch (geometryType) {
  25409. case "boxes":
  25410. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  25411. break;
  25412. case "spheres":
  25413. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  25414. break;
  25415. case "cylinders":
  25416. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  25417. break;
  25418. case "toruses":
  25419. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  25420. break;
  25421. case "grounds":
  25422. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  25423. break;
  25424. case "planes":
  25425. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  25426. break;
  25427. case "torusKnots":
  25428. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  25429. break;
  25430. case "vertexData":
  25431. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  25432. break;
  25433. }
  25434. found = true;
  25435. }
  25436. });
  25437. }
  25438. });
  25439. if (!found) {
  25440. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  25441. }
  25442. }
  25443. }
  25444. // Material ?
  25445. if (parsedMesh.materialId) {
  25446. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  25447. if (!materialFound && parsedData.multiMaterials) {
  25448. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  25449. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  25450. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  25451. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  25452. var subMatId = parsedMultiMaterial.materials[matIndex];
  25453. loadedMaterialsIds.push(subMatId);
  25454. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  25455. log += "\n\tMaterial " + mat.toString(fullDetails);
  25456. }
  25457. loadedMaterialsIds.push(parsedMultiMaterial.id);
  25458. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  25459. materialFound = true;
  25460. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  25461. break;
  25462. }
  25463. }
  25464. }
  25465. if (!materialFound) {
  25466. loadedMaterialsIds.push(parsedMesh.materialId);
  25467. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  25468. if (!mat) {
  25469. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  25470. }
  25471. else {
  25472. log += "\n\tMaterial " + mat.toString(fullDetails);
  25473. }
  25474. }
  25475. }
  25476. // Skeleton ?
  25477. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  25478. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  25479. if (!skeletonAlreadyLoaded) {
  25480. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  25481. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  25482. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  25483. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  25484. skeletons.push(skeleton);
  25485. loadedSkeletonsIds.push(parsedSkeleton.id);
  25486. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  25487. }
  25488. }
  25489. }
  25490. }
  25491. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  25492. meshes.push(mesh);
  25493. log += "\n\tMesh " + mesh.toString(fullDetails);
  25494. }
  25495. }
  25496. // Connecting parents
  25497. var currentMesh;
  25498. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  25499. currentMesh = scene.meshes[index];
  25500. if (currentMesh._waitingParentId) {
  25501. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  25502. currentMesh._waitingParentId = undefined;
  25503. }
  25504. }
  25505. // freeze and compute world matrix application
  25506. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  25507. currentMesh = scene.meshes[index];
  25508. if (currentMesh._waitingFreezeWorldMatrix) {
  25509. currentMesh.freezeWorldMatrix();
  25510. currentMesh._waitingFreezeWorldMatrix = undefined;
  25511. }
  25512. else {
  25513. currentMesh.computeWorldMatrix(true);
  25514. }
  25515. }
  25516. // Particles
  25517. if (parsedData.particleSystems) {
  25518. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  25519. var parsedParticleSystem = parsedData.particleSystems[index];
  25520. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  25521. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  25522. }
  25523. }
  25524. }
  25525. return true;
  25526. }
  25527. catch (err) {
  25528. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
  25529. log = null;
  25530. throw err;
  25531. }
  25532. finally {
  25533. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  25534. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  25535. }
  25536. }
  25537. },
  25538. load: function (scene, data, rootUrl) {
  25539. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  25540. // when SceneLoader.debugLogging = true (default), or exception encountered.
  25541. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  25542. // and avoid problems with multiple concurrent .babylon loads.
  25543. var log = "importScene has failed JSON parse";
  25544. try {
  25545. var parsedData = JSON.parse(data);
  25546. log = "";
  25547. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  25548. // Scene
  25549. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  25550. scene.autoClear = parsedData.autoClear;
  25551. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  25552. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  25553. if (parsedData.gravity) {
  25554. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  25555. }
  25556. // Fog
  25557. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  25558. scene.fogMode = parsedData.fogMode;
  25559. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  25560. scene.fogStart = parsedData.fogStart;
  25561. scene.fogEnd = parsedData.fogEnd;
  25562. scene.fogDensity = parsedData.fogDensity;
  25563. log += "\tFog mode for scene: ";
  25564. switch (scene.fogMode) {
  25565. // getters not compiling, so using hardcoded
  25566. case 1:
  25567. log += "exp\n";
  25568. break;
  25569. case 2:
  25570. log += "exp2\n";
  25571. break;
  25572. case 3:
  25573. log += "linear\n";
  25574. break;
  25575. }
  25576. }
  25577. //Physics
  25578. if (parsedData.physicsEnabled) {
  25579. var physicsPlugin;
  25580. if (parsedData.physicsEngine === "cannon") {
  25581. physicsPlugin = new BABYLON.CannonJSPlugin();
  25582. }
  25583. else if (parsedData.physicsEngine === "oimo") {
  25584. physicsPlugin = new BABYLON.OimoJSPlugin();
  25585. }
  25586. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  25587. //else - default engine, which is currently oimo
  25588. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  25589. scene.enablePhysics(physicsGravity, physicsPlugin);
  25590. }
  25591. //collisions, if defined. otherwise, default is true
  25592. if (parsedData.collisionsEnabled != undefined) {
  25593. scene.collisionsEnabled = parsedData.collisionsEnabled;
  25594. }
  25595. scene.workerCollisions = !!parsedData.workerCollisions;
  25596. var index;
  25597. var cache;
  25598. // Lights
  25599. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  25600. var parsedLight = parsedData.lights[index];
  25601. var light = BABYLON.Light.Parse(parsedLight, scene);
  25602. log += (index === 0 ? "\n\tLights:" : "");
  25603. log += "\n\t\t" + light.toString(fullDetails);
  25604. }
  25605. // Animations
  25606. if (parsedData.animations) {
  25607. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  25608. var parsedAnimation = parsedData.animations[index];
  25609. var animation = BABYLON.Animation.Parse(parsedAnimation);
  25610. scene.animations.push(animation);
  25611. log += (index === 0 ? "\n\tAnimations:" : "");
  25612. log += "\n\t\t" + animation.toString(fullDetails);
  25613. }
  25614. }
  25615. if (parsedData.autoAnimate) {
  25616. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  25617. }
  25618. // Materials
  25619. if (parsedData.materials) {
  25620. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  25621. var parsedMaterial = parsedData.materials[index];
  25622. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  25623. log += (index === 0 ? "\n\tMaterials:" : "");
  25624. log += "\n\t\t" + mat.toString(fullDetails);
  25625. }
  25626. }
  25627. if (parsedData.multiMaterials) {
  25628. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  25629. var parsedMultiMaterial = parsedData.multiMaterials[index];
  25630. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  25631. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  25632. log += "\n\t\t" + mmat.toString(fullDetails);
  25633. }
  25634. }
  25635. // Skeletons
  25636. if (parsedData.skeletons) {
  25637. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  25638. var parsedSkeleton = parsedData.skeletons[index];
  25639. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  25640. log += (index === 0 ? "\n\tSkeletons:" : "");
  25641. log += "\n\t\t" + skeleton.toString(fullDetails);
  25642. }
  25643. }
  25644. // Geometries
  25645. var geometries = parsedData.geometries;
  25646. if (geometries) {
  25647. // Boxes
  25648. var boxes = geometries.boxes;
  25649. if (boxes) {
  25650. for (index = 0, cache = boxes.length; index < cache; index++) {
  25651. var parsedBox = boxes[index];
  25652. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  25653. }
  25654. }
  25655. // Spheres
  25656. var spheres = geometries.spheres;
  25657. if (spheres) {
  25658. for (index = 0, cache = spheres.length; index < cache; index++) {
  25659. var parsedSphere = spheres[index];
  25660. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  25661. }
  25662. }
  25663. // Cylinders
  25664. var cylinders = geometries.cylinders;
  25665. if (cylinders) {
  25666. for (index = 0, cache = cylinders.length; index < cache; index++) {
  25667. var parsedCylinder = cylinders[index];
  25668. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  25669. }
  25670. }
  25671. // Toruses
  25672. var toruses = geometries.toruses;
  25673. if (toruses) {
  25674. for (index = 0, cache = toruses.length; index < cache; index++) {
  25675. var parsedTorus = toruses[index];
  25676. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  25677. }
  25678. }
  25679. // Grounds
  25680. var grounds = geometries.grounds;
  25681. if (grounds) {
  25682. for (index = 0, cache = grounds.length; index < cache; index++) {
  25683. var parsedGround = grounds[index];
  25684. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  25685. }
  25686. }
  25687. // Planes
  25688. var planes = geometries.planes;
  25689. if (planes) {
  25690. for (index = 0, cache = planes.length; index < cache; index++) {
  25691. var parsedPlane = planes[index];
  25692. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  25693. }
  25694. }
  25695. // TorusKnots
  25696. var torusKnots = geometries.torusKnots;
  25697. if (torusKnots) {
  25698. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  25699. var parsedTorusKnot = torusKnots[index];
  25700. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  25701. }
  25702. }
  25703. // VertexData
  25704. var vertexData = geometries.vertexData;
  25705. if (vertexData) {
  25706. for (index = 0, cache = vertexData.length; index < cache; index++) {
  25707. var parsedVertexData = vertexData[index];
  25708. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  25709. }
  25710. }
  25711. }
  25712. // Meshes
  25713. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  25714. var parsedMesh = parsedData.meshes[index];
  25715. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  25716. log += (index === 0 ? "\n\tMeshes:" : "");
  25717. log += "\n\t\t" + mesh.toString(fullDetails);
  25718. }
  25719. // Cameras
  25720. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  25721. var parsedCamera = parsedData.cameras[index];
  25722. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  25723. log += (index === 0 ? "\n\tCameras:" : "");
  25724. log += "\n\t\t" + camera.toString(fullDetails);
  25725. }
  25726. if (parsedData.activeCameraID) {
  25727. scene.setActiveCameraByID(parsedData.activeCameraID);
  25728. }
  25729. // Browsing all the graph to connect the dots
  25730. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  25731. var camera = scene.cameras[index];
  25732. if (camera._waitingParentId) {
  25733. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  25734. camera._waitingParentId = undefined;
  25735. }
  25736. }
  25737. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  25738. var light = scene.lights[index];
  25739. if (light._waitingParentId) {
  25740. light.parent = scene.getLastEntryByID(light._waitingParentId);
  25741. light._waitingParentId = undefined;
  25742. }
  25743. }
  25744. // Sounds
  25745. var loadedSounds = [];
  25746. var loadedSound;
  25747. if (BABYLON.AudioEngine && parsedData.sounds) {
  25748. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  25749. var parsedSound = parsedData.sounds[index];
  25750. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25751. if (!parsedSound.url)
  25752. parsedSound.url = parsedSound.name;
  25753. if (!loadedSounds[parsedSound.url]) {
  25754. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  25755. loadedSounds[parsedSound.url] = loadedSound;
  25756. }
  25757. else {
  25758. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  25759. }
  25760. }
  25761. else {
  25762. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  25763. }
  25764. }
  25765. }
  25766. loadedSounds = [];
  25767. // Connect parents & children and parse actions
  25768. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  25769. var mesh = scene.meshes[index];
  25770. if (mesh._waitingParentId) {
  25771. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  25772. mesh._waitingParentId = undefined;
  25773. }
  25774. if (mesh._waitingActions) {
  25775. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  25776. mesh._waitingActions = undefined;
  25777. }
  25778. }
  25779. // freeze world matrix application
  25780. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  25781. var currentMesh = scene.meshes[index];
  25782. if (currentMesh._waitingFreezeWorldMatrix) {
  25783. currentMesh.freezeWorldMatrix();
  25784. currentMesh._waitingFreezeWorldMatrix = undefined;
  25785. }
  25786. else {
  25787. currentMesh.computeWorldMatrix(true);
  25788. }
  25789. }
  25790. // Particles Systems
  25791. if (parsedData.particleSystems) {
  25792. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  25793. var parsedParticleSystem = parsedData.particleSystems[index];
  25794. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  25795. }
  25796. }
  25797. // Lens flares
  25798. if (parsedData.lensFlareSystems) {
  25799. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  25800. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  25801. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  25802. }
  25803. }
  25804. // Shadows
  25805. if (parsedData.shadowGenerators) {
  25806. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  25807. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  25808. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  25809. }
  25810. }
  25811. // Actions (scene)
  25812. if (parsedData.actions) {
  25813. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  25814. }
  25815. // Finish
  25816. return true;
  25817. }
  25818. catch (err) {
  25819. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
  25820. log = null;
  25821. throw err;
  25822. }
  25823. finally {
  25824. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  25825. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  25826. }
  25827. }
  25828. }
  25829. });
  25830. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25831. })(BABYLON || (BABYLON = {}));
  25832. var BABYLON;
  25833. (function (BABYLON) {
  25834. var SpriteManager = (function () {
  25835. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  25836. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25837. this.name = name;
  25838. this.cellSize = cellSize;
  25839. this.sprites = new Array();
  25840. this.renderingGroupId = 0;
  25841. this.layerMask = 0x0FFFFFFF;
  25842. this.fogEnabled = true;
  25843. this.isPickable = false;
  25844. /**
  25845. * An event triggered when the manager is disposed.
  25846. * @type {BABYLON.Observable}
  25847. */
  25848. this.onDisposeObservable = new BABYLON.Observable();
  25849. this._vertexBuffers = {};
  25850. this._capacity = capacity;
  25851. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  25852. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25853. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25854. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  25855. this._scene = scene;
  25856. this._scene.spriteManagers.push(this);
  25857. var indices = [];
  25858. var index = 0;
  25859. for (var count = 0; count < capacity; count++) {
  25860. indices.push(index);
  25861. indices.push(index + 1);
  25862. indices.push(index + 2);
  25863. indices.push(index);
  25864. indices.push(index + 2);
  25865. indices.push(index + 3);
  25866. index += 4;
  25867. }
  25868. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  25869. // VBO
  25870. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  25871. this._vertexData = new Float32Array(capacity * 16 * 4);
  25872. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  25873. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  25874. var options = this._buffer.createVertexBuffer("options", 4, 4);
  25875. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  25876. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  25877. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  25878. this._vertexBuffers["options"] = options;
  25879. this._vertexBuffers["cellInfo"] = cellInfo;
  25880. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  25881. // Effects
  25882. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  25883. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  25884. }
  25885. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  25886. set: function (callback) {
  25887. if (this._onDisposeObserver) {
  25888. this.onDisposeObservable.remove(this._onDisposeObserver);
  25889. }
  25890. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25891. },
  25892. enumerable: true,
  25893. configurable: true
  25894. });
  25895. Object.defineProperty(SpriteManager.prototype, "texture", {
  25896. get: function () {
  25897. return this._spriteTexture;
  25898. },
  25899. set: function (value) {
  25900. this._spriteTexture = value;
  25901. },
  25902. enumerable: true,
  25903. configurable: true
  25904. });
  25905. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  25906. var arrayOffset = index * 16;
  25907. if (offsetX === 0)
  25908. offsetX = this._epsilon;
  25909. else if (offsetX === 1)
  25910. offsetX = 1 - this._epsilon;
  25911. if (offsetY === 0)
  25912. offsetY = this._epsilon;
  25913. else if (offsetY === 1)
  25914. offsetY = 1 - this._epsilon;
  25915. this._vertexData[arrayOffset] = sprite.position.x;
  25916. this._vertexData[arrayOffset + 1] = sprite.position.y;
  25917. this._vertexData[arrayOffset + 2] = sprite.position.z;
  25918. this._vertexData[arrayOffset + 3] = sprite.angle;
  25919. this._vertexData[arrayOffset + 4] = sprite.width;
  25920. this._vertexData[arrayOffset + 5] = sprite.height;
  25921. this._vertexData[arrayOffset + 6] = offsetX;
  25922. this._vertexData[arrayOffset + 7] = offsetY;
  25923. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  25924. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  25925. var offset = (sprite.cellIndex / rowSize) >> 0;
  25926. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  25927. this._vertexData[arrayOffset + 11] = offset;
  25928. // Color
  25929. this._vertexData[arrayOffset + 12] = sprite.color.r;
  25930. this._vertexData[arrayOffset + 13] = sprite.color.g;
  25931. this._vertexData[arrayOffset + 14] = sprite.color.b;
  25932. this._vertexData[arrayOffset + 15] = sprite.color.a;
  25933. };
  25934. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  25935. var count = Math.min(this._capacity, this.sprites.length);
  25936. var min = BABYLON.Vector3.Zero();
  25937. var max = BABYLON.Vector3.Zero();
  25938. var distance = Number.MAX_VALUE;
  25939. var currentSprite;
  25940. var cameraSpacePosition = BABYLON.Vector3.Zero();
  25941. var cameraView = camera.getViewMatrix();
  25942. for (var index = 0; index < count; index++) {
  25943. var sprite = this.sprites[index];
  25944. if (!sprite) {
  25945. continue;
  25946. }
  25947. if (predicate) {
  25948. if (!predicate(sprite)) {
  25949. continue;
  25950. }
  25951. }
  25952. else if (!sprite.isPickable) {
  25953. continue;
  25954. }
  25955. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  25956. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  25957. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  25958. if (ray.intersectsBoxMinMax(min, max)) {
  25959. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  25960. if (distance > currentDistance) {
  25961. distance = currentDistance;
  25962. currentSprite = sprite;
  25963. if (fastCheck) {
  25964. break;
  25965. }
  25966. }
  25967. }
  25968. }
  25969. if (currentSprite) {
  25970. var result = new BABYLON.PickingInfo();
  25971. result.hit = true;
  25972. result.pickedSprite = currentSprite;
  25973. result.distance = distance;
  25974. return result;
  25975. }
  25976. return null;
  25977. };
  25978. SpriteManager.prototype.render = function () {
  25979. // Check
  25980. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  25981. return;
  25982. var engine = this._scene.getEngine();
  25983. var baseSize = this._spriteTexture.getBaseSize();
  25984. // Sprites
  25985. var deltaTime = engine.getDeltaTime();
  25986. var max = Math.min(this._capacity, this.sprites.length);
  25987. var rowSize = baseSize.width / this.cellSize;
  25988. var offset = 0;
  25989. for (var index = 0; index < max; index++) {
  25990. var sprite = this.sprites[index];
  25991. if (!sprite) {
  25992. continue;
  25993. }
  25994. sprite._animate(deltaTime);
  25995. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  25996. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  25997. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  25998. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  25999. }
  26000. this._buffer.update(this._vertexData);
  26001. // Render
  26002. var effect = this._effectBase;
  26003. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  26004. effect = this._effectFog;
  26005. }
  26006. engine.enableEffect(effect);
  26007. var viewMatrix = this._scene.getViewMatrix();
  26008. effect.setTexture("diffuseSampler", this._spriteTexture);
  26009. effect.setMatrix("view", viewMatrix);
  26010. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  26011. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  26012. // Fog
  26013. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  26014. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  26015. effect.setColor3("vFogColor", this._scene.fogColor);
  26016. }
  26017. // VBOs
  26018. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  26019. // Draw order
  26020. engine.setDepthFunctionToLessOrEqual();
  26021. effect.setBool("alphaTest", true);
  26022. engine.setColorWrite(false);
  26023. engine.draw(true, 0, max * 6);
  26024. engine.setColorWrite(true);
  26025. effect.setBool("alphaTest", false);
  26026. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  26027. engine.draw(true, 0, max * 6);
  26028. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26029. };
  26030. SpriteManager.prototype.dispose = function () {
  26031. if (this._buffer) {
  26032. this._buffer.dispose();
  26033. this._buffer = null;
  26034. }
  26035. if (this._indexBuffer) {
  26036. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26037. this._indexBuffer = null;
  26038. }
  26039. if (this._spriteTexture) {
  26040. this._spriteTexture.dispose();
  26041. this._spriteTexture = null;
  26042. }
  26043. // Remove from scene
  26044. var index = this._scene.spriteManagers.indexOf(this);
  26045. this._scene.spriteManagers.splice(index, 1);
  26046. // Callback
  26047. this.onDisposeObservable.notifyObservers(this);
  26048. this.onDisposeObservable.clear();
  26049. };
  26050. return SpriteManager;
  26051. }());
  26052. BABYLON.SpriteManager = SpriteManager;
  26053. })(BABYLON || (BABYLON = {}));
  26054. var BABYLON;
  26055. (function (BABYLON) {
  26056. var Sprite = (function () {
  26057. function Sprite(name, manager) {
  26058. this.name = name;
  26059. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26060. this.width = 1.0;
  26061. this.height = 1.0;
  26062. this.angle = 0;
  26063. this.cellIndex = 0;
  26064. this.invertU = 0;
  26065. this.invertV = 0;
  26066. this.animations = new Array();
  26067. this.isPickable = false;
  26068. this._animationStarted = false;
  26069. this._loopAnimation = false;
  26070. this._fromIndex = 0;
  26071. this._toIndex = 0;
  26072. this._delay = 0;
  26073. this._direction = 1;
  26074. this._frameCount = 0;
  26075. this._time = 0;
  26076. this._manager = manager;
  26077. this._manager.sprites.push(this);
  26078. this.position = BABYLON.Vector3.Zero();
  26079. }
  26080. Object.defineProperty(Sprite.prototype, "size", {
  26081. get: function () {
  26082. return this.width;
  26083. },
  26084. set: function (value) {
  26085. this.width = value;
  26086. this.height = value;
  26087. },
  26088. enumerable: true,
  26089. configurable: true
  26090. });
  26091. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  26092. this._fromIndex = from;
  26093. this._toIndex = to;
  26094. this._loopAnimation = loop;
  26095. this._delay = delay;
  26096. this._animationStarted = true;
  26097. this._direction = from < to ? 1 : -1;
  26098. this.cellIndex = from;
  26099. this._time = 0;
  26100. };
  26101. Sprite.prototype.stopAnimation = function () {
  26102. this._animationStarted = false;
  26103. };
  26104. Sprite.prototype._animate = function (deltaTime) {
  26105. if (!this._animationStarted)
  26106. return;
  26107. this._time += deltaTime;
  26108. if (this._time > this._delay) {
  26109. this._time = this._time % this._delay;
  26110. this.cellIndex += this._direction;
  26111. if (this.cellIndex == this._toIndex) {
  26112. if (this._loopAnimation) {
  26113. this.cellIndex = this._fromIndex;
  26114. }
  26115. else {
  26116. this._animationStarted = false;
  26117. if (this.disposeWhenFinishedAnimating) {
  26118. this.dispose();
  26119. }
  26120. }
  26121. }
  26122. }
  26123. };
  26124. Sprite.prototype.dispose = function () {
  26125. for (var i = 0; i < this._manager.sprites.length; i++) {
  26126. if (this._manager.sprites[i] == this) {
  26127. this._manager.sprites.splice(i, 1);
  26128. }
  26129. }
  26130. };
  26131. return Sprite;
  26132. }());
  26133. BABYLON.Sprite = Sprite;
  26134. })(BABYLON || (BABYLON = {}));
  26135. var BABYLON;
  26136. (function (BABYLON) {
  26137. var Layer = (function () {
  26138. function Layer(name, imgUrl, scene, isBackground, color) {
  26139. this.name = name;
  26140. this.scale = new BABYLON.Vector2(1, 1);
  26141. this.offset = new BABYLON.Vector2(0, 0);
  26142. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  26143. this._vertexBuffers = {};
  26144. // Events
  26145. /**
  26146. * An event triggered when the layer is disposed.
  26147. * @type {BABYLON.Observable}
  26148. */
  26149. this.onDisposeObservable = new BABYLON.Observable();
  26150. /**
  26151. * An event triggered before rendering the scene
  26152. * @type {BABYLON.Observable}
  26153. */
  26154. this.onBeforeRenderObservable = new BABYLON.Observable();
  26155. /**
  26156. * An event triggered after rendering the scene
  26157. * @type {BABYLON.Observable}
  26158. */
  26159. this.onAfterRenderObservable = new BABYLON.Observable();
  26160. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  26161. this.isBackground = isBackground === undefined ? true : isBackground;
  26162. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  26163. this._scene = scene;
  26164. this._scene.layers.push(this);
  26165. var engine = scene.getEngine();
  26166. // VBO
  26167. var vertices = [];
  26168. vertices.push(1, 1);
  26169. vertices.push(-1, 1);
  26170. vertices.push(-1, -1);
  26171. vertices.push(1, -1);
  26172. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  26173. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  26174. // Indices
  26175. var indices = [];
  26176. indices.push(0);
  26177. indices.push(1);
  26178. indices.push(2);
  26179. indices.push(0);
  26180. indices.push(2);
  26181. indices.push(3);
  26182. this._indexBuffer = engine.createIndexBuffer(indices);
  26183. // Effects
  26184. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  26185. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  26186. }
  26187. Object.defineProperty(Layer.prototype, "onDispose", {
  26188. set: function (callback) {
  26189. if (this._onDisposeObserver) {
  26190. this.onDisposeObservable.remove(this._onDisposeObserver);
  26191. }
  26192. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26193. },
  26194. enumerable: true,
  26195. configurable: true
  26196. });
  26197. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  26198. set: function (callback) {
  26199. if (this._onBeforeRenderObserver) {
  26200. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  26201. }
  26202. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  26203. },
  26204. enumerable: true,
  26205. configurable: true
  26206. });
  26207. Object.defineProperty(Layer.prototype, "onAfterRender", {
  26208. set: function (callback) {
  26209. if (this._onAfterRenderObserver) {
  26210. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  26211. }
  26212. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  26213. },
  26214. enumerable: true,
  26215. configurable: true
  26216. });
  26217. Layer.prototype.render = function () {
  26218. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  26219. // Check
  26220. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  26221. return;
  26222. var engine = this._scene.getEngine();
  26223. this.onBeforeRenderObservable.notifyObservers(this);
  26224. // Render
  26225. engine.enableEffect(currentEffect);
  26226. engine.setState(false);
  26227. // Texture
  26228. currentEffect.setTexture("textureSampler", this.texture);
  26229. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  26230. // Color
  26231. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  26232. // Scale / offset
  26233. currentEffect.setVector2("offset", this.offset);
  26234. currentEffect.setVector2("scale", this.scale);
  26235. // VBOs
  26236. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  26237. // Draw order
  26238. if (!this._alphaTestEffect) {
  26239. engine.setAlphaMode(this.alphaBlendingMode);
  26240. engine.draw(true, 0, 6);
  26241. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26242. }
  26243. else {
  26244. engine.draw(true, 0, 6);
  26245. }
  26246. this.onAfterRenderObservable.notifyObservers(this);
  26247. };
  26248. Layer.prototype.dispose = function () {
  26249. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  26250. if (vertexBuffer) {
  26251. vertexBuffer.dispose();
  26252. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  26253. }
  26254. if (this._indexBuffer) {
  26255. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26256. this._indexBuffer = null;
  26257. }
  26258. if (this.texture) {
  26259. this.texture.dispose();
  26260. this.texture = null;
  26261. }
  26262. // Remove from scene
  26263. var index = this._scene.layers.indexOf(this);
  26264. this._scene.layers.splice(index, 1);
  26265. // Callback
  26266. this.onDisposeObservable.notifyObservers(this);
  26267. this.onDisposeObservable.clear();
  26268. this.onAfterRenderObservable.clear();
  26269. this.onBeforeRenderObservable.clear();
  26270. };
  26271. return Layer;
  26272. }());
  26273. BABYLON.Layer = Layer;
  26274. })(BABYLON || (BABYLON = {}));
  26275. var BABYLON;
  26276. (function (BABYLON) {
  26277. var Particle = (function () {
  26278. function Particle() {
  26279. this.position = BABYLON.Vector3.Zero();
  26280. this.direction = BABYLON.Vector3.Zero();
  26281. this.color = new BABYLON.Color4(0, 0, 0, 0);
  26282. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  26283. this.lifeTime = 1.0;
  26284. this.age = 0;
  26285. this.size = 0;
  26286. this.angle = 0;
  26287. this.angularSpeed = 0;
  26288. }
  26289. Particle.prototype.copyTo = function (other) {
  26290. other.position.copyFrom(this.position);
  26291. other.direction.copyFrom(this.direction);
  26292. other.color.copyFrom(this.color);
  26293. other.colorStep.copyFrom(this.colorStep);
  26294. other.lifeTime = this.lifeTime;
  26295. other.age = this.age;
  26296. other.size = this.size;
  26297. other.angle = this.angle;
  26298. other.angularSpeed = this.angularSpeed;
  26299. };
  26300. return Particle;
  26301. }());
  26302. BABYLON.Particle = Particle;
  26303. })(BABYLON || (BABYLON = {}));
  26304. var BABYLON;
  26305. (function (BABYLON) {
  26306. var randomNumber = function (min, max) {
  26307. if (min === max) {
  26308. return (min);
  26309. }
  26310. var random = Math.random();
  26311. return ((random * (max - min)) + min);
  26312. };
  26313. var ParticleSystem = (function () {
  26314. function ParticleSystem(name, capacity, scene, customEffect) {
  26315. var _this = this;
  26316. this.name = name;
  26317. // Members
  26318. this.animations = [];
  26319. this.renderingGroupId = 0;
  26320. this.emitter = null;
  26321. this.emitRate = 10;
  26322. this.manualEmitCount = -1;
  26323. this.updateSpeed = 0.01;
  26324. this.targetStopDuration = 0;
  26325. this.disposeOnStop = false;
  26326. this.minEmitPower = 1;
  26327. this.maxEmitPower = 1;
  26328. this.minLifeTime = 1;
  26329. this.maxLifeTime = 1;
  26330. this.minSize = 1;
  26331. this.maxSize = 1;
  26332. this.minAngularSpeed = 0;
  26333. this.maxAngularSpeed = 0;
  26334. this.layerMask = 0x0FFFFFFF;
  26335. /**
  26336. * An event triggered when the system is disposed.
  26337. * @type {BABYLON.Observable}
  26338. */
  26339. this.onDisposeObservable = new BABYLON.Observable();
  26340. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  26341. this.forceDepthWrite = false;
  26342. this.gravity = BABYLON.Vector3.Zero();
  26343. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  26344. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  26345. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  26346. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  26347. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26348. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26349. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  26350. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26351. this.particles = new Array();
  26352. this._stockParticles = new Array();
  26353. this._newPartsExcess = 0;
  26354. this._vertexBuffers = {};
  26355. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  26356. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  26357. this._scaledDirection = BABYLON.Vector3.Zero();
  26358. this._scaledGravity = BABYLON.Vector3.Zero();
  26359. this._currentRenderId = -1;
  26360. this._started = false;
  26361. this._stopped = false;
  26362. this._actualFrame = 0;
  26363. this.id = name;
  26364. this._capacity = capacity;
  26365. this._scene = scene;
  26366. this._customEffect = customEffect;
  26367. scene.particleSystems.push(this);
  26368. var indices = [];
  26369. var index = 0;
  26370. for (var count = 0; count < capacity; count++) {
  26371. indices.push(index);
  26372. indices.push(index + 1);
  26373. indices.push(index + 2);
  26374. indices.push(index);
  26375. indices.push(index + 2);
  26376. indices.push(index + 3);
  26377. index += 4;
  26378. }
  26379. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  26380. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  26381. this._vertexData = new Float32Array(capacity * 11 * 4);
  26382. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  26383. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  26384. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  26385. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  26386. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  26387. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  26388. this._vertexBuffers["options"] = options;
  26389. // Default behaviors
  26390. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  26391. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  26392. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  26393. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  26394. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  26395. };
  26396. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  26397. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  26398. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  26399. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  26400. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  26401. };
  26402. this.updateFunction = function (particles) {
  26403. for (var index = 0; index < particles.length; index++) {
  26404. var particle = particles[index];
  26405. particle.age += _this._scaledUpdateSpeed;
  26406. if (particle.age >= particle.lifeTime) {
  26407. _this.recycleParticle(particle);
  26408. index--;
  26409. continue;
  26410. }
  26411. else {
  26412. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  26413. particle.color.addInPlace(_this._scaledColorStep);
  26414. if (particle.color.a < 0)
  26415. particle.color.a = 0;
  26416. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  26417. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  26418. particle.position.addInPlace(_this._scaledDirection);
  26419. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  26420. particle.direction.addInPlace(_this._scaledGravity);
  26421. }
  26422. }
  26423. };
  26424. }
  26425. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  26426. set: function (callback) {
  26427. if (this._onDisposeObserver) {
  26428. this.onDisposeObservable.remove(this._onDisposeObserver);
  26429. }
  26430. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26431. },
  26432. enumerable: true,
  26433. configurable: true
  26434. });
  26435. ParticleSystem.prototype.recycleParticle = function (particle) {
  26436. var lastParticle = this.particles.pop();
  26437. if (lastParticle !== particle) {
  26438. lastParticle.copyTo(particle);
  26439. this._stockParticles.push(lastParticle);
  26440. }
  26441. };
  26442. ParticleSystem.prototype.getCapacity = function () {
  26443. return this._capacity;
  26444. };
  26445. ParticleSystem.prototype.isAlive = function () {
  26446. return this._alive;
  26447. };
  26448. ParticleSystem.prototype.isStarted = function () {
  26449. return this._started;
  26450. };
  26451. ParticleSystem.prototype.start = function () {
  26452. this._started = true;
  26453. this._stopped = false;
  26454. this._actualFrame = 0;
  26455. };
  26456. ParticleSystem.prototype.stop = function () {
  26457. this._stopped = true;
  26458. };
  26459. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  26460. var offset = index * 11;
  26461. this._vertexData[offset] = particle.position.x;
  26462. this._vertexData[offset + 1] = particle.position.y;
  26463. this._vertexData[offset + 2] = particle.position.z;
  26464. this._vertexData[offset + 3] = particle.color.r;
  26465. this._vertexData[offset + 4] = particle.color.g;
  26466. this._vertexData[offset + 5] = particle.color.b;
  26467. this._vertexData[offset + 6] = particle.color.a;
  26468. this._vertexData[offset + 7] = particle.angle;
  26469. this._vertexData[offset + 8] = particle.size;
  26470. this._vertexData[offset + 9] = offsetX;
  26471. this._vertexData[offset + 10] = offsetY;
  26472. };
  26473. ParticleSystem.prototype._update = function (newParticles) {
  26474. // Update current
  26475. this._alive = this.particles.length > 0;
  26476. this.updateFunction(this.particles);
  26477. // Add new ones
  26478. var worldMatrix;
  26479. if (this.emitter.position) {
  26480. worldMatrix = this.emitter.getWorldMatrix();
  26481. }
  26482. else {
  26483. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  26484. }
  26485. var particle;
  26486. for (var index = 0; index < newParticles; index++) {
  26487. if (this.particles.length === this._capacity) {
  26488. break;
  26489. }
  26490. if (this._stockParticles.length !== 0) {
  26491. particle = this._stockParticles.pop();
  26492. particle.age = 0;
  26493. }
  26494. else {
  26495. particle = new BABYLON.Particle();
  26496. }
  26497. this.particles.push(particle);
  26498. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  26499. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  26500. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  26501. particle.size = randomNumber(this.minSize, this.maxSize);
  26502. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  26503. this.startPositionFunction(worldMatrix, particle.position, particle);
  26504. var step = randomNumber(0, 1.0);
  26505. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  26506. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  26507. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  26508. }
  26509. };
  26510. ParticleSystem.prototype._getEffect = function () {
  26511. if (this._customEffect) {
  26512. return this._customEffect;
  26513. }
  26514. ;
  26515. var defines = [];
  26516. if (this._scene.clipPlane) {
  26517. defines.push("#define CLIPPLANE");
  26518. }
  26519. // Effect
  26520. var join = defines.join("\n");
  26521. if (this._cachedDefines !== join) {
  26522. this._cachedDefines = join;
  26523. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  26524. }
  26525. return this._effect;
  26526. };
  26527. ParticleSystem.prototype.animate = function () {
  26528. if (!this._started)
  26529. return;
  26530. var effect = this._getEffect();
  26531. // Check
  26532. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  26533. return;
  26534. if (this._currentRenderId === this._scene.getRenderId()) {
  26535. return;
  26536. }
  26537. this._currentRenderId = this._scene.getRenderId();
  26538. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  26539. // determine the number of particles we need to create
  26540. var newParticles;
  26541. if (this.manualEmitCount > -1) {
  26542. newParticles = this.manualEmitCount;
  26543. this._newPartsExcess = 0;
  26544. this.manualEmitCount = 0;
  26545. }
  26546. else {
  26547. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  26548. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  26549. }
  26550. if (this._newPartsExcess > 1.0) {
  26551. newParticles += this._newPartsExcess >> 0;
  26552. this._newPartsExcess -= this._newPartsExcess >> 0;
  26553. }
  26554. this._alive = false;
  26555. if (!this._stopped) {
  26556. this._actualFrame += this._scaledUpdateSpeed;
  26557. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  26558. this.stop();
  26559. }
  26560. else {
  26561. newParticles = 0;
  26562. }
  26563. this._update(newParticles);
  26564. // Stopped?
  26565. if (this._stopped) {
  26566. if (!this._alive) {
  26567. this._started = false;
  26568. if (this.disposeOnStop) {
  26569. this._scene._toBeDisposed.push(this);
  26570. }
  26571. }
  26572. }
  26573. // Update VBO
  26574. var offset = 0;
  26575. for (var index = 0; index < this.particles.length; index++) {
  26576. var particle = this.particles[index];
  26577. this._appendParticleVertex(offset++, particle, 0, 0);
  26578. this._appendParticleVertex(offset++, particle, 1, 0);
  26579. this._appendParticleVertex(offset++, particle, 1, 1);
  26580. this._appendParticleVertex(offset++, particle, 0, 1);
  26581. }
  26582. this._vertexBuffer.update(this._vertexData);
  26583. };
  26584. ParticleSystem.prototype.render = function () {
  26585. var effect = this._getEffect();
  26586. // Check
  26587. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  26588. return 0;
  26589. var engine = this._scene.getEngine();
  26590. // Render
  26591. engine.enableEffect(effect);
  26592. engine.setState(false);
  26593. var viewMatrix = this._scene.getViewMatrix();
  26594. effect.setTexture("diffuseSampler", this.particleTexture);
  26595. effect.setMatrix("view", viewMatrix);
  26596. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  26597. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  26598. if (this._scene.clipPlane) {
  26599. var clipPlane = this._scene.clipPlane;
  26600. var invView = viewMatrix.clone();
  26601. invView.invert();
  26602. effect.setMatrix("invView", invView);
  26603. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  26604. }
  26605. // VBOs
  26606. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  26607. // Draw order
  26608. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  26609. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  26610. }
  26611. else {
  26612. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  26613. }
  26614. if (this.forceDepthWrite) {
  26615. engine.setDepthWrite(true);
  26616. }
  26617. engine.draw(true, 0, this.particles.length * 6);
  26618. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26619. return this.particles.length;
  26620. };
  26621. ParticleSystem.prototype.dispose = function () {
  26622. if (this._vertexBuffer) {
  26623. this._vertexBuffer.dispose();
  26624. this._vertexBuffer = null;
  26625. }
  26626. if (this._indexBuffer) {
  26627. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26628. this._indexBuffer = null;
  26629. }
  26630. if (this.particleTexture) {
  26631. this.particleTexture.dispose();
  26632. this.particleTexture = null;
  26633. }
  26634. // Remove from scene
  26635. var index = this._scene.particleSystems.indexOf(this);
  26636. this._scene.particleSystems.splice(index, 1);
  26637. // Callback
  26638. this.onDisposeObservable.notifyObservers(this);
  26639. this.onDisposeObservable.clear();
  26640. };
  26641. // Clone
  26642. ParticleSystem.prototype.clone = function (name, newEmitter) {
  26643. var result = new ParticleSystem(name, this._capacity, this._scene);
  26644. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  26645. if (newEmitter === undefined) {
  26646. newEmitter = this.emitter;
  26647. }
  26648. result.emitter = newEmitter;
  26649. if (this.particleTexture) {
  26650. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  26651. }
  26652. result.start();
  26653. return result;
  26654. };
  26655. ParticleSystem.prototype.serialize = function () {
  26656. var serializationObject = {};
  26657. serializationObject.name = this.name;
  26658. serializationObject.id = this.id;
  26659. // Emitter
  26660. if (this.emitter.position) {
  26661. serializationObject.emitterId = this.emitter.id;
  26662. }
  26663. else {
  26664. serializationObject.emitter = this.emitter.asArray();
  26665. }
  26666. serializationObject.capacity = this.getCapacity();
  26667. if (this.particleTexture) {
  26668. serializationObject.textureName = this.particleTexture.name;
  26669. }
  26670. // Animations
  26671. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26672. // Particle system
  26673. serializationObject.minAngularSpeed = this.minAngularSpeed;
  26674. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  26675. serializationObject.minSize = this.minSize;
  26676. serializationObject.maxSize = this.maxSize;
  26677. serializationObject.minEmitPower = this.minEmitPower;
  26678. serializationObject.maxEmitPower = this.maxEmitPower;
  26679. serializationObject.minLifeTime = this.minLifeTime;
  26680. serializationObject.maxLifeTime = this.maxLifeTime;
  26681. serializationObject.emitRate = this.emitRate;
  26682. serializationObject.minEmitBox = this.minEmitBox.asArray();
  26683. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  26684. serializationObject.gravity = this.gravity.asArray();
  26685. serializationObject.direction1 = this.direction1.asArray();
  26686. serializationObject.direction2 = this.direction2.asArray();
  26687. serializationObject.color1 = this.color1.asArray();
  26688. serializationObject.color2 = this.color2.asArray();
  26689. serializationObject.colorDead = this.colorDead.asArray();
  26690. serializationObject.updateSpeed = this.updateSpeed;
  26691. serializationObject.targetStopDuration = this.targetStopDuration;
  26692. serializationObject.textureMask = this.textureMask.asArray();
  26693. serializationObject.blendMode = this.blendMode;
  26694. return serializationObject;
  26695. };
  26696. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  26697. var name = parsedParticleSystem.name;
  26698. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  26699. if (parsedParticleSystem.id) {
  26700. particleSystem.id = parsedParticleSystem.id;
  26701. }
  26702. // Texture
  26703. if (parsedParticleSystem.textureName) {
  26704. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  26705. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  26706. }
  26707. // Emitter
  26708. if (parsedParticleSystem.emitterId) {
  26709. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  26710. }
  26711. else {
  26712. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  26713. }
  26714. // Animations
  26715. if (parsedParticleSystem.animations) {
  26716. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  26717. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  26718. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26719. }
  26720. }
  26721. if (parsedParticleSystem.autoAnimate) {
  26722. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  26723. }
  26724. // Particle system
  26725. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  26726. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  26727. particleSystem.minSize = parsedParticleSystem.minSize;
  26728. particleSystem.maxSize = parsedParticleSystem.maxSize;
  26729. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  26730. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  26731. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  26732. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  26733. particleSystem.emitRate = parsedParticleSystem.emitRate;
  26734. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  26735. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  26736. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  26737. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  26738. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  26739. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  26740. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  26741. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  26742. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  26743. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  26744. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  26745. particleSystem.blendMode = parsedParticleSystem.blendMode;
  26746. if (!parsedParticleSystem.preventAutoStart) {
  26747. particleSystem.start();
  26748. }
  26749. return particleSystem;
  26750. };
  26751. // Statics
  26752. ParticleSystem.BLENDMODE_ONEONE = 0;
  26753. ParticleSystem.BLENDMODE_STANDARD = 1;
  26754. return ParticleSystem;
  26755. }());
  26756. BABYLON.ParticleSystem = ParticleSystem;
  26757. })(BABYLON || (BABYLON = {}));
  26758. var BABYLON;
  26759. (function (BABYLON) {
  26760. var AnimationRange = (function () {
  26761. function AnimationRange(name, from, to) {
  26762. this.name = name;
  26763. this.from = from;
  26764. this.to = to;
  26765. }
  26766. AnimationRange.prototype.clone = function () {
  26767. return new AnimationRange(this.name, this.from, this.to);
  26768. };
  26769. return AnimationRange;
  26770. }());
  26771. BABYLON.AnimationRange = AnimationRange;
  26772. /**
  26773. * Composed of a frame, and an action function
  26774. */
  26775. var AnimationEvent = (function () {
  26776. function AnimationEvent(frame, action, onlyOnce) {
  26777. this.frame = frame;
  26778. this.action = action;
  26779. this.onlyOnce = onlyOnce;
  26780. this.isDone = false;
  26781. }
  26782. return AnimationEvent;
  26783. }());
  26784. BABYLON.AnimationEvent = AnimationEvent;
  26785. var PathCursor = (function () {
  26786. function PathCursor(path) {
  26787. this.path = path;
  26788. this._onchange = new Array();
  26789. this.value = 0;
  26790. this.animations = new Array();
  26791. }
  26792. PathCursor.prototype.getPoint = function () {
  26793. var point = this.path.getPointAtLengthPosition(this.value);
  26794. return new BABYLON.Vector3(point.x, 0, point.y);
  26795. };
  26796. PathCursor.prototype.moveAhead = function (step) {
  26797. if (step === void 0) { step = 0.002; }
  26798. this.move(step);
  26799. return this;
  26800. };
  26801. PathCursor.prototype.moveBack = function (step) {
  26802. if (step === void 0) { step = 0.002; }
  26803. this.move(-step);
  26804. return this;
  26805. };
  26806. PathCursor.prototype.move = function (step) {
  26807. if (Math.abs(step) > 1) {
  26808. throw "step size should be less than 1.";
  26809. }
  26810. this.value += step;
  26811. this.ensureLimits();
  26812. this.raiseOnChange();
  26813. return this;
  26814. };
  26815. PathCursor.prototype.ensureLimits = function () {
  26816. while (this.value > 1) {
  26817. this.value -= 1;
  26818. }
  26819. while (this.value < 0) {
  26820. this.value += 1;
  26821. }
  26822. return this;
  26823. };
  26824. // used by animation engine
  26825. PathCursor.prototype.markAsDirty = function (propertyName) {
  26826. this.ensureLimits();
  26827. this.raiseOnChange();
  26828. return this;
  26829. };
  26830. PathCursor.prototype.raiseOnChange = function () {
  26831. var _this = this;
  26832. this._onchange.forEach(function (f) { return f(_this); });
  26833. return this;
  26834. };
  26835. PathCursor.prototype.onchange = function (f) {
  26836. this._onchange.push(f);
  26837. return this;
  26838. };
  26839. return PathCursor;
  26840. }());
  26841. BABYLON.PathCursor = PathCursor;
  26842. var Animation = (function () {
  26843. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  26844. this.name = name;
  26845. this.targetProperty = targetProperty;
  26846. this.framePerSecond = framePerSecond;
  26847. this.dataType = dataType;
  26848. this.loopMode = loopMode;
  26849. this.enableBlending = enableBlending;
  26850. this._offsetsCache = {};
  26851. this._highLimitsCache = {};
  26852. this._stopped = false;
  26853. this._blendingFactor = 0;
  26854. // The set of event that will be linked to this animation
  26855. this._events = new Array();
  26856. this.allowMatricesInterpolation = false;
  26857. this.blendingSpeed = 0.01;
  26858. this._ranges = {};
  26859. this.targetPropertyPath = targetProperty.split(".");
  26860. this.dataType = dataType;
  26861. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  26862. }
  26863. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  26864. var dataType = undefined;
  26865. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  26866. dataType = Animation.ANIMATIONTYPE_FLOAT;
  26867. }
  26868. else if (from instanceof BABYLON.Quaternion) {
  26869. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  26870. }
  26871. else if (from instanceof BABYLON.Vector3) {
  26872. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  26873. }
  26874. else if (from instanceof BABYLON.Vector2) {
  26875. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  26876. }
  26877. else if (from instanceof BABYLON.Color3) {
  26878. dataType = Animation.ANIMATIONTYPE_COLOR3;
  26879. }
  26880. else if (from instanceof BABYLON.Size) {
  26881. dataType = Animation.ANIMATIONTYPE_SIZE;
  26882. }
  26883. if (dataType == undefined) {
  26884. return null;
  26885. }
  26886. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  26887. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  26888. animation.setKeys(keys);
  26889. if (easingFunction !== undefined) {
  26890. animation.setEasingFunction(easingFunction);
  26891. }
  26892. return animation;
  26893. };
  26894. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  26895. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  26896. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  26897. };
  26898. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  26899. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  26900. node.animations.push(animation);
  26901. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  26902. };
  26903. // Methods
  26904. /**
  26905. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26906. */
  26907. Animation.prototype.toString = function (fullDetails) {
  26908. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  26909. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  26910. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  26911. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  26912. if (fullDetails) {
  26913. ret += ", Ranges: {";
  26914. var first = true;
  26915. for (var name in this._ranges) {
  26916. if (first) {
  26917. ret += ", ";
  26918. first = false;
  26919. }
  26920. ret += name;
  26921. }
  26922. ret += "}";
  26923. }
  26924. return ret;
  26925. };
  26926. /**
  26927. * Add an event to this animation.
  26928. */
  26929. Animation.prototype.addEvent = function (event) {
  26930. this._events.push(event);
  26931. };
  26932. /**
  26933. * Remove all events found at the given frame
  26934. * @param frame
  26935. */
  26936. Animation.prototype.removeEvents = function (frame) {
  26937. for (var index = 0; index < this._events.length; index++) {
  26938. if (this._events[index].frame === frame) {
  26939. this._events.splice(index, 1);
  26940. index--;
  26941. }
  26942. }
  26943. };
  26944. Animation.prototype.createRange = function (name, from, to) {
  26945. // check name not already in use; could happen for bones after serialized
  26946. if (!this._ranges[name]) {
  26947. this._ranges[name] = new AnimationRange(name, from, to);
  26948. }
  26949. };
  26950. Animation.prototype.deleteRange = function (name, deleteFrames) {
  26951. if (deleteFrames === void 0) { deleteFrames = true; }
  26952. if (this._ranges[name]) {
  26953. if (deleteFrames) {
  26954. var from = this._ranges[name].from;
  26955. var to = this._ranges[name].to;
  26956. // this loop MUST go high to low for multiple splices to work
  26957. for (var key = this._keys.length - 1; key >= 0; key--) {
  26958. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  26959. this._keys.splice(key, 1);
  26960. }
  26961. }
  26962. }
  26963. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  26964. }
  26965. };
  26966. Animation.prototype.getRange = function (name) {
  26967. return this._ranges[name];
  26968. };
  26969. Animation.prototype.reset = function () {
  26970. this._offsetsCache = {};
  26971. this._highLimitsCache = {};
  26972. this.currentFrame = 0;
  26973. this._blendingFactor = 0;
  26974. this._originalBlendValue = null;
  26975. };
  26976. Animation.prototype.isStopped = function () {
  26977. return this._stopped;
  26978. };
  26979. Animation.prototype.getKeys = function () {
  26980. return this._keys;
  26981. };
  26982. Animation.prototype.getHighestFrame = function () {
  26983. var ret = 0;
  26984. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  26985. if (ret < this._keys[key].frame) {
  26986. ret = this._keys[key].frame;
  26987. }
  26988. }
  26989. return ret;
  26990. };
  26991. Animation.prototype.getEasingFunction = function () {
  26992. return this._easingFunction;
  26993. };
  26994. Animation.prototype.setEasingFunction = function (easingFunction) {
  26995. this._easingFunction = easingFunction;
  26996. };
  26997. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  26998. return startValue + (endValue - startValue) * gradient;
  26999. };
  27000. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  27001. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  27002. };
  27003. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  27004. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  27005. };
  27006. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  27007. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  27008. };
  27009. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  27010. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  27011. };
  27012. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  27013. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  27014. };
  27015. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  27016. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  27017. };
  27018. Animation.prototype.clone = function () {
  27019. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  27020. if (this._keys) {
  27021. clone.setKeys(this._keys);
  27022. }
  27023. if (this._ranges) {
  27024. clone._ranges = {};
  27025. for (var name in this._ranges) {
  27026. clone._ranges[name] = this._ranges[name].clone();
  27027. }
  27028. }
  27029. return clone;
  27030. };
  27031. Animation.prototype.setKeys = function (values) {
  27032. this._keys = values.slice(0);
  27033. this._offsetsCache = {};
  27034. this._highLimitsCache = {};
  27035. };
  27036. Animation.prototype._getKeyValue = function (value) {
  27037. if (typeof value === "function") {
  27038. return value();
  27039. }
  27040. return value;
  27041. };
  27042. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  27043. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  27044. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  27045. }
  27046. this.currentFrame = currentFrame;
  27047. // Try to get a hash to find the right key
  27048. 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));
  27049. if (this._keys[startKey].frame >= currentFrame) {
  27050. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  27051. startKey--;
  27052. }
  27053. }
  27054. for (var key = startKey; key < this._keys.length; key++) {
  27055. if (this._keys[key + 1].frame >= currentFrame) {
  27056. var startValue = this._getKeyValue(this._keys[key].value);
  27057. var endValue = this._getKeyValue(this._keys[key + 1].value);
  27058. // gradient : percent of currentFrame between the frame inf and the frame sup
  27059. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  27060. // check for easingFunction and correction of gradient
  27061. if (this._easingFunction != null) {
  27062. gradient = this._easingFunction.ease(gradient);
  27063. }
  27064. switch (this.dataType) {
  27065. // Float
  27066. case Animation.ANIMATIONTYPE_FLOAT:
  27067. switch (loopMode) {
  27068. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27069. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27070. return this.floatInterpolateFunction(startValue, endValue, gradient);
  27071. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27072. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  27073. }
  27074. break;
  27075. // Quaternion
  27076. case Animation.ANIMATIONTYPE_QUATERNION:
  27077. var quaternion = null;
  27078. switch (loopMode) {
  27079. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27080. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27081. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  27082. break;
  27083. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27084. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27085. break;
  27086. }
  27087. return quaternion;
  27088. // Vector3
  27089. case Animation.ANIMATIONTYPE_VECTOR3:
  27090. switch (loopMode) {
  27091. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27092. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27093. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  27094. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27095. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27096. }
  27097. // Vector2
  27098. case Animation.ANIMATIONTYPE_VECTOR2:
  27099. switch (loopMode) {
  27100. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27101. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27102. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  27103. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27104. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27105. }
  27106. // Size
  27107. case Animation.ANIMATIONTYPE_SIZE:
  27108. switch (loopMode) {
  27109. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27110. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27111. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  27112. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27113. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27114. }
  27115. // Color3
  27116. case Animation.ANIMATIONTYPE_COLOR3:
  27117. switch (loopMode) {
  27118. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27119. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27120. return this.color3InterpolateFunction(startValue, endValue, gradient);
  27121. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27122. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27123. }
  27124. // Matrix
  27125. case Animation.ANIMATIONTYPE_MATRIX:
  27126. switch (loopMode) {
  27127. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27128. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27129. if (this.allowMatricesInterpolation) {
  27130. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  27131. }
  27132. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27133. return startValue;
  27134. }
  27135. default:
  27136. break;
  27137. }
  27138. break;
  27139. }
  27140. }
  27141. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  27142. };
  27143. Animation.prototype.setValue = function (currentValue, blend) {
  27144. if (blend === void 0) { blend = false; }
  27145. // Set value
  27146. var path;
  27147. var destination;
  27148. if (this.targetPropertyPath.length > 1) {
  27149. var property = this._target[this.targetPropertyPath[0]];
  27150. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  27151. property = property[this.targetPropertyPath[index]];
  27152. }
  27153. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  27154. destination = property;
  27155. }
  27156. else {
  27157. path = this.targetPropertyPath[0];
  27158. destination = this._target;
  27159. }
  27160. // Blending
  27161. if (this.enableBlending && this._blendingFactor <= 1.0) {
  27162. if (!this._originalBlendValue) {
  27163. if (destination[path].clone) {
  27164. this._originalBlendValue = destination[path].clone();
  27165. }
  27166. else {
  27167. this._originalBlendValue = destination[path];
  27168. }
  27169. }
  27170. if (this._originalBlendValue.prototype) {
  27171. if (this._originalBlendValue.prototype.Lerp) {
  27172. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  27173. }
  27174. else {
  27175. destination[path] = currentValue;
  27176. }
  27177. }
  27178. else if (this._originalBlendValue.m) {
  27179. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  27180. }
  27181. else {
  27182. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  27183. }
  27184. this._blendingFactor += this.blendingSpeed;
  27185. }
  27186. else {
  27187. destination[path] = currentValue;
  27188. }
  27189. if (this._target.markAsDirty) {
  27190. this._target.markAsDirty(this.targetProperty);
  27191. }
  27192. };
  27193. Animation.prototype.goToFrame = function (frame) {
  27194. if (frame < this._keys[0].frame) {
  27195. frame = this._keys[0].frame;
  27196. }
  27197. else if (frame > this._keys[this._keys.length - 1].frame) {
  27198. frame = this._keys[this._keys.length - 1].frame;
  27199. }
  27200. var currentValue = this._interpolate(frame, 0, this.loopMode);
  27201. this.setValue(currentValue);
  27202. };
  27203. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  27204. if (blend === void 0) { blend = false; }
  27205. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  27206. this._stopped = true;
  27207. return false;
  27208. }
  27209. var returnValue = true;
  27210. // Adding a start key at frame 0 if missing
  27211. if (this._keys[0].frame !== 0) {
  27212. var newKey = { frame: 0, value: this._keys[0].value };
  27213. this._keys.splice(0, 0, newKey);
  27214. }
  27215. // Check limits
  27216. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  27217. from = this._keys[0].frame;
  27218. }
  27219. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  27220. to = this._keys[this._keys.length - 1].frame;
  27221. }
  27222. // Compute ratio
  27223. var range = to - from;
  27224. var offsetValue;
  27225. // ratio represents the frame delta between from and to
  27226. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  27227. var highLimitValue = 0;
  27228. if (ratio > range && !loop) {
  27229. returnValue = false;
  27230. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  27231. }
  27232. else {
  27233. // Get max value if required
  27234. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  27235. var keyOffset = to.toString() + from.toString();
  27236. if (!this._offsetsCache[keyOffset]) {
  27237. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  27238. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  27239. switch (this.dataType) {
  27240. // Float
  27241. case Animation.ANIMATIONTYPE_FLOAT:
  27242. this._offsetsCache[keyOffset] = toValue - fromValue;
  27243. break;
  27244. // Quaternion
  27245. case Animation.ANIMATIONTYPE_QUATERNION:
  27246. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27247. break;
  27248. // Vector3
  27249. case Animation.ANIMATIONTYPE_VECTOR3:
  27250. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27251. // Vector2
  27252. case Animation.ANIMATIONTYPE_VECTOR2:
  27253. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27254. // Size
  27255. case Animation.ANIMATIONTYPE_SIZE:
  27256. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27257. // Color3
  27258. case Animation.ANIMATIONTYPE_COLOR3:
  27259. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27260. default:
  27261. break;
  27262. }
  27263. this._highLimitsCache[keyOffset] = toValue;
  27264. }
  27265. highLimitValue = this._highLimitsCache[keyOffset];
  27266. offsetValue = this._offsetsCache[keyOffset];
  27267. }
  27268. }
  27269. if (offsetValue === undefined) {
  27270. switch (this.dataType) {
  27271. // Float
  27272. case Animation.ANIMATIONTYPE_FLOAT:
  27273. offsetValue = 0;
  27274. break;
  27275. // Quaternion
  27276. case Animation.ANIMATIONTYPE_QUATERNION:
  27277. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  27278. break;
  27279. // Vector3
  27280. case Animation.ANIMATIONTYPE_VECTOR3:
  27281. offsetValue = BABYLON.Vector3.Zero();
  27282. break;
  27283. // Vector2
  27284. case Animation.ANIMATIONTYPE_VECTOR2:
  27285. offsetValue = BABYLON.Vector2.Zero();
  27286. break;
  27287. // Size
  27288. case Animation.ANIMATIONTYPE_SIZE:
  27289. offsetValue = BABYLON.Size.Zero();
  27290. break;
  27291. // Color3
  27292. case Animation.ANIMATIONTYPE_COLOR3:
  27293. offsetValue = BABYLON.Color3.Black();
  27294. }
  27295. }
  27296. // Compute value
  27297. var repeatCount = (ratio / range) >> 0;
  27298. var currentFrame = returnValue ? from + ratio % range : to;
  27299. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  27300. // Set value
  27301. this.setValue(currentValue);
  27302. // Check events
  27303. for (var index = 0; index < this._events.length; index++) {
  27304. if (currentFrame >= this._events[index].frame) {
  27305. var event = this._events[index];
  27306. if (!event.isDone) {
  27307. // If event should be done only once, remove it.
  27308. if (event.onlyOnce) {
  27309. this._events.splice(index, 1);
  27310. index--;
  27311. }
  27312. event.isDone = true;
  27313. event.action();
  27314. } // Don't do anything if the event has already be done.
  27315. }
  27316. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  27317. // reset event, the animation is looping
  27318. this._events[index].isDone = false;
  27319. }
  27320. }
  27321. if (!returnValue) {
  27322. this._stopped = true;
  27323. }
  27324. return returnValue;
  27325. };
  27326. Animation.prototype.serialize = function () {
  27327. var serializationObject = {};
  27328. serializationObject.name = this.name;
  27329. serializationObject.property = this.targetProperty;
  27330. serializationObject.framePerSecond = this.framePerSecond;
  27331. serializationObject.dataType = this.dataType;
  27332. serializationObject.loopBehavior = this.loopMode;
  27333. var dataType = this.dataType;
  27334. serializationObject.keys = [];
  27335. var keys = this.getKeys();
  27336. for (var index = 0; index < keys.length; index++) {
  27337. var animationKey = keys[index];
  27338. var key = {};
  27339. key.frame = animationKey.frame;
  27340. switch (dataType) {
  27341. case Animation.ANIMATIONTYPE_FLOAT:
  27342. key.values = [animationKey.value];
  27343. break;
  27344. case Animation.ANIMATIONTYPE_QUATERNION:
  27345. case Animation.ANIMATIONTYPE_MATRIX:
  27346. case Animation.ANIMATIONTYPE_VECTOR3:
  27347. case Animation.ANIMATIONTYPE_COLOR3:
  27348. key.values = animationKey.value.asArray();
  27349. break;
  27350. }
  27351. serializationObject.keys.push(key);
  27352. }
  27353. serializationObject.ranges = [];
  27354. for (var name in this._ranges) {
  27355. var range = {};
  27356. range.name = name;
  27357. range.from = this._ranges[name].from;
  27358. range.to = this._ranges[name].to;
  27359. serializationObject.ranges.push(range);
  27360. }
  27361. return serializationObject;
  27362. };
  27363. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  27364. get: function () {
  27365. return Animation._ANIMATIONTYPE_FLOAT;
  27366. },
  27367. enumerable: true,
  27368. configurable: true
  27369. });
  27370. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  27371. get: function () {
  27372. return Animation._ANIMATIONTYPE_VECTOR3;
  27373. },
  27374. enumerable: true,
  27375. configurable: true
  27376. });
  27377. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  27378. get: function () {
  27379. return Animation._ANIMATIONTYPE_VECTOR2;
  27380. },
  27381. enumerable: true,
  27382. configurable: true
  27383. });
  27384. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  27385. get: function () {
  27386. return Animation._ANIMATIONTYPE_SIZE;
  27387. },
  27388. enumerable: true,
  27389. configurable: true
  27390. });
  27391. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  27392. get: function () {
  27393. return Animation._ANIMATIONTYPE_QUATERNION;
  27394. },
  27395. enumerable: true,
  27396. configurable: true
  27397. });
  27398. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  27399. get: function () {
  27400. return Animation._ANIMATIONTYPE_MATRIX;
  27401. },
  27402. enumerable: true,
  27403. configurable: true
  27404. });
  27405. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  27406. get: function () {
  27407. return Animation._ANIMATIONTYPE_COLOR3;
  27408. },
  27409. enumerable: true,
  27410. configurable: true
  27411. });
  27412. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  27413. get: function () {
  27414. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  27415. },
  27416. enumerable: true,
  27417. configurable: true
  27418. });
  27419. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  27420. get: function () {
  27421. return Animation._ANIMATIONLOOPMODE_CYCLE;
  27422. },
  27423. enumerable: true,
  27424. configurable: true
  27425. });
  27426. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  27427. get: function () {
  27428. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  27429. },
  27430. enumerable: true,
  27431. configurable: true
  27432. });
  27433. Animation.Parse = function (parsedAnimation) {
  27434. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  27435. var dataType = parsedAnimation.dataType;
  27436. var keys = [];
  27437. var data;
  27438. var index;
  27439. for (index = 0; index < parsedAnimation.keys.length; index++) {
  27440. var key = parsedAnimation.keys[index];
  27441. switch (dataType) {
  27442. case Animation.ANIMATIONTYPE_FLOAT:
  27443. data = key.values[0];
  27444. break;
  27445. case Animation.ANIMATIONTYPE_QUATERNION:
  27446. data = BABYLON.Quaternion.FromArray(key.values);
  27447. break;
  27448. case Animation.ANIMATIONTYPE_MATRIX:
  27449. data = BABYLON.Matrix.FromArray(key.values);
  27450. break;
  27451. case Animation.ANIMATIONTYPE_COLOR3:
  27452. data = BABYLON.Color3.FromArray(key.values);
  27453. break;
  27454. case Animation.ANIMATIONTYPE_VECTOR3:
  27455. default:
  27456. data = BABYLON.Vector3.FromArray(key.values);
  27457. break;
  27458. }
  27459. keys.push({
  27460. frame: key.frame,
  27461. value: data
  27462. });
  27463. }
  27464. animation.setKeys(keys);
  27465. if (parsedAnimation.ranges) {
  27466. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  27467. data = parsedAnimation.ranges[index];
  27468. animation.createRange(data.name, data.from, data.to);
  27469. }
  27470. }
  27471. return animation;
  27472. };
  27473. Animation.AppendSerializedAnimations = function (source, destination) {
  27474. if (source.animations) {
  27475. destination.animations = [];
  27476. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  27477. var animation = source.animations[animationIndex];
  27478. destination.animations.push(animation.serialize());
  27479. }
  27480. }
  27481. };
  27482. // Statics
  27483. Animation._ANIMATIONTYPE_FLOAT = 0;
  27484. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  27485. Animation._ANIMATIONTYPE_QUATERNION = 2;
  27486. Animation._ANIMATIONTYPE_MATRIX = 3;
  27487. Animation._ANIMATIONTYPE_COLOR3 = 4;
  27488. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  27489. Animation._ANIMATIONTYPE_SIZE = 6;
  27490. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  27491. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  27492. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  27493. return Animation;
  27494. }());
  27495. BABYLON.Animation = Animation;
  27496. })(BABYLON || (BABYLON = {}));
  27497. var BABYLON;
  27498. (function (BABYLON) {
  27499. var Animatable = (function () {
  27500. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  27501. if (fromFrame === void 0) { fromFrame = 0; }
  27502. if (toFrame === void 0) { toFrame = 100; }
  27503. if (loopAnimation === void 0) { loopAnimation = false; }
  27504. if (speedRatio === void 0) { speedRatio = 1.0; }
  27505. this.target = target;
  27506. this.fromFrame = fromFrame;
  27507. this.toFrame = toFrame;
  27508. this.loopAnimation = loopAnimation;
  27509. this.speedRatio = speedRatio;
  27510. this.onAnimationEnd = onAnimationEnd;
  27511. this._animations = new Array();
  27512. this._paused = false;
  27513. this.animationStarted = false;
  27514. if (animations) {
  27515. this.appendAnimations(target, animations);
  27516. }
  27517. this._scene = scene;
  27518. scene._activeAnimatables.push(this);
  27519. }
  27520. // Methods
  27521. Animatable.prototype.getAnimations = function () {
  27522. return this._animations;
  27523. };
  27524. Animatable.prototype.appendAnimations = function (target, animations) {
  27525. for (var index = 0; index < animations.length; index++) {
  27526. var animation = animations[index];
  27527. animation._target = target;
  27528. this._animations.push(animation);
  27529. }
  27530. };
  27531. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  27532. var animations = this._animations;
  27533. for (var index = 0; index < animations.length; index++) {
  27534. if (animations[index].targetProperty === property) {
  27535. return animations[index];
  27536. }
  27537. }
  27538. return null;
  27539. };
  27540. Animatable.prototype.reset = function () {
  27541. var animations = this._animations;
  27542. for (var index = 0; index < animations.length; index++) {
  27543. animations[index].reset();
  27544. }
  27545. this._localDelayOffset = null;
  27546. this._pausedDelay = null;
  27547. };
  27548. Animatable.prototype.enableBlending = function (blendingSpeed) {
  27549. var animations = this._animations;
  27550. for (var index = 0; index < animations.length; index++) {
  27551. animations[index].enableBlending = true;
  27552. animations[index].blendingSpeed = blendingSpeed;
  27553. }
  27554. };
  27555. Animatable.prototype.disableBlending = function () {
  27556. var animations = this._animations;
  27557. for (var index = 0; index < animations.length; index++) {
  27558. animations[index].enableBlending = false;
  27559. }
  27560. };
  27561. Animatable.prototype.goToFrame = function (frame) {
  27562. var animations = this._animations;
  27563. for (var index = 0; index < animations.length; index++) {
  27564. animations[index].goToFrame(frame);
  27565. }
  27566. };
  27567. Animatable.prototype.pause = function () {
  27568. if (this._paused) {
  27569. return;
  27570. }
  27571. this._paused = true;
  27572. };
  27573. Animatable.prototype.restart = function () {
  27574. this._paused = false;
  27575. };
  27576. Animatable.prototype.stop = function () {
  27577. var index = this._scene._activeAnimatables.indexOf(this);
  27578. if (index > -1) {
  27579. this._scene._activeAnimatables.splice(index, 1);
  27580. var animations = this._animations;
  27581. for (var index = 0; index < animations.length; index++) {
  27582. animations[index].reset();
  27583. }
  27584. if (this.onAnimationEnd) {
  27585. this.onAnimationEnd();
  27586. }
  27587. }
  27588. };
  27589. Animatable.prototype._animate = function (delay) {
  27590. if (this._paused) {
  27591. this.animationStarted = false;
  27592. if (!this._pausedDelay) {
  27593. this._pausedDelay = delay;
  27594. }
  27595. return true;
  27596. }
  27597. if (!this._localDelayOffset) {
  27598. this._localDelayOffset = delay;
  27599. }
  27600. else if (this._pausedDelay) {
  27601. this._localDelayOffset += delay - this._pausedDelay;
  27602. this._pausedDelay = null;
  27603. }
  27604. // Animating
  27605. var running = false;
  27606. var animations = this._animations;
  27607. var index;
  27608. for (index = 0; index < animations.length; index++) {
  27609. var animation = animations[index];
  27610. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  27611. running = running || isRunning;
  27612. }
  27613. this.animationStarted = running;
  27614. if (!running) {
  27615. // Remove from active animatables
  27616. index = this._scene._activeAnimatables.indexOf(this);
  27617. this._scene._activeAnimatables.splice(index, 1);
  27618. }
  27619. if (!running && this.onAnimationEnd) {
  27620. this.onAnimationEnd();
  27621. this.onAnimationEnd = null;
  27622. }
  27623. return running;
  27624. };
  27625. return Animatable;
  27626. }());
  27627. BABYLON.Animatable = Animatable;
  27628. })(BABYLON || (BABYLON = {}));
  27629. var BABYLON;
  27630. (function (BABYLON) {
  27631. var EasingFunction = (function () {
  27632. function EasingFunction() {
  27633. // Properties
  27634. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  27635. }
  27636. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  27637. get: function () {
  27638. return EasingFunction._EASINGMODE_EASEIN;
  27639. },
  27640. enumerable: true,
  27641. configurable: true
  27642. });
  27643. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  27644. get: function () {
  27645. return EasingFunction._EASINGMODE_EASEOUT;
  27646. },
  27647. enumerable: true,
  27648. configurable: true
  27649. });
  27650. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  27651. get: function () {
  27652. return EasingFunction._EASINGMODE_EASEINOUT;
  27653. },
  27654. enumerable: true,
  27655. configurable: true
  27656. });
  27657. EasingFunction.prototype.setEasingMode = function (easingMode) {
  27658. var n = Math.min(Math.max(easingMode, 0), 2);
  27659. this._easingMode = n;
  27660. };
  27661. EasingFunction.prototype.getEasingMode = function () {
  27662. return this._easingMode;
  27663. };
  27664. EasingFunction.prototype.easeInCore = function (gradient) {
  27665. throw new Error('You must implement this method');
  27666. };
  27667. EasingFunction.prototype.ease = function (gradient) {
  27668. switch (this._easingMode) {
  27669. case EasingFunction.EASINGMODE_EASEIN:
  27670. return this.easeInCore(gradient);
  27671. case EasingFunction.EASINGMODE_EASEOUT:
  27672. return (1 - this.easeInCore(1 - gradient));
  27673. }
  27674. if (gradient >= 0.5) {
  27675. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  27676. }
  27677. return (this.easeInCore(gradient * 2) * 0.5);
  27678. };
  27679. //Statics
  27680. EasingFunction._EASINGMODE_EASEIN = 0;
  27681. EasingFunction._EASINGMODE_EASEOUT = 1;
  27682. EasingFunction._EASINGMODE_EASEINOUT = 2;
  27683. return EasingFunction;
  27684. }());
  27685. BABYLON.EasingFunction = EasingFunction;
  27686. var CircleEase = (function (_super) {
  27687. __extends(CircleEase, _super);
  27688. function CircleEase() {
  27689. _super.apply(this, arguments);
  27690. }
  27691. CircleEase.prototype.easeInCore = function (gradient) {
  27692. gradient = Math.max(0, Math.min(1, gradient));
  27693. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  27694. };
  27695. return CircleEase;
  27696. }(EasingFunction));
  27697. BABYLON.CircleEase = CircleEase;
  27698. var BackEase = (function (_super) {
  27699. __extends(BackEase, _super);
  27700. function BackEase(amplitude) {
  27701. if (amplitude === void 0) { amplitude = 1; }
  27702. _super.call(this);
  27703. this.amplitude = amplitude;
  27704. }
  27705. BackEase.prototype.easeInCore = function (gradient) {
  27706. var num = Math.max(0, this.amplitude);
  27707. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  27708. };
  27709. return BackEase;
  27710. }(EasingFunction));
  27711. BABYLON.BackEase = BackEase;
  27712. var BounceEase = (function (_super) {
  27713. __extends(BounceEase, _super);
  27714. function BounceEase(bounces, bounciness) {
  27715. if (bounces === void 0) { bounces = 3; }
  27716. if (bounciness === void 0) { bounciness = 2; }
  27717. _super.call(this);
  27718. this.bounces = bounces;
  27719. this.bounciness = bounciness;
  27720. }
  27721. BounceEase.prototype.easeInCore = function (gradient) {
  27722. var y = Math.max(0.0, this.bounces);
  27723. var bounciness = this.bounciness;
  27724. if (bounciness <= 1.0) {
  27725. bounciness = 1.001;
  27726. }
  27727. var num9 = Math.pow(bounciness, y);
  27728. var num5 = 1.0 - bounciness;
  27729. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  27730. var num15 = gradient * num4;
  27731. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  27732. var num3 = Math.floor(num65);
  27733. var num13 = num3 + 1.0;
  27734. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  27735. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  27736. var num7 = (num8 + num12) * 0.5;
  27737. var num6 = gradient - num7;
  27738. var num2 = num7 - num8;
  27739. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  27740. };
  27741. return BounceEase;
  27742. }(EasingFunction));
  27743. BABYLON.BounceEase = BounceEase;
  27744. var CubicEase = (function (_super) {
  27745. __extends(CubicEase, _super);
  27746. function CubicEase() {
  27747. _super.apply(this, arguments);
  27748. }
  27749. CubicEase.prototype.easeInCore = function (gradient) {
  27750. return (gradient * gradient * gradient);
  27751. };
  27752. return CubicEase;
  27753. }(EasingFunction));
  27754. BABYLON.CubicEase = CubicEase;
  27755. var ElasticEase = (function (_super) {
  27756. __extends(ElasticEase, _super);
  27757. function ElasticEase(oscillations, springiness) {
  27758. if (oscillations === void 0) { oscillations = 3; }
  27759. if (springiness === void 0) { springiness = 3; }
  27760. _super.call(this);
  27761. this.oscillations = oscillations;
  27762. this.springiness = springiness;
  27763. }
  27764. ElasticEase.prototype.easeInCore = function (gradient) {
  27765. var num2;
  27766. var num3 = Math.max(0.0, this.oscillations);
  27767. var num = Math.max(0.0, this.springiness);
  27768. if (num == 0) {
  27769. num2 = gradient;
  27770. }
  27771. else {
  27772. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  27773. }
  27774. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  27775. };
  27776. return ElasticEase;
  27777. }(EasingFunction));
  27778. BABYLON.ElasticEase = ElasticEase;
  27779. var ExponentialEase = (function (_super) {
  27780. __extends(ExponentialEase, _super);
  27781. function ExponentialEase(exponent) {
  27782. if (exponent === void 0) { exponent = 2; }
  27783. _super.call(this);
  27784. this.exponent = exponent;
  27785. }
  27786. ExponentialEase.prototype.easeInCore = function (gradient) {
  27787. if (this.exponent <= 0) {
  27788. return gradient;
  27789. }
  27790. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  27791. };
  27792. return ExponentialEase;
  27793. }(EasingFunction));
  27794. BABYLON.ExponentialEase = ExponentialEase;
  27795. var PowerEase = (function (_super) {
  27796. __extends(PowerEase, _super);
  27797. function PowerEase(power) {
  27798. if (power === void 0) { power = 2; }
  27799. _super.call(this);
  27800. this.power = power;
  27801. }
  27802. PowerEase.prototype.easeInCore = function (gradient) {
  27803. var y = Math.max(0.0, this.power);
  27804. return Math.pow(gradient, y);
  27805. };
  27806. return PowerEase;
  27807. }(EasingFunction));
  27808. BABYLON.PowerEase = PowerEase;
  27809. var QuadraticEase = (function (_super) {
  27810. __extends(QuadraticEase, _super);
  27811. function QuadraticEase() {
  27812. _super.apply(this, arguments);
  27813. }
  27814. QuadraticEase.prototype.easeInCore = function (gradient) {
  27815. return (gradient * gradient);
  27816. };
  27817. return QuadraticEase;
  27818. }(EasingFunction));
  27819. BABYLON.QuadraticEase = QuadraticEase;
  27820. var QuarticEase = (function (_super) {
  27821. __extends(QuarticEase, _super);
  27822. function QuarticEase() {
  27823. _super.apply(this, arguments);
  27824. }
  27825. QuarticEase.prototype.easeInCore = function (gradient) {
  27826. return (gradient * gradient * gradient * gradient);
  27827. };
  27828. return QuarticEase;
  27829. }(EasingFunction));
  27830. BABYLON.QuarticEase = QuarticEase;
  27831. var QuinticEase = (function (_super) {
  27832. __extends(QuinticEase, _super);
  27833. function QuinticEase() {
  27834. _super.apply(this, arguments);
  27835. }
  27836. QuinticEase.prototype.easeInCore = function (gradient) {
  27837. return (gradient * gradient * gradient * gradient * gradient);
  27838. };
  27839. return QuinticEase;
  27840. }(EasingFunction));
  27841. BABYLON.QuinticEase = QuinticEase;
  27842. var SineEase = (function (_super) {
  27843. __extends(SineEase, _super);
  27844. function SineEase() {
  27845. _super.apply(this, arguments);
  27846. }
  27847. SineEase.prototype.easeInCore = function (gradient) {
  27848. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  27849. };
  27850. return SineEase;
  27851. }(EasingFunction));
  27852. BABYLON.SineEase = SineEase;
  27853. var BezierCurveEase = (function (_super) {
  27854. __extends(BezierCurveEase, _super);
  27855. function BezierCurveEase(x1, y1, x2, y2) {
  27856. if (x1 === void 0) { x1 = 0; }
  27857. if (y1 === void 0) { y1 = 0; }
  27858. if (x2 === void 0) { x2 = 1; }
  27859. if (y2 === void 0) { y2 = 1; }
  27860. _super.call(this);
  27861. this.x1 = x1;
  27862. this.y1 = y1;
  27863. this.x2 = x2;
  27864. this.y2 = y2;
  27865. }
  27866. BezierCurveEase.prototype.easeInCore = function (gradient) {
  27867. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  27868. };
  27869. return BezierCurveEase;
  27870. }(EasingFunction));
  27871. BABYLON.BezierCurveEase = BezierCurveEase;
  27872. })(BABYLON || (BABYLON = {}));
  27873. var BABYLON;
  27874. (function (BABYLON) {
  27875. var Bone = (function (_super) {
  27876. __extends(Bone, _super);
  27877. function Bone(name, skeleton, parentBone, matrix, restPose) {
  27878. _super.call(this, name, skeleton.getScene());
  27879. this.name = name;
  27880. this.children = new Array();
  27881. this.animations = new Array();
  27882. this._worldTransform = new BABYLON.Matrix();
  27883. this._absoluteTransform = new BABYLON.Matrix();
  27884. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  27885. this._skeleton = skeleton;
  27886. this._matrix = matrix;
  27887. this._baseMatrix = matrix;
  27888. this._restPose = restPose ? restPose : matrix.clone();
  27889. skeleton.bones.push(this);
  27890. if (parentBone) {
  27891. this._parent = parentBone;
  27892. parentBone.children.push(this);
  27893. }
  27894. else {
  27895. this._parent = null;
  27896. }
  27897. this._updateDifferenceMatrix();
  27898. }
  27899. // Members
  27900. Bone.prototype.getParent = function () {
  27901. return this._parent;
  27902. };
  27903. Bone.prototype.getLocalMatrix = function () {
  27904. return this._matrix;
  27905. };
  27906. Bone.prototype.getBaseMatrix = function () {
  27907. return this._baseMatrix;
  27908. };
  27909. Bone.prototype.getRestPose = function () {
  27910. return this._restPose;
  27911. };
  27912. Bone.prototype.returnToRest = function () {
  27913. this.updateMatrix(this._restPose.clone());
  27914. };
  27915. Bone.prototype.getWorldMatrix = function () {
  27916. return this._worldTransform;
  27917. };
  27918. Bone.prototype.getInvertedAbsoluteTransform = function () {
  27919. return this._invertedAbsoluteTransform;
  27920. };
  27921. Bone.prototype.getAbsoluteTransform = function () {
  27922. return this._absoluteTransform;
  27923. };
  27924. // Methods
  27925. Bone.prototype.updateMatrix = function (matrix) {
  27926. this._baseMatrix = matrix.clone();
  27927. this._matrix = matrix.clone();
  27928. this._skeleton._markAsDirty();
  27929. this._updateDifferenceMatrix();
  27930. };
  27931. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  27932. if (!rootMatrix) {
  27933. rootMatrix = this._baseMatrix;
  27934. }
  27935. if (this._parent) {
  27936. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  27937. }
  27938. else {
  27939. this._absoluteTransform.copyFrom(rootMatrix);
  27940. }
  27941. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  27942. for (var index = 0; index < this.children.length; index++) {
  27943. this.children[index]._updateDifferenceMatrix();
  27944. }
  27945. };
  27946. Bone.prototype.markAsDirty = function () {
  27947. this._currentRenderId++;
  27948. this._skeleton._markAsDirty();
  27949. };
  27950. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  27951. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  27952. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  27953. // all animation may be coming from a library skeleton, so may need to create animation
  27954. if (this.animations.length === 0) {
  27955. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  27956. this.animations[0].setKeys([]);
  27957. }
  27958. // get animation info / verify there is such a range from the source bone
  27959. var sourceRange = source.animations[0].getRange(rangeName);
  27960. if (!sourceRange) {
  27961. return false;
  27962. }
  27963. var from = sourceRange.from;
  27964. var to = sourceRange.to;
  27965. var sourceKeys = source.animations[0].getKeys();
  27966. // rescaling prep
  27967. var sourceBoneLength = source.length;
  27968. var sourceParent = source.getParent();
  27969. var parent = this.getParent();
  27970. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  27971. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  27972. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  27973. var destKeys = this.animations[0].getKeys();
  27974. // loop vars declaration
  27975. var orig;
  27976. var origTranslation;
  27977. var mat;
  27978. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  27979. orig = sourceKeys[key];
  27980. if (orig.frame >= from && orig.frame <= to) {
  27981. if (rescaleAsRequired) {
  27982. mat = orig.value.clone();
  27983. // scale based on parent ratio, when bone has parent
  27984. if (parentScalingReqd) {
  27985. origTranslation = mat.getTranslation();
  27986. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  27987. }
  27988. else if (dimensionsScalingReqd) {
  27989. origTranslation = mat.getTranslation();
  27990. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  27991. }
  27992. else {
  27993. mat = orig.value;
  27994. }
  27995. }
  27996. else {
  27997. mat = orig.value;
  27998. }
  27999. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  28000. }
  28001. }
  28002. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  28003. return true;
  28004. };
  28005. return Bone;
  28006. }(BABYLON.Node));
  28007. BABYLON.Bone = Bone;
  28008. })(BABYLON || (BABYLON = {}));
  28009. var BABYLON;
  28010. (function (BABYLON) {
  28011. var Skeleton = (function () {
  28012. function Skeleton(name, id, scene) {
  28013. this.name = name;
  28014. this.id = id;
  28015. this.bones = new Array();
  28016. this.needInitialSkinMatrix = false;
  28017. this._isDirty = true;
  28018. this._meshesWithPoseMatrix = new Array();
  28019. this._identity = BABYLON.Matrix.Identity();
  28020. this._ranges = {};
  28021. this.bones = [];
  28022. this._scene = scene;
  28023. scene.skeletons.push(this);
  28024. //make sure it will recalculate the matrix next time prepare is called.
  28025. this._isDirty = true;
  28026. }
  28027. // Members
  28028. Skeleton.prototype.getTransformMatrices = function (mesh) {
  28029. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  28030. return mesh._bonesTransformMatrices;
  28031. }
  28032. return this._transformMatrices;
  28033. };
  28034. Skeleton.prototype.getScene = function () {
  28035. return this._scene;
  28036. };
  28037. // Methods
  28038. /**
  28039. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28040. */
  28041. Skeleton.prototype.toString = function (fullDetails) {
  28042. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  28043. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  28044. if (fullDetails) {
  28045. ret += ", Ranges: {";
  28046. var first = true;
  28047. for (var name_1 in this._ranges) {
  28048. if (first) {
  28049. ret += ", ";
  28050. first = false;
  28051. }
  28052. ret += name_1;
  28053. }
  28054. ret += "}";
  28055. }
  28056. return ret;
  28057. };
  28058. /**
  28059. * Get bone's index searching by name
  28060. * @param {string} name is bone's name to search for
  28061. * @return {number} Indice of the bone. Returns -1 if not found
  28062. */
  28063. Skeleton.prototype.getBoneIndexByName = function (name) {
  28064. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  28065. if (this.bones[boneIndex].name === name) {
  28066. return boneIndex;
  28067. }
  28068. }
  28069. return -1;
  28070. };
  28071. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  28072. // check name not already in use
  28073. if (!this._ranges[name]) {
  28074. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  28075. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  28076. if (this.bones[i].animations[0]) {
  28077. this.bones[i].animations[0].createRange(name, from, to);
  28078. }
  28079. }
  28080. }
  28081. };
  28082. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  28083. if (deleteFrames === void 0) { deleteFrames = true; }
  28084. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  28085. if (this.bones[i].animations[0]) {
  28086. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  28087. }
  28088. }
  28089. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  28090. };
  28091. Skeleton.prototype.getAnimationRange = function (name) {
  28092. return this._ranges[name];
  28093. };
  28094. /**
  28095. * Returns as an Array, all AnimationRanges defined on this skeleton
  28096. */
  28097. Skeleton.prototype.getAnimationRanges = function () {
  28098. var animationRanges = [];
  28099. var name;
  28100. var i = 0;
  28101. for (name in this._ranges) {
  28102. animationRanges[i] = this._ranges[name];
  28103. i++;
  28104. }
  28105. return animationRanges;
  28106. };
  28107. /**
  28108. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  28109. */
  28110. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  28111. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  28112. if (this._ranges[name] || !source.getAnimationRange(name)) {
  28113. return false;
  28114. }
  28115. var ret = true;
  28116. var frameOffset = this._getHighestAnimationFrame() + 1;
  28117. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  28118. var boneDict = {};
  28119. var sourceBones = source.bones;
  28120. var nBones;
  28121. var i;
  28122. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  28123. boneDict[sourceBones[i].name] = sourceBones[i];
  28124. }
  28125. if (this.bones.length !== sourceBones.length) {
  28126. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  28127. ret = false;
  28128. }
  28129. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  28130. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  28131. var boneName = this.bones[i].name;
  28132. var sourceBone = boneDict[boneName];
  28133. if (sourceBone) {
  28134. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  28135. }
  28136. else {
  28137. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  28138. ret = false;
  28139. }
  28140. }
  28141. // do not call createAnimationRange(), since it also is done to bones, which was already done
  28142. var range = source.getAnimationRange(name);
  28143. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  28144. return ret;
  28145. };
  28146. Skeleton.prototype.returnToRest = function () {
  28147. for (var index = 0; index < this.bones.length; index++) {
  28148. this.bones[index].returnToRest();
  28149. }
  28150. };
  28151. Skeleton.prototype._getHighestAnimationFrame = function () {
  28152. var ret = 0;
  28153. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  28154. if (this.bones[i].animations[0]) {
  28155. var highest = this.bones[i].animations[0].getHighestFrame();
  28156. if (ret < highest) {
  28157. ret = highest;
  28158. }
  28159. }
  28160. }
  28161. return ret;
  28162. };
  28163. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  28164. var range = this.getAnimationRange(name);
  28165. if (!range) {
  28166. return null;
  28167. }
  28168. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  28169. };
  28170. Skeleton.prototype._markAsDirty = function () {
  28171. this._isDirty = true;
  28172. };
  28173. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  28174. this._meshesWithPoseMatrix.push(mesh);
  28175. };
  28176. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  28177. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  28178. if (index > -1) {
  28179. this._meshesWithPoseMatrix.splice(index, 1);
  28180. }
  28181. };
  28182. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  28183. for (var index = 0; index < this.bones.length; index++) {
  28184. var bone = this.bones[index];
  28185. var parentBone = bone.getParent();
  28186. if (parentBone) {
  28187. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  28188. }
  28189. else {
  28190. if (initialSkinMatrix) {
  28191. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  28192. }
  28193. else {
  28194. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  28195. }
  28196. }
  28197. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  28198. }
  28199. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  28200. };
  28201. Skeleton.prototype.prepare = function () {
  28202. if (!this._isDirty) {
  28203. return;
  28204. }
  28205. if (this.needInitialSkinMatrix) {
  28206. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  28207. var mesh = this._meshesWithPoseMatrix[index];
  28208. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  28209. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  28210. }
  28211. var poseMatrix = mesh.getPoseMatrix();
  28212. // Prepare bones
  28213. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  28214. var bone = this.bones[boneIndex];
  28215. if (!bone.getParent()) {
  28216. var matrix = bone.getBaseMatrix();
  28217. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  28218. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  28219. }
  28220. }
  28221. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  28222. }
  28223. }
  28224. else {
  28225. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  28226. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  28227. }
  28228. this._computeTransformMatrices(this._transformMatrices, null);
  28229. }
  28230. this._isDirty = false;
  28231. this._scene._activeBones.addCount(this.bones.length, false);
  28232. };
  28233. Skeleton.prototype.getAnimatables = function () {
  28234. if (!this._animatables || this._animatables.length !== this.bones.length) {
  28235. this._animatables = [];
  28236. for (var index = 0; index < this.bones.length; index++) {
  28237. this._animatables.push(this.bones[index]);
  28238. }
  28239. }
  28240. return this._animatables;
  28241. };
  28242. Skeleton.prototype.clone = function (name, id) {
  28243. var result = new Skeleton(name, id || name, this._scene);
  28244. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  28245. for (var index = 0; index < this.bones.length; index++) {
  28246. var source = this.bones[index];
  28247. var parentBone = null;
  28248. if (source.getParent()) {
  28249. var parentIndex = this.bones.indexOf(source.getParent());
  28250. parentBone = result.bones[parentIndex];
  28251. }
  28252. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  28253. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  28254. }
  28255. if (this._ranges) {
  28256. result._ranges = {};
  28257. for (var rangeName in this._ranges) {
  28258. result._ranges[rangeName] = this._ranges[rangeName].clone();
  28259. }
  28260. }
  28261. this._isDirty = true;
  28262. return result;
  28263. };
  28264. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  28265. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  28266. this.bones.forEach(function (bone) {
  28267. bone.animations.forEach(function (animation) {
  28268. animation.enableBlending = true;
  28269. animation.blendingSpeed = blendingSpeed;
  28270. });
  28271. });
  28272. };
  28273. Skeleton.prototype.dispose = function () {
  28274. this._meshesWithPoseMatrix = [];
  28275. // Animations
  28276. this.getScene().stopAnimation(this);
  28277. // Remove from scene
  28278. this.getScene().removeSkeleton(this);
  28279. };
  28280. Skeleton.prototype.serialize = function () {
  28281. var serializationObject = {};
  28282. serializationObject.name = this.name;
  28283. serializationObject.id = this.id;
  28284. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  28285. serializationObject.bones = [];
  28286. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  28287. for (var index = 0; index < this.bones.length; index++) {
  28288. var bone = this.bones[index];
  28289. var serializedBone = {
  28290. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  28291. name: bone.name,
  28292. matrix: bone.getLocalMatrix().toArray(),
  28293. rest: bone.getRestPose().toArray()
  28294. };
  28295. serializationObject.bones.push(serializedBone);
  28296. if (bone.length) {
  28297. serializedBone.length = bone.length;
  28298. }
  28299. if (bone.animations && bone.animations.length > 0) {
  28300. serializedBone.animation = bone.animations[0].serialize();
  28301. }
  28302. serializationObject.ranges = [];
  28303. for (var name in this._ranges) {
  28304. var range = {};
  28305. range.name = name;
  28306. range.from = this._ranges[name].from;
  28307. range.to = this._ranges[name].to;
  28308. serializationObject.ranges.push(range);
  28309. }
  28310. }
  28311. return serializationObject;
  28312. };
  28313. Skeleton.Parse = function (parsedSkeleton, scene) {
  28314. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  28315. if (parsedSkeleton.dimensionsAtRest) {
  28316. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  28317. }
  28318. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  28319. var index;
  28320. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  28321. var parsedBone = parsedSkeleton.bones[index];
  28322. var parentBone = null;
  28323. if (parsedBone.parentBoneIndex > -1) {
  28324. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  28325. }
  28326. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  28327. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  28328. if (parsedBone.length) {
  28329. bone.length = parsedBone.length;
  28330. }
  28331. if (parsedBone.animation) {
  28332. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  28333. }
  28334. }
  28335. // placed after bones, so createAnimationRange can cascade down
  28336. if (parsedSkeleton.ranges) {
  28337. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  28338. var data = parsedSkeleton.ranges[index];
  28339. skeleton.createAnimationRange(data.name, data.from, data.to);
  28340. }
  28341. }
  28342. return skeleton;
  28343. };
  28344. return Skeleton;
  28345. }());
  28346. BABYLON.Skeleton = Skeleton;
  28347. })(BABYLON || (BABYLON = {}));
  28348. var BABYLON;
  28349. (function (BABYLON) {
  28350. var PostProcess = (function () {
  28351. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  28352. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  28353. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  28354. this.name = name;
  28355. this.width = -1;
  28356. this.height = -1;
  28357. /*
  28358. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  28359. Can only be used on a single postprocess or on the last one of a chain.
  28360. */
  28361. this.enablePixelPerfectMode = false;
  28362. this._reusable = false;
  28363. this._textures = new BABYLON.SmartArray(2);
  28364. this._currentRenderTextureInd = 0;
  28365. this._scaleRatio = new BABYLON.Vector2(1, 1);
  28366. // Events
  28367. /**
  28368. * An event triggered when the postprocess is activated.
  28369. * @type {BABYLON.Observable}
  28370. */
  28371. this.onActivateObservable = new BABYLON.Observable();
  28372. /**
  28373. * An event triggered when the postprocess changes its size.
  28374. * @type {BABYLON.Observable}
  28375. */
  28376. this.onSizeChangedObservable = new BABYLON.Observable();
  28377. /**
  28378. * An event triggered when the postprocess applies its effect.
  28379. * @type {BABYLON.Observable}
  28380. */
  28381. this.onApplyObservable = new BABYLON.Observable();
  28382. /**
  28383. * An event triggered before rendering the postprocess
  28384. * @type {BABYLON.Observable}
  28385. */
  28386. this.onBeforeRenderObservable = new BABYLON.Observable();
  28387. /**
  28388. * An event triggered after rendering the postprocess
  28389. * @type {BABYLON.Observable}
  28390. */
  28391. this.onAfterRenderObservable = new BABYLON.Observable();
  28392. if (camera != null) {
  28393. this._camera = camera;
  28394. this._scene = camera.getScene();
  28395. camera.attachPostProcess(this);
  28396. this._engine = this._scene.getEngine();
  28397. }
  28398. else {
  28399. this._engine = engine;
  28400. }
  28401. this._options = options;
  28402. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  28403. this._reusable = reusable || false;
  28404. this._textureType = textureType;
  28405. this._samplers = samplers || [];
  28406. this._samplers.push("textureSampler");
  28407. this._fragmentUrl = fragmentUrl;
  28408. this._parameters = parameters || [];
  28409. this._parameters.push("scale");
  28410. this.updateEffect(defines);
  28411. }
  28412. Object.defineProperty(PostProcess.prototype, "onActivate", {
  28413. set: function (callback) {
  28414. if (this._onActivateObserver) {
  28415. this.onActivateObservable.remove(this._onActivateObserver);
  28416. }
  28417. this._onActivateObserver = this.onActivateObservable.add(callback);
  28418. },
  28419. enumerable: true,
  28420. configurable: true
  28421. });
  28422. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  28423. set: function (callback) {
  28424. if (this._onSizeChangedObserver) {
  28425. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  28426. }
  28427. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  28428. },
  28429. enumerable: true,
  28430. configurable: true
  28431. });
  28432. Object.defineProperty(PostProcess.prototype, "onApply", {
  28433. set: function (callback) {
  28434. if (this._onApplyObserver) {
  28435. this.onApplyObservable.remove(this._onApplyObserver);
  28436. }
  28437. this._onApplyObserver = this.onApplyObservable.add(callback);
  28438. },
  28439. enumerable: true,
  28440. configurable: true
  28441. });
  28442. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  28443. set: function (callback) {
  28444. if (this._onBeforeRenderObserver) {
  28445. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  28446. }
  28447. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  28448. },
  28449. enumerable: true,
  28450. configurable: true
  28451. });
  28452. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  28453. set: function (callback) {
  28454. if (this._onAfterRenderObserver) {
  28455. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  28456. }
  28457. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  28458. },
  28459. enumerable: true,
  28460. configurable: true
  28461. });
  28462. PostProcess.prototype.updateEffect = function (defines) {
  28463. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  28464. };
  28465. PostProcess.prototype.isReusable = function () {
  28466. return this._reusable;
  28467. };
  28468. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  28469. PostProcess.prototype.markTextureDirty = function () {
  28470. this.width = -1;
  28471. };
  28472. PostProcess.prototype.activate = function (camera, sourceTexture) {
  28473. camera = camera || this._camera;
  28474. var scene = camera.getScene();
  28475. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  28476. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  28477. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  28478. var desiredWidth = this._options.width || requiredWidth;
  28479. var desiredHeight = this._options.height || requiredHeight;
  28480. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  28481. if (!this._options.width) {
  28482. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  28483. }
  28484. if (!this._options.height) {
  28485. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  28486. }
  28487. }
  28488. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  28489. if (this._textures.length > 0) {
  28490. for (var i = 0; i < this._textures.length; i++) {
  28491. this._engine._releaseTexture(this._textures.data[i]);
  28492. }
  28493. this._textures.reset();
  28494. }
  28495. this.width = desiredWidth;
  28496. this.height = desiredHeight;
  28497. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === 0, samplingMode: this.renderTargetSamplingMode, type: this._textureType }));
  28498. if (this._reusable) {
  28499. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === 0, samplingMode: this.renderTargetSamplingMode, type: this._textureType }));
  28500. }
  28501. this.onSizeChangedObservable.notifyObservers(this);
  28502. }
  28503. if (this.enablePixelPerfectMode) {
  28504. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  28505. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  28506. }
  28507. else {
  28508. this._scaleRatio.copyFromFloats(1, 1);
  28509. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  28510. }
  28511. this.onActivateObservable.notifyObservers(camera);
  28512. // Clear
  28513. if (this.clearColor) {
  28514. this._engine.clear(this.clearColor, true, true);
  28515. }
  28516. else {
  28517. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  28518. }
  28519. if (this._reusable) {
  28520. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  28521. }
  28522. };
  28523. Object.defineProperty(PostProcess.prototype, "isSupported", {
  28524. get: function () {
  28525. return this._effect.isSupported;
  28526. },
  28527. enumerable: true,
  28528. configurable: true
  28529. });
  28530. PostProcess.prototype.apply = function () {
  28531. // Check
  28532. if (!this._effect.isReady())
  28533. return null;
  28534. // States
  28535. this._engine.enableEffect(this._effect);
  28536. this._engine.setState(false);
  28537. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28538. this._engine.setDepthBuffer(false);
  28539. this._engine.setDepthWrite(false);
  28540. // Texture
  28541. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  28542. // Parameters
  28543. this._effect.setVector2("scale", this._scaleRatio);
  28544. this.onApplyObservable.notifyObservers(this._effect);
  28545. return this._effect;
  28546. };
  28547. PostProcess.prototype.dispose = function (camera) {
  28548. camera = camera || this._camera;
  28549. if (this._textures.length > 0) {
  28550. for (var i = 0; i < this._textures.length; i++) {
  28551. this._engine._releaseTexture(this._textures.data[i]);
  28552. }
  28553. this._textures.reset();
  28554. }
  28555. if (!camera) {
  28556. return;
  28557. }
  28558. camera.detachPostProcess(this);
  28559. var index = camera._postProcesses.indexOf(this);
  28560. if (index === 0 && camera._postProcesses.length > 0) {
  28561. this._camera._postProcesses[0].markTextureDirty();
  28562. }
  28563. this.onActivateObservable.clear();
  28564. this.onAfterRenderObservable.clear();
  28565. this.onApplyObservable.clear();
  28566. this.onBeforeRenderObservable.clear();
  28567. this.onSizeChangedObservable.clear();
  28568. };
  28569. return PostProcess;
  28570. }());
  28571. BABYLON.PostProcess = PostProcess;
  28572. })(BABYLON || (BABYLON = {}));
  28573. var BABYLON;
  28574. (function (BABYLON) {
  28575. var PostProcessManager = (function () {
  28576. function PostProcessManager(scene) {
  28577. this._vertexBuffers = {};
  28578. this._scene = scene;
  28579. }
  28580. PostProcessManager.prototype._prepareBuffers = function () {
  28581. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  28582. return;
  28583. }
  28584. // VBO
  28585. var vertices = [];
  28586. vertices.push(1, 1);
  28587. vertices.push(-1, 1);
  28588. vertices.push(-1, -1);
  28589. vertices.push(1, -1);
  28590. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28591. // Indices
  28592. var indices = [];
  28593. indices.push(0);
  28594. indices.push(1);
  28595. indices.push(2);
  28596. indices.push(0);
  28597. indices.push(2);
  28598. indices.push(3);
  28599. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  28600. };
  28601. // Methods
  28602. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  28603. var postProcesses = this._scene.activeCamera._postProcesses;
  28604. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28605. return false;
  28606. }
  28607. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  28608. return true;
  28609. };
  28610. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  28611. var engine = this._scene.getEngine();
  28612. for (var index = 0; index < postProcesses.length; index++) {
  28613. if (index < postProcesses.length - 1) {
  28614. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28615. }
  28616. else {
  28617. if (targetTexture) {
  28618. engine.bindFramebuffer(targetTexture);
  28619. }
  28620. else {
  28621. engine.restoreDefaultFramebuffer();
  28622. }
  28623. }
  28624. var pp = postProcesses[index];
  28625. var effect = pp.apply();
  28626. if (effect) {
  28627. pp.onBeforeRenderObservable.notifyObservers(effect);
  28628. // VBOs
  28629. this._prepareBuffers();
  28630. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28631. // Draw order
  28632. engine.draw(true, 0, 6);
  28633. pp.onAfterRenderObservable.notifyObservers(effect);
  28634. }
  28635. }
  28636. // Restore depth buffer
  28637. engine.setDepthBuffer(true);
  28638. engine.setDepthWrite(true);
  28639. };
  28640. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  28641. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28642. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28643. return;
  28644. }
  28645. var engine = this._scene.getEngine();
  28646. for (var index = 0, len = postProcesses.length; index < len; index++) {
  28647. if (index < len - 1) {
  28648. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28649. }
  28650. else {
  28651. if (targetTexture) {
  28652. engine.bindFramebuffer(targetTexture, faceIndex);
  28653. }
  28654. else {
  28655. engine.restoreDefaultFramebuffer();
  28656. }
  28657. }
  28658. if (doNotPresent) {
  28659. break;
  28660. }
  28661. var pp = postProcesses[index];
  28662. var effect = pp.apply();
  28663. if (effect) {
  28664. pp.onBeforeRenderObservable.notifyObservers(effect);
  28665. // VBOs
  28666. this._prepareBuffers();
  28667. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28668. // Draw order
  28669. engine.draw(true, 0, 6);
  28670. pp.onAfterRenderObservable.notifyObservers(effect);
  28671. }
  28672. }
  28673. // Restore depth buffer
  28674. engine.setDepthBuffer(true);
  28675. engine.setDepthWrite(true);
  28676. };
  28677. PostProcessManager.prototype.dispose = function () {
  28678. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28679. if (buffer) {
  28680. buffer.dispose();
  28681. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28682. }
  28683. if (this._indexBuffer) {
  28684. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28685. this._indexBuffer = null;
  28686. }
  28687. };
  28688. return PostProcessManager;
  28689. }());
  28690. BABYLON.PostProcessManager = PostProcessManager;
  28691. })(BABYLON || (BABYLON = {}));
  28692. var BABYLON;
  28693. (function (BABYLON) {
  28694. var PassPostProcess = (function (_super) {
  28695. __extends(PassPostProcess, _super);
  28696. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  28697. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  28698. }
  28699. return PassPostProcess;
  28700. }(BABYLON.PostProcess));
  28701. BABYLON.PassPostProcess = PassPostProcess;
  28702. })(BABYLON || (BABYLON = {}));
  28703. var BABYLON;
  28704. (function (BABYLON) {
  28705. /**
  28706. * This is a holder class for the physics joint created by the physics plugin.
  28707. * It holds a set of functions to control the underlying joint.
  28708. */
  28709. var PhysicsJoint = (function () {
  28710. function PhysicsJoint(type, jointData) {
  28711. this.type = type;
  28712. this.jointData = jointData;
  28713. jointData.nativeParams = jointData.nativeParams || {};
  28714. }
  28715. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  28716. get: function () {
  28717. return this._physicsJoint;
  28718. },
  28719. set: function (newJoint) {
  28720. if (this._physicsJoint) {
  28721. }
  28722. this._physicsJoint = newJoint;
  28723. },
  28724. enumerable: true,
  28725. configurable: true
  28726. });
  28727. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  28728. set: function (physicsPlugin) {
  28729. this._physicsPlugin = physicsPlugin;
  28730. },
  28731. enumerable: true,
  28732. configurable: true
  28733. });
  28734. /**
  28735. * Execute a function that is physics-plugin specific.
  28736. * @param {Function} func the function that will be executed.
  28737. * It accepts two parameters: the physics world and the physics joint.
  28738. */
  28739. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  28740. func(this._physicsPlugin.world, this._physicsJoint);
  28741. };
  28742. //TODO check if the native joints are the same
  28743. //Joint Types
  28744. PhysicsJoint.DistanceJoint = 0;
  28745. PhysicsJoint.HingeJoint = 1;
  28746. PhysicsJoint.BallAndSocketJoint = 2;
  28747. PhysicsJoint.WheelJoint = 3;
  28748. PhysicsJoint.SliderJoint = 4;
  28749. //OIMO
  28750. PhysicsJoint.PrismaticJoint = 5;
  28751. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  28752. PhysicsJoint.UniversalJoint = 6;
  28753. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  28754. //Cannon
  28755. //Similar to a Ball-Joint. Different in params
  28756. PhysicsJoint.PointToPointJoint = 8;
  28757. //Cannon only at the moment
  28758. PhysicsJoint.SpringJoint = 9;
  28759. PhysicsJoint.LockJoint = 10;
  28760. return PhysicsJoint;
  28761. }());
  28762. BABYLON.PhysicsJoint = PhysicsJoint;
  28763. /**
  28764. * A class representing a physics distance joint.
  28765. */
  28766. var DistanceJoint = (function (_super) {
  28767. __extends(DistanceJoint, _super);
  28768. function DistanceJoint(jointData) {
  28769. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  28770. }
  28771. /**
  28772. * Update the predefined distance.
  28773. */
  28774. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  28775. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  28776. };
  28777. return DistanceJoint;
  28778. }(PhysicsJoint));
  28779. BABYLON.DistanceJoint = DistanceJoint;
  28780. var MotorEnabledJoint = (function (_super) {
  28781. __extends(MotorEnabledJoint, _super);
  28782. function MotorEnabledJoint(type, jointData) {
  28783. _super.call(this, type, jointData);
  28784. }
  28785. /**
  28786. * Set the motor values.
  28787. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28788. * @param {number} force the force to apply
  28789. * @param {number} maxForce max force for this motor.
  28790. */
  28791. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  28792. this._physicsPlugin.setMotor(this, force, maxForce);
  28793. };
  28794. /**
  28795. * Set the motor's limits.
  28796. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28797. */
  28798. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  28799. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  28800. };
  28801. return MotorEnabledJoint;
  28802. }(PhysicsJoint));
  28803. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  28804. /**
  28805. * This class represents a single hinge physics joint
  28806. */
  28807. var HingeJoint = (function (_super) {
  28808. __extends(HingeJoint, _super);
  28809. function HingeJoint(jointData) {
  28810. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  28811. }
  28812. /**
  28813. * Set the motor values.
  28814. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28815. * @param {number} force the force to apply
  28816. * @param {number} maxForce max force for this motor.
  28817. */
  28818. HingeJoint.prototype.setMotor = function (force, maxForce) {
  28819. this._physicsPlugin.setMotor(this, force, maxForce);
  28820. };
  28821. /**
  28822. * Set the motor's limits.
  28823. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28824. */
  28825. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  28826. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  28827. };
  28828. return HingeJoint;
  28829. }(MotorEnabledJoint));
  28830. BABYLON.HingeJoint = HingeJoint;
  28831. /**
  28832. * This class represents a dual hinge physics joint (same as wheel joint)
  28833. */
  28834. var Hinge2Joint = (function (_super) {
  28835. __extends(Hinge2Joint, _super);
  28836. function Hinge2Joint(jointData) {
  28837. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  28838. }
  28839. /**
  28840. * Set the motor values.
  28841. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28842. * @param {number} force the force to apply
  28843. * @param {number} maxForce max force for this motor.
  28844. * @param {motorIndex} the motor's index, 0 or 1.
  28845. */
  28846. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  28847. if (motorIndex === void 0) { motorIndex = 0; }
  28848. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  28849. };
  28850. /**
  28851. * Set the motor limits.
  28852. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28853. * @param {number} upperLimit the upper limit
  28854. * @param {number} lowerLimit lower limit
  28855. * @param {motorIndex} the motor's index, 0 or 1.
  28856. */
  28857. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  28858. if (motorIndex === void 0) { motorIndex = 0; }
  28859. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  28860. };
  28861. return Hinge2Joint;
  28862. }(MotorEnabledJoint));
  28863. BABYLON.Hinge2Joint = Hinge2Joint;
  28864. })(BABYLON || (BABYLON = {}));
  28865. var BABYLON;
  28866. (function (BABYLON) {
  28867. var PhysicsImpostor = (function () {
  28868. function PhysicsImpostor(object, type, _options, _scene) {
  28869. var _this = this;
  28870. if (_options === void 0) { _options = { mass: 0 }; }
  28871. this.object = object;
  28872. this.type = type;
  28873. this._options = _options;
  28874. this._scene = _scene;
  28875. this._bodyUpdateRequired = false;
  28876. this._onBeforePhysicsStepCallbacks = new Array();
  28877. this._onAfterPhysicsStepCallbacks = new Array();
  28878. this._onPhysicsCollideCallbacks = [];
  28879. this._deltaPosition = BABYLON.Vector3.Zero();
  28880. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  28881. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  28882. /**
  28883. * this function is executed by the physics engine.
  28884. */
  28885. this.beforeStep = function () {
  28886. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  28887. //conjugate deltaRotation
  28888. if (_this._deltaRotationConjugated) {
  28889. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  28890. }
  28891. else {
  28892. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  28893. }
  28894. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  28895. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  28896. func(_this);
  28897. });
  28898. };
  28899. /**
  28900. * this function is executed by the physics engine.
  28901. */
  28902. this.afterStep = function () {
  28903. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  28904. func(_this);
  28905. });
  28906. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  28907. _this.object.position.addInPlace(_this._deltaPosition);
  28908. if (_this._deltaRotation) {
  28909. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  28910. }
  28911. };
  28912. //event and body object due to cannon's event-based architecture.
  28913. this.onCollide = function (e) {
  28914. if (!_this._onPhysicsCollideCallbacks.length)
  28915. return;
  28916. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  28917. if (otherImpostor) {
  28918. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  28919. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  28920. }).forEach(function (obj) {
  28921. obj.callback(_this, otherImpostor);
  28922. });
  28923. }
  28924. };
  28925. //sanity check!
  28926. if (!this.object) {
  28927. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  28928. return;
  28929. }
  28930. //legacy support for old syntax.
  28931. if (!this._scene && object.getScene) {
  28932. this._scene = object.getScene();
  28933. }
  28934. this._physicsEngine = this._scene.getPhysicsEngine();
  28935. if (!this._physicsEngine) {
  28936. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  28937. }
  28938. else {
  28939. //set the object's quaternion, if not set
  28940. if (!this.object.rotationQuaternion) {
  28941. if (this.object.rotation) {
  28942. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  28943. }
  28944. else {
  28945. this.object.rotationQuaternion = new BABYLON.Quaternion();
  28946. }
  28947. }
  28948. //default options params
  28949. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  28950. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  28951. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  28952. this._joints = [];
  28953. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  28954. if (!this.object.parent) {
  28955. this._init();
  28956. }
  28957. }
  28958. }
  28959. /**
  28960. * This function will completly initialize this impostor.
  28961. * It will create a new body - but only if this mesh has no parent.
  28962. * If it has, this impostor will not be used other than to define the impostor
  28963. * of the child mesh.
  28964. */
  28965. PhysicsImpostor.prototype._init = function () {
  28966. this._physicsEngine.removeImpostor(this);
  28967. this.physicsBody = null;
  28968. this._parent = this._parent || this._getPhysicsParent();
  28969. if (!this.parent) {
  28970. this._physicsEngine.addImpostor(this);
  28971. }
  28972. };
  28973. PhysicsImpostor.prototype._getPhysicsParent = function () {
  28974. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  28975. var parentMesh = this.object.parent;
  28976. return parentMesh.physicsImpostor;
  28977. }
  28978. return;
  28979. };
  28980. /**
  28981. * Should a new body be generated.
  28982. */
  28983. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  28984. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  28985. };
  28986. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  28987. this.forceUpdate();
  28988. };
  28989. /**
  28990. * Force a regeneration of this or the parent's impostor's body.
  28991. * Use under cautious - This will remove all joints already implemented.
  28992. */
  28993. PhysicsImpostor.prototype.forceUpdate = function () {
  28994. this._init();
  28995. if (this.parent) {
  28996. this.parent.forceUpdate();
  28997. }
  28998. };
  28999. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  29000. /*public get mesh(): AbstractMesh {
  29001. return this._mesh;
  29002. }*/
  29003. /**
  29004. * Gets the body that holds this impostor. Either its own, or its parent.
  29005. */
  29006. get: function () {
  29007. return this._parent ? this._parent.physicsBody : this._physicsBody;
  29008. },
  29009. /**
  29010. * Set the physics body. Used mainly by the physics engine/plugin
  29011. */
  29012. set: function (physicsBody) {
  29013. if (this._physicsBody) {
  29014. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  29015. }
  29016. this._physicsBody = physicsBody;
  29017. this.resetUpdateFlags();
  29018. },
  29019. enumerable: true,
  29020. configurable: true
  29021. });
  29022. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  29023. get: function () {
  29024. return this._parent;
  29025. },
  29026. enumerable: true,
  29027. configurable: true
  29028. });
  29029. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  29030. this._bodyUpdateRequired = false;
  29031. };
  29032. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  29033. if (this.object.getBoundingInfo) {
  29034. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  29035. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  29036. }
  29037. else {
  29038. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  29039. }
  29040. };
  29041. PhysicsImpostor.prototype.getObjectCenter = function () {
  29042. if (this.object.getBoundingInfo) {
  29043. return this.object.getBoundingInfo().boundingBox.center;
  29044. }
  29045. else {
  29046. return this.object.position;
  29047. }
  29048. };
  29049. /**
  29050. * Get a specific parametes from the options parameter.
  29051. */
  29052. PhysicsImpostor.prototype.getParam = function (paramName) {
  29053. return this._options[paramName];
  29054. };
  29055. /**
  29056. * Sets a specific parameter in the options given to the physics plugin
  29057. */
  29058. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  29059. this._options[paramName] = value;
  29060. this._bodyUpdateRequired = true;
  29061. };
  29062. /**
  29063. * Specifically change the body's mass option. Won't recreate the physics body object
  29064. */
  29065. PhysicsImpostor.prototype.setMass = function (mass) {
  29066. if (this.getParam("mass") !== mass) {
  29067. this.setParam("mass", mass);
  29068. }
  29069. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  29070. };
  29071. PhysicsImpostor.prototype.getLinearVelocity = function () {
  29072. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  29073. };
  29074. /**
  29075. * Set the body's linear velocity.
  29076. */
  29077. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  29078. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  29079. };
  29080. PhysicsImpostor.prototype.getAngularVelocity = function () {
  29081. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  29082. };
  29083. /**
  29084. * Set the body's linear velocity.
  29085. */
  29086. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  29087. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  29088. };
  29089. /**
  29090. * Execute a function with the physics plugin native code.
  29091. * Provide a function the will have two variables - the world object and the physics body object.
  29092. */
  29093. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  29094. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  29095. };
  29096. /**
  29097. * Register a function that will be executed before the physics world is stepping forward.
  29098. */
  29099. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  29100. this._onBeforePhysicsStepCallbacks.push(func);
  29101. };
  29102. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  29103. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  29104. if (index > -1) {
  29105. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  29106. }
  29107. else {
  29108. BABYLON.Tools.Warn("Function to remove was not found");
  29109. }
  29110. };
  29111. /**
  29112. * Register a function that will be executed after the physics step
  29113. */
  29114. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  29115. this._onAfterPhysicsStepCallbacks.push(func);
  29116. };
  29117. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  29118. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  29119. if (index > -1) {
  29120. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  29121. }
  29122. else {
  29123. BABYLON.Tools.Warn("Function to remove was not found");
  29124. }
  29125. };
  29126. /**
  29127. * register a function that will be executed when this impostor collides against a different body.
  29128. */
  29129. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  29130. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  29131. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  29132. };
  29133. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  29134. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  29135. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  29136. if (index > -1) {
  29137. this._onPhysicsCollideCallbacks.splice(index, 1);
  29138. }
  29139. else {
  29140. BABYLON.Tools.Warn("Function to remove was not found");
  29141. }
  29142. };
  29143. /**
  29144. * Apply a force
  29145. */
  29146. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  29147. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  29148. };
  29149. /**
  29150. * Apply an impulse
  29151. */
  29152. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  29153. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  29154. };
  29155. /**
  29156. * A help function to create a joint.
  29157. */
  29158. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  29159. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  29160. this.addJoint(otherImpostor, joint);
  29161. };
  29162. /**
  29163. * Add a joint to this impostor with a different impostor.
  29164. */
  29165. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  29166. this._joints.push({
  29167. otherImpostor: otherImpostor,
  29168. joint: joint
  29169. });
  29170. this._physicsEngine.addJoint(this, otherImpostor, joint);
  29171. };
  29172. /**
  29173. * Will keep this body still, in a sleep mode.
  29174. */
  29175. PhysicsImpostor.prototype.sleep = function () {
  29176. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  29177. };
  29178. /**
  29179. * Wake the body up.
  29180. */
  29181. PhysicsImpostor.prototype.wakeUp = function () {
  29182. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  29183. };
  29184. PhysicsImpostor.prototype.clone = function (newObject) {
  29185. if (!newObject)
  29186. return null;
  29187. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  29188. };
  29189. PhysicsImpostor.prototype.dispose = function () {
  29190. var _this = this;
  29191. //no dispose if no physics engine is available.
  29192. if (!this._physicsEngine) {
  29193. return;
  29194. }
  29195. this._joints.forEach(function (j) {
  29196. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  29197. });
  29198. //dispose the physics body
  29199. this._physicsEngine.removeImpostor(this);
  29200. if (this.parent) {
  29201. this.parent.forceUpdate();
  29202. }
  29203. else {
  29204. }
  29205. };
  29206. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  29207. this._deltaPosition.copyFrom(position);
  29208. };
  29209. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  29210. if (!this._deltaRotation) {
  29211. this._deltaRotation = new BABYLON.Quaternion();
  29212. }
  29213. this._deltaRotation.copyFrom(rotation);
  29214. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  29215. };
  29216. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  29217. //Impostor types
  29218. PhysicsImpostor.NoImpostor = 0;
  29219. PhysicsImpostor.SphereImpostor = 1;
  29220. PhysicsImpostor.BoxImpostor = 2;
  29221. PhysicsImpostor.PlaneImpostor = 3;
  29222. PhysicsImpostor.MeshImpostor = 4;
  29223. PhysicsImpostor.CylinderImpostor = 7;
  29224. PhysicsImpostor.ParticleImpostor = 8;
  29225. PhysicsImpostor.HeightmapImpostor = 9;
  29226. return PhysicsImpostor;
  29227. }());
  29228. BABYLON.PhysicsImpostor = PhysicsImpostor;
  29229. })(BABYLON || (BABYLON = {}));
  29230. var BABYLON;
  29231. (function (BABYLON) {
  29232. var PhysicsEngine = (function () {
  29233. function PhysicsEngine(gravity, _physicsPlugin) {
  29234. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  29235. this._physicsPlugin = _physicsPlugin;
  29236. //new methods and parameters
  29237. this._impostors = [];
  29238. this._joints = [];
  29239. if (!this._physicsPlugin.isSupported()) {
  29240. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  29241. + "Please make sure it is included.");
  29242. }
  29243. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  29244. this.setGravity(gravity);
  29245. this.setTimeStep();
  29246. }
  29247. PhysicsEngine.prototype.setGravity = function (gravity) {
  29248. this.gravity = gravity;
  29249. this._physicsPlugin.setGravity(this.gravity);
  29250. };
  29251. /**
  29252. * Set the time step of the physics engine.
  29253. * default is 1/60.
  29254. * To slow it down, enter 1/600 for example.
  29255. * To speed it up, 1/30
  29256. * @param {number} newTimeStep the new timestep to apply to this world.
  29257. */
  29258. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  29259. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  29260. this._physicsPlugin.setTimeStep(newTimeStep);
  29261. };
  29262. PhysicsEngine.prototype.dispose = function () {
  29263. this._impostors.forEach(function (impostor) {
  29264. impostor.dispose();
  29265. });
  29266. this._physicsPlugin.dispose();
  29267. };
  29268. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  29269. return this._physicsPlugin.name;
  29270. };
  29271. /**
  29272. * Adding a new impostor for the impostor tracking.
  29273. * This will be done by the impostor itself.
  29274. * @param {PhysicsImpostor} impostor the impostor to add
  29275. */
  29276. PhysicsEngine.prototype.addImpostor = function (impostor) {
  29277. impostor.uniqueId = this._impostors.push(impostor);
  29278. //if no parent, generate the body
  29279. if (!impostor.parent) {
  29280. this._physicsPlugin.generatePhysicsBody(impostor);
  29281. }
  29282. };
  29283. /**
  29284. * Remove an impostor from the engine.
  29285. * This impostor and its mesh will not longer be updated by the physics engine.
  29286. * @param {PhysicsImpostor} impostor the impostor to remove
  29287. */
  29288. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  29289. var index = this._impostors.indexOf(impostor);
  29290. if (index > -1) {
  29291. var removed = this._impostors.splice(index, 1);
  29292. //Is it needed?
  29293. if (removed.length) {
  29294. //this will also remove it from the world.
  29295. removed[0].physicsBody = null;
  29296. }
  29297. }
  29298. };
  29299. /**
  29300. * Add a joint to the physics engine
  29301. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  29302. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  29303. * @param {PhysicsJoint} the joint that will connect both impostors.
  29304. */
  29305. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  29306. var impostorJoint = {
  29307. mainImpostor: mainImpostor,
  29308. connectedImpostor: connectedImpostor,
  29309. joint: joint
  29310. };
  29311. joint.physicsPlugin = this._physicsPlugin;
  29312. this._joints.push(impostorJoint);
  29313. this._physicsPlugin.generateJoint(impostorJoint);
  29314. };
  29315. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  29316. var matchingJoints = this._joints.filter(function (impostorJoint) {
  29317. return (impostorJoint.connectedImpostor === connectedImpostor
  29318. && impostorJoint.joint === joint
  29319. && impostorJoint.mainImpostor === mainImpostor);
  29320. });
  29321. if (matchingJoints.length) {
  29322. this._physicsPlugin.removeJoint(matchingJoints[0]);
  29323. }
  29324. };
  29325. /**
  29326. * Called by the scene. no need to call it.
  29327. */
  29328. PhysicsEngine.prototype._step = function (delta) {
  29329. var _this = this;
  29330. //check if any mesh has no body / requires an update
  29331. this._impostors.forEach(function (impostor) {
  29332. if (impostor.isBodyInitRequired()) {
  29333. _this._physicsPlugin.generatePhysicsBody(impostor);
  29334. }
  29335. });
  29336. if (delta > 0.1) {
  29337. delta = 0.1;
  29338. }
  29339. else if (delta <= 0) {
  29340. delta = 1.0 / 60.0;
  29341. }
  29342. this._physicsPlugin.executeStep(delta, this._impostors);
  29343. };
  29344. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  29345. return this._physicsPlugin;
  29346. };
  29347. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  29348. for (var i = 0; i < this._impostors.length; ++i) {
  29349. if (this._impostors[i].object === object) {
  29350. return this._impostors[i];
  29351. }
  29352. }
  29353. };
  29354. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  29355. for (var i = 0; i < this._impostors.length; ++i) {
  29356. if (this._impostors[i].physicsBody === body) {
  29357. return this._impostors[i];
  29358. }
  29359. }
  29360. };
  29361. // Statics, Legacy support.
  29362. /**
  29363. * @Deprecated
  29364. *
  29365. */
  29366. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  29367. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  29368. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  29369. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  29370. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  29371. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  29372. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  29373. PhysicsEngine.CapsuleImpostor = -1;
  29374. PhysicsEngine.ConeImpostor = -1;
  29375. PhysicsEngine.ConvexHullImpostor = -1;
  29376. PhysicsEngine.Epsilon = 0.001;
  29377. return PhysicsEngine;
  29378. }());
  29379. BABYLON.PhysicsEngine = PhysicsEngine;
  29380. })(BABYLON || (BABYLON = {}));
  29381. var BABYLON;
  29382. (function (BABYLON) {
  29383. var VertexData = (function () {
  29384. function VertexData() {
  29385. }
  29386. VertexData.prototype.set = function (data, kind) {
  29387. switch (kind) {
  29388. case BABYLON.VertexBuffer.PositionKind:
  29389. this.positions = data;
  29390. break;
  29391. case BABYLON.VertexBuffer.NormalKind:
  29392. this.normals = data;
  29393. break;
  29394. case BABYLON.VertexBuffer.UVKind:
  29395. this.uvs = data;
  29396. break;
  29397. case BABYLON.VertexBuffer.UV2Kind:
  29398. this.uvs2 = data;
  29399. break;
  29400. case BABYLON.VertexBuffer.UV3Kind:
  29401. this.uvs3 = data;
  29402. break;
  29403. case BABYLON.VertexBuffer.UV4Kind:
  29404. this.uvs4 = data;
  29405. break;
  29406. case BABYLON.VertexBuffer.UV5Kind:
  29407. this.uvs5 = data;
  29408. break;
  29409. case BABYLON.VertexBuffer.UV6Kind:
  29410. this.uvs6 = data;
  29411. break;
  29412. case BABYLON.VertexBuffer.ColorKind:
  29413. this.colors = data;
  29414. break;
  29415. case BABYLON.VertexBuffer.MatricesIndicesKind:
  29416. this.matricesIndices = data;
  29417. break;
  29418. case BABYLON.VertexBuffer.MatricesWeightsKind:
  29419. this.matricesWeights = data;
  29420. break;
  29421. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  29422. this.matricesIndicesExtra = data;
  29423. break;
  29424. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  29425. this.matricesWeightsExtra = data;
  29426. break;
  29427. }
  29428. };
  29429. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  29430. this._applyTo(mesh, updatable);
  29431. };
  29432. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  29433. this._applyTo(geometry, updatable);
  29434. };
  29435. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  29436. this._update(mesh);
  29437. };
  29438. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  29439. this._update(geometry);
  29440. };
  29441. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  29442. if (this.positions) {
  29443. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  29444. }
  29445. if (this.normals) {
  29446. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  29447. }
  29448. if (this.uvs) {
  29449. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  29450. }
  29451. if (this.uvs2) {
  29452. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  29453. }
  29454. if (this.uvs3) {
  29455. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  29456. }
  29457. if (this.uvs4) {
  29458. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  29459. }
  29460. if (this.uvs5) {
  29461. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  29462. }
  29463. if (this.uvs6) {
  29464. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  29465. }
  29466. if (this.colors) {
  29467. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  29468. }
  29469. if (this.matricesIndices) {
  29470. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  29471. }
  29472. if (this.matricesWeights) {
  29473. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  29474. }
  29475. if (this.matricesIndicesExtra) {
  29476. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  29477. }
  29478. if (this.matricesWeightsExtra) {
  29479. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  29480. }
  29481. if (this.indices) {
  29482. meshOrGeometry.setIndices(this.indices);
  29483. }
  29484. };
  29485. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  29486. if (this.positions) {
  29487. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  29488. }
  29489. if (this.normals) {
  29490. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  29491. }
  29492. if (this.uvs) {
  29493. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  29494. }
  29495. if (this.uvs2) {
  29496. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  29497. }
  29498. if (this.uvs3) {
  29499. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  29500. }
  29501. if (this.uvs4) {
  29502. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  29503. }
  29504. if (this.uvs5) {
  29505. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  29506. }
  29507. if (this.uvs6) {
  29508. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  29509. }
  29510. if (this.colors) {
  29511. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  29512. }
  29513. if (this.matricesIndices) {
  29514. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  29515. }
  29516. if (this.matricesWeights) {
  29517. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  29518. }
  29519. if (this.matricesIndicesExtra) {
  29520. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  29521. }
  29522. if (this.matricesWeightsExtra) {
  29523. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  29524. }
  29525. if (this.indices) {
  29526. meshOrGeometry.setIndices(this.indices);
  29527. }
  29528. };
  29529. VertexData.prototype.transform = function (matrix) {
  29530. var transformed = BABYLON.Vector3.Zero();
  29531. var index;
  29532. if (this.positions) {
  29533. var position = BABYLON.Vector3.Zero();
  29534. for (index = 0; index < this.positions.length; index += 3) {
  29535. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  29536. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  29537. this.positions[index] = transformed.x;
  29538. this.positions[index + 1] = transformed.y;
  29539. this.positions[index + 2] = transformed.z;
  29540. }
  29541. }
  29542. if (this.normals) {
  29543. var normal = BABYLON.Vector3.Zero();
  29544. for (index = 0; index < this.normals.length; index += 3) {
  29545. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  29546. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  29547. this.normals[index] = transformed.x;
  29548. this.normals[index + 1] = transformed.y;
  29549. this.normals[index + 2] = transformed.z;
  29550. }
  29551. }
  29552. };
  29553. VertexData.prototype.merge = function (other) {
  29554. if (other.indices) {
  29555. if (!this.indices) {
  29556. this.indices = [];
  29557. }
  29558. var offset = this.positions ? this.positions.length / 3 : 0;
  29559. for (var index = 0; index < other.indices.length; index++) {
  29560. //TODO check type - if Int32Array!
  29561. this.indices.push(other.indices[index] + offset);
  29562. }
  29563. }
  29564. this.positions = this._mergeElement(this.positions, other.positions);
  29565. this.normals = this._mergeElement(this.normals, other.normals);
  29566. this.uvs = this._mergeElement(this.uvs, other.uvs);
  29567. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  29568. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  29569. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  29570. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  29571. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  29572. this.colors = this._mergeElement(this.colors, other.colors);
  29573. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  29574. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  29575. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  29576. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  29577. };
  29578. VertexData.prototype._mergeElement = function (source, other) {
  29579. if (!other)
  29580. return source;
  29581. if (!source)
  29582. return other;
  29583. var len = other.length + source.length;
  29584. var isSrcTypedArray = source instanceof Float32Array;
  29585. var isOthTypedArray = other instanceof Float32Array;
  29586. // use non-loop method when the source is Float32Array
  29587. if (isSrcTypedArray) {
  29588. var ret32 = new Float32Array(len);
  29589. ret32.set(source);
  29590. ret32.set(other, source.length);
  29591. return ret32;
  29592. }
  29593. else if (!isOthTypedArray) {
  29594. return source.concat(other);
  29595. }
  29596. else {
  29597. var ret = source.slice(0); // copy source to a separate array
  29598. for (var i = 0, len = other.length; i < len; i++) {
  29599. ret.push(other[i]);
  29600. }
  29601. return ret;
  29602. }
  29603. };
  29604. VertexData.prototype.serialize = function () {
  29605. var serializationObject = this.serialize();
  29606. if (this.positions) {
  29607. serializationObject.positions = this.positions;
  29608. }
  29609. if (this.normals) {
  29610. serializationObject.normals = this.normals;
  29611. }
  29612. if (this.uvs) {
  29613. serializationObject.uvs = this.uvs;
  29614. }
  29615. if (this.uvs2) {
  29616. serializationObject.uvs2 = this.uvs2;
  29617. }
  29618. if (this.uvs3) {
  29619. serializationObject.uvs3 = this.uvs3;
  29620. }
  29621. if (this.uvs4) {
  29622. serializationObject.uvs4 = this.uvs4;
  29623. }
  29624. if (this.uvs5) {
  29625. serializationObject.uvs5 = this.uvs5;
  29626. }
  29627. if (this.uvs6) {
  29628. serializationObject.uvs6 = this.uvs6;
  29629. }
  29630. if (this.colors) {
  29631. serializationObject.colors = this.colors;
  29632. }
  29633. if (this.matricesIndices) {
  29634. serializationObject.matricesIndices = this.matricesIndices;
  29635. serializationObject.matricesIndices._isExpanded = true;
  29636. }
  29637. if (this.matricesWeights) {
  29638. serializationObject.matricesWeights = this.matricesWeights;
  29639. }
  29640. if (this.matricesIndicesExtra) {
  29641. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  29642. serializationObject.matricesIndicesExtra._isExpanded = true;
  29643. }
  29644. if (this.matricesWeightsExtra) {
  29645. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  29646. }
  29647. serializationObject.indices = this.indices;
  29648. return serializationObject;
  29649. };
  29650. // Statics
  29651. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  29652. return VertexData._ExtractFrom(mesh, copyWhenShared);
  29653. };
  29654. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  29655. return VertexData._ExtractFrom(geometry, copyWhenShared);
  29656. };
  29657. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  29658. var result = new VertexData();
  29659. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29660. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  29661. }
  29662. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29663. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  29664. }
  29665. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29666. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  29667. }
  29668. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29669. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  29670. }
  29671. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29672. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  29673. }
  29674. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29675. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  29676. }
  29677. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29678. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  29679. }
  29680. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29681. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  29682. }
  29683. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29684. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  29685. }
  29686. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29687. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  29688. }
  29689. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29690. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  29691. }
  29692. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29693. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  29694. }
  29695. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29696. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  29697. }
  29698. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29699. return result;
  29700. };
  29701. VertexData.CreateRibbon = function (options) {
  29702. var pathArray = options.pathArray;
  29703. var closeArray = options.closeArray || false;
  29704. var closePath = options.closePath || false;
  29705. var invertUV = options.invertUV || false;
  29706. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29707. var offset = options.offset || defaultOffset;
  29708. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29709. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29710. var positions = [];
  29711. var indices = [];
  29712. var normals = [];
  29713. var uvs = [];
  29714. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29715. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29716. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29717. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29718. var minlg; // minimal length among all paths from pathArray
  29719. var lg = []; // array of path lengths : nb of vertex per path
  29720. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29721. var p; // path iterator
  29722. var i; // point iterator
  29723. var j; // point iterator
  29724. // if single path in pathArray
  29725. if (pathArray.length < 2) {
  29726. var ar1 = [];
  29727. var ar2 = [];
  29728. for (i = 0; i < pathArray[0].length - offset; i++) {
  29729. ar1.push(pathArray[0][i]);
  29730. ar2.push(pathArray[0][i + offset]);
  29731. }
  29732. pathArray = [ar1, ar2];
  29733. }
  29734. // positions and horizontal distances (u)
  29735. var idc = 0;
  29736. var closePathCorr = (closePath) ? 1 : 0;
  29737. var path;
  29738. var l;
  29739. minlg = pathArray[0].length;
  29740. var vectlg;
  29741. var dist;
  29742. for (p = 0; p < pathArray.length; p++) {
  29743. uTotalDistance[p] = 0;
  29744. us[p] = [0];
  29745. path = pathArray[p];
  29746. l = path.length;
  29747. minlg = (minlg < l) ? minlg : l;
  29748. j = 0;
  29749. while (j < l) {
  29750. positions.push(path[j].x, path[j].y, path[j].z);
  29751. if (j > 0) {
  29752. vectlg = path[j].subtract(path[j - 1]).length();
  29753. dist = vectlg + uTotalDistance[p];
  29754. us[p].push(dist);
  29755. uTotalDistance[p] = dist;
  29756. }
  29757. j++;
  29758. }
  29759. if (closePath) {
  29760. j--;
  29761. positions.push(path[0].x, path[0].y, path[0].z);
  29762. vectlg = path[j].subtract(path[0]).length();
  29763. dist = vectlg + uTotalDistance[p];
  29764. us[p].push(dist);
  29765. uTotalDistance[p] = dist;
  29766. }
  29767. lg[p] = l + closePathCorr;
  29768. idx[p] = idc;
  29769. idc += (l + closePathCorr);
  29770. }
  29771. // vertical distances (v)
  29772. var path1;
  29773. var path2;
  29774. var vertex1;
  29775. var vertex2;
  29776. for (i = 0; i < minlg + closePathCorr; i++) {
  29777. vTotalDistance[i] = 0;
  29778. vs[i] = [0];
  29779. for (p = 0; p < pathArray.length - 1; p++) {
  29780. path1 = pathArray[p];
  29781. path2 = pathArray[p + 1];
  29782. if (i === minlg) {
  29783. vertex1 = path1[0];
  29784. vertex2 = path2[0];
  29785. }
  29786. else {
  29787. vertex1 = path1[i];
  29788. vertex2 = path2[i];
  29789. }
  29790. vectlg = vertex2.subtract(vertex1).length();
  29791. dist = vectlg + vTotalDistance[i];
  29792. vs[i].push(dist);
  29793. vTotalDistance[i] = dist;
  29794. }
  29795. if (closeArray) {
  29796. path1 = pathArray[p];
  29797. path2 = pathArray[0];
  29798. if (i === minlg) {
  29799. vertex2 = path2[0];
  29800. }
  29801. vectlg = vertex2.subtract(vertex1).length();
  29802. dist = vectlg + vTotalDistance[i];
  29803. vTotalDistance[i] = dist;
  29804. }
  29805. }
  29806. // uvs
  29807. var u;
  29808. var v;
  29809. for (p = 0; p < pathArray.length; p++) {
  29810. for (i = 0; i < minlg + closePathCorr; i++) {
  29811. u = us[p][i] / uTotalDistance[p];
  29812. v = vs[i][p] / vTotalDistance[i];
  29813. if (invertUV) {
  29814. uvs.push(v, u);
  29815. }
  29816. else {
  29817. uvs.push(u, v);
  29818. }
  29819. }
  29820. }
  29821. // indices
  29822. p = 0; // path index
  29823. var pi = 0; // positions array index
  29824. var l1 = lg[p] - 1; // path1 length
  29825. var l2 = lg[p + 1] - 1; // path2 length
  29826. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29827. var shft = idx[1] - idx[0]; // shift
  29828. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29829. while (pi <= min && p < path1nb) {
  29830. // 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
  29831. indices.push(pi, pi + shft, pi + 1);
  29832. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29833. pi += 1;
  29834. if (pi === min) {
  29835. p++;
  29836. if (p === lg.length - 1) {
  29837. shft = idx[0] - idx[p];
  29838. l1 = lg[p] - 1;
  29839. l2 = lg[0] - 1;
  29840. }
  29841. else {
  29842. shft = idx[p + 1] - idx[p];
  29843. l1 = lg[p] - 1;
  29844. l2 = lg[p + 1] - 1;
  29845. }
  29846. pi = idx[p];
  29847. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29848. }
  29849. }
  29850. // normals
  29851. VertexData.ComputeNormals(positions, indices, normals);
  29852. if (closePath) {
  29853. var indexFirst = 0;
  29854. var indexLast = 0;
  29855. for (p = 0; p < pathArray.length; p++) {
  29856. indexFirst = idx[p] * 3;
  29857. if (p + 1 < pathArray.length) {
  29858. indexLast = (idx[p + 1] - 1) * 3;
  29859. }
  29860. else {
  29861. indexLast = normals.length - 3;
  29862. }
  29863. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29864. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29865. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29866. normals[indexLast] = normals[indexFirst];
  29867. normals[indexLast + 1] = normals[indexFirst + 1];
  29868. normals[indexLast + 2] = normals[indexFirst + 2];
  29869. }
  29870. }
  29871. // sides
  29872. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29873. // Result
  29874. var vertexData = new VertexData();
  29875. vertexData.indices = indices;
  29876. vertexData.positions = positions;
  29877. vertexData.normals = normals;
  29878. vertexData.uvs = uvs;
  29879. if (closePath) {
  29880. vertexData._idx = idx;
  29881. }
  29882. return vertexData;
  29883. };
  29884. VertexData.CreateBox = function (options) {
  29885. var normalsSource = [
  29886. new BABYLON.Vector3(0, 0, 1),
  29887. new BABYLON.Vector3(0, 0, -1),
  29888. new BABYLON.Vector3(1, 0, 0),
  29889. new BABYLON.Vector3(-1, 0, 0),
  29890. new BABYLON.Vector3(0, 1, 0),
  29891. new BABYLON.Vector3(0, -1, 0)
  29892. ];
  29893. var indices = [];
  29894. var positions = [];
  29895. var normals = [];
  29896. var uvs = [];
  29897. var width = options.width || options.size || 1;
  29898. var height = options.height || options.size || 1;
  29899. var depth = options.depth || options.size || 1;
  29900. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29901. var faceUV = options.faceUV || new Array(6);
  29902. var faceColors = options.faceColors;
  29903. var colors = [];
  29904. // default face colors and UV if undefined
  29905. for (var f = 0; f < 6; f++) {
  29906. if (faceUV[f] === undefined) {
  29907. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29908. }
  29909. if (faceColors && faceColors[f] === undefined) {
  29910. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29911. }
  29912. }
  29913. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  29914. // Create each face in turn.
  29915. for (var index = 0; index < normalsSource.length; index++) {
  29916. var normal = normalsSource[index];
  29917. // Get two vectors perpendicular to the face normal and to each other.
  29918. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  29919. var side2 = BABYLON.Vector3.Cross(normal, side1);
  29920. // Six indices (two triangles) per face.
  29921. var verticesLength = positions.length / 3;
  29922. indices.push(verticesLength);
  29923. indices.push(verticesLength + 1);
  29924. indices.push(verticesLength + 2);
  29925. indices.push(verticesLength);
  29926. indices.push(verticesLength + 2);
  29927. indices.push(verticesLength + 3);
  29928. // Four vertices per face.
  29929. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  29930. positions.push(vertex.x, vertex.y, vertex.z);
  29931. normals.push(normal.x, normal.y, normal.z);
  29932. uvs.push(faceUV[index].z, faceUV[index].w);
  29933. if (faceColors) {
  29934. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29935. }
  29936. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  29937. positions.push(vertex.x, vertex.y, vertex.z);
  29938. normals.push(normal.x, normal.y, normal.z);
  29939. uvs.push(faceUV[index].x, faceUV[index].w);
  29940. if (faceColors) {
  29941. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29942. }
  29943. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  29944. positions.push(vertex.x, vertex.y, vertex.z);
  29945. normals.push(normal.x, normal.y, normal.z);
  29946. uvs.push(faceUV[index].x, faceUV[index].y);
  29947. if (faceColors) {
  29948. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29949. }
  29950. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  29951. positions.push(vertex.x, vertex.y, vertex.z);
  29952. normals.push(normal.x, normal.y, normal.z);
  29953. uvs.push(faceUV[index].z, faceUV[index].y);
  29954. if (faceColors) {
  29955. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29956. }
  29957. }
  29958. // sides
  29959. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29960. // Result
  29961. var vertexData = new VertexData();
  29962. vertexData.indices = indices;
  29963. vertexData.positions = positions;
  29964. vertexData.normals = normals;
  29965. vertexData.uvs = uvs;
  29966. if (faceColors) {
  29967. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29968. vertexData.colors = totalColors;
  29969. }
  29970. return vertexData;
  29971. };
  29972. VertexData.CreateSphere = function (options) {
  29973. var segments = options.segments || 32;
  29974. var diameterX = options.diameterX || options.diameter || 1;
  29975. var diameterY = options.diameterY || options.diameter || 1;
  29976. var diameterZ = options.diameterZ || options.diameter || 1;
  29977. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29978. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  29979. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29980. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  29981. var totalZRotationSteps = 2 + segments;
  29982. var totalYRotationSteps = 2 * totalZRotationSteps;
  29983. var indices = [];
  29984. var positions = [];
  29985. var normals = [];
  29986. var uvs = [];
  29987. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  29988. var normalizedZ = zRotationStep / totalZRotationSteps;
  29989. var angleZ = normalizedZ * Math.PI * slice;
  29990. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  29991. var normalizedY = yRotationStep / totalYRotationSteps;
  29992. var angleY = normalizedY * Math.PI * 2 * arc;
  29993. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  29994. var rotationY = BABYLON.Matrix.RotationY(angleY);
  29995. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  29996. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  29997. var vertex = complete.multiply(radius);
  29998. var normal = complete.divide(radius).normalize();
  29999. positions.push(vertex.x, vertex.y, vertex.z);
  30000. normals.push(normal.x, normal.y, normal.z);
  30001. uvs.push(normalizedY, normalizedZ);
  30002. }
  30003. if (zRotationStep > 0) {
  30004. var verticesCount = positions.length / 3;
  30005. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  30006. indices.push((firstIndex));
  30007. indices.push((firstIndex + 1));
  30008. indices.push(firstIndex + totalYRotationSteps + 1);
  30009. indices.push((firstIndex + totalYRotationSteps + 1));
  30010. indices.push((firstIndex + 1));
  30011. indices.push((firstIndex + totalYRotationSteps + 2));
  30012. }
  30013. }
  30014. }
  30015. // Sides
  30016. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30017. // Result
  30018. var vertexData = new VertexData();
  30019. vertexData.indices = indices;
  30020. vertexData.positions = positions;
  30021. vertexData.normals = normals;
  30022. vertexData.uvs = uvs;
  30023. return vertexData;
  30024. };
  30025. // Cylinder and cone
  30026. VertexData.CreateCylinder = function (options) {
  30027. var height = options.height || 2;
  30028. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  30029. var diameterBottom = options.diameterBottom || options.diameter || 1;
  30030. var tessellation = options.tessellation || 24;
  30031. var subdivisions = options.subdivisions || 1;
  30032. var hasRings = options.hasRings;
  30033. var enclose = options.enclose;
  30034. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30035. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30036. var faceUV = options.faceUV || new Array(3);
  30037. var faceColors = options.faceColors;
  30038. // default face colors and UV if undefined
  30039. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  30040. var ringNb = (hasRings) ? subdivisions : 1;
  30041. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  30042. var f;
  30043. for (f = 0; f < surfaceNb; f++) {
  30044. if (faceColors && faceColors[f] === undefined) {
  30045. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30046. }
  30047. }
  30048. for (f = 0; f < surfaceNb; f++) {
  30049. if (faceUV && faceUV[f] === undefined) {
  30050. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30051. }
  30052. }
  30053. var indices = [];
  30054. var positions = [];
  30055. var normals = [];
  30056. var uvs = [];
  30057. var colors = [];
  30058. var angle_step = Math.PI * 2 * arc / tessellation;
  30059. var angle;
  30060. var h;
  30061. var radius;
  30062. var tan = (diameterBottom - diameterTop) / 2 / height;
  30063. var ringVertex = BABYLON.Vector3.Zero();
  30064. var ringNormal = BABYLON.Vector3.Zero();
  30065. var ringFirstVertex = BABYLON.Vector3.Zero();
  30066. var ringFirstNormal = BABYLON.Vector3.Zero();
  30067. var quadNormal = BABYLON.Vector3.Zero();
  30068. var Y = BABYLON.Axis.Y;
  30069. // positions, normals, uvs
  30070. var i;
  30071. var j;
  30072. var r;
  30073. var ringIdx = 1;
  30074. var s = 1; // surface index
  30075. var cs = 0;
  30076. var v = 0;
  30077. for (i = 0; i <= subdivisions; i++) {
  30078. h = i / subdivisions;
  30079. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  30080. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  30081. for (r = 0; r < ringIdx; r++) {
  30082. if (hasRings) {
  30083. s += r;
  30084. }
  30085. if (enclose) {
  30086. s += 2 * r;
  30087. }
  30088. for (j = 0; j <= tessellation; j++) {
  30089. angle = j * angle_step;
  30090. // position
  30091. ringVertex.x = Math.cos(-angle) * radius;
  30092. ringVertex.y = -height / 2 + h * height;
  30093. ringVertex.z = Math.sin(-angle) * radius;
  30094. // normal
  30095. if (diameterTop === 0 && i === subdivisions) {
  30096. // if no top cap, reuse former normals
  30097. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  30098. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  30099. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  30100. }
  30101. else {
  30102. ringNormal.x = ringVertex.x;
  30103. ringNormal.z = ringVertex.z;
  30104. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  30105. ringNormal.normalize();
  30106. }
  30107. // keep first ring vertex values for enclose
  30108. if (j === 0) {
  30109. ringFirstVertex.copyFrom(ringVertex);
  30110. ringFirstNormal.copyFrom(ringNormal);
  30111. }
  30112. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30113. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  30114. if (hasRings) {
  30115. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  30116. }
  30117. else {
  30118. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  30119. }
  30120. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  30121. if (faceColors) {
  30122. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  30123. }
  30124. }
  30125. // if enclose, add four vertices and their dedicated normals
  30126. if (arc !== 1 && enclose) {
  30127. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30128. positions.push(0, ringVertex.y, 0);
  30129. positions.push(0, ringVertex.y, 0);
  30130. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  30131. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  30132. quadNormal.normalize();
  30133. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30134. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  30135. quadNormal.normalize();
  30136. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30137. if (hasRings) {
  30138. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  30139. }
  30140. else {
  30141. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  30142. }
  30143. uvs.push(faceUV[s + 1].x, v);
  30144. uvs.push(faceUV[s + 1].z, v);
  30145. if (hasRings) {
  30146. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  30147. }
  30148. else {
  30149. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  30150. }
  30151. uvs.push(faceUV[s + 2].x, v);
  30152. uvs.push(faceUV[s + 2].z, v);
  30153. if (faceColors) {
  30154. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30155. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30156. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30157. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30158. }
  30159. }
  30160. if (cs !== s) {
  30161. cs = s;
  30162. }
  30163. }
  30164. }
  30165. // indices
  30166. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  30167. var s;
  30168. i = 0;
  30169. for (s = 0; s < subdivisions; s++) {
  30170. for (j = 0; j < tessellation; j++) {
  30171. var i0 = i * (e + 1) + j;
  30172. var i1 = (i + 1) * (e + 1) + j;
  30173. var i2 = i * (e + 1) + (j + 1);
  30174. var i3 = (i + 1) * (e + 1) + (j + 1);
  30175. indices.push(i0, i1, i2);
  30176. indices.push(i3, i2, i1);
  30177. }
  30178. if (arc !== 1 && enclose) {
  30179. indices.push(i0 + 2, i1 + 2, i2 + 2);
  30180. indices.push(i3 + 2, i2 + 2, i1 + 2);
  30181. indices.push(i0 + 4, i1 + 4, i2 + 4);
  30182. indices.push(i3 + 4, i2 + 4, i1 + 4);
  30183. }
  30184. i = (hasRings) ? (i + 2) : (i + 1);
  30185. }
  30186. // Caps
  30187. var createCylinderCap = function (isTop) {
  30188. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  30189. if (radius === 0) {
  30190. return;
  30191. }
  30192. // Cap positions, normals & uvs
  30193. var angle;
  30194. var circleVector;
  30195. var i;
  30196. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  30197. var c;
  30198. if (faceColors) {
  30199. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  30200. }
  30201. // cap center
  30202. var vbase = positions.length / 3;
  30203. var offset = isTop ? height / 2 : -height / 2;
  30204. var center = new BABYLON.Vector3(0, offset, 0);
  30205. positions.push(center.x, center.y, center.z);
  30206. normals.push(0, isTop ? 1 : -1, 0);
  30207. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  30208. if (faceColors) {
  30209. colors.push(c.r, c.g, c.b, c.a);
  30210. }
  30211. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  30212. for (i = 0; i <= tessellation; i++) {
  30213. angle = Math.PI * 2 * i * arc / tessellation;
  30214. var cos = Math.cos(-angle);
  30215. var sin = Math.sin(-angle);
  30216. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  30217. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  30218. positions.push(circleVector.x, circleVector.y, circleVector.z);
  30219. normals.push(0, isTop ? 1 : -1, 0);
  30220. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  30221. if (faceColors) {
  30222. colors.push(c.r, c.g, c.b, c.a);
  30223. }
  30224. }
  30225. // Cap indices
  30226. for (i = 0; i < tessellation; i++) {
  30227. if (!isTop) {
  30228. indices.push(vbase);
  30229. indices.push(vbase + (i + 1));
  30230. indices.push(vbase + (i + 2));
  30231. }
  30232. else {
  30233. indices.push(vbase);
  30234. indices.push(vbase + (i + 2));
  30235. indices.push(vbase + (i + 1));
  30236. }
  30237. }
  30238. };
  30239. // add caps to geometry
  30240. createCylinderCap(false);
  30241. createCylinderCap(true);
  30242. // Sides
  30243. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30244. var vertexData = new VertexData();
  30245. vertexData.indices = indices;
  30246. vertexData.positions = positions;
  30247. vertexData.normals = normals;
  30248. vertexData.uvs = uvs;
  30249. if (faceColors) {
  30250. vertexData.colors = colors;
  30251. }
  30252. return vertexData;
  30253. };
  30254. VertexData.CreateTorus = function (options) {
  30255. var indices = [];
  30256. var positions = [];
  30257. var normals = [];
  30258. var uvs = [];
  30259. var diameter = options.diameter || 1;
  30260. var thickness = options.thickness || 0.5;
  30261. var tessellation = options.tessellation || 16;
  30262. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30263. var stride = tessellation + 1;
  30264. for (var i = 0; i <= tessellation; i++) {
  30265. var u = i / tessellation;
  30266. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  30267. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  30268. for (var j = 0; j <= tessellation; j++) {
  30269. var v = 1 - j / tessellation;
  30270. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  30271. var dx = Math.cos(innerAngle);
  30272. var dy = Math.sin(innerAngle);
  30273. // Create a vertex.
  30274. var normal = new BABYLON.Vector3(dx, dy, 0);
  30275. var position = normal.scale(thickness / 2);
  30276. var textureCoordinate = new BABYLON.Vector2(u, v);
  30277. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  30278. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  30279. positions.push(position.x, position.y, position.z);
  30280. normals.push(normal.x, normal.y, normal.z);
  30281. uvs.push(textureCoordinate.x, textureCoordinate.y);
  30282. // And create indices for two triangles.
  30283. var nextI = (i + 1) % stride;
  30284. var nextJ = (j + 1) % stride;
  30285. indices.push(i * stride + j);
  30286. indices.push(i * stride + nextJ);
  30287. indices.push(nextI * stride + j);
  30288. indices.push(i * stride + nextJ);
  30289. indices.push(nextI * stride + nextJ);
  30290. indices.push(nextI * stride + j);
  30291. }
  30292. }
  30293. // Sides
  30294. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30295. // Result
  30296. var vertexData = new VertexData();
  30297. vertexData.indices = indices;
  30298. vertexData.positions = positions;
  30299. vertexData.normals = normals;
  30300. vertexData.uvs = uvs;
  30301. return vertexData;
  30302. };
  30303. VertexData.CreateLineSystem = function (options) {
  30304. var indices = [];
  30305. var positions = [];
  30306. var lines = options.lines;
  30307. var idx = 0;
  30308. for (var l = 0; l < lines.length; l++) {
  30309. var points = lines[l];
  30310. for (var index = 0; index < points.length; index++) {
  30311. positions.push(points[index].x, points[index].y, points[index].z);
  30312. if (index > 0) {
  30313. indices.push(idx - 1);
  30314. indices.push(idx);
  30315. }
  30316. idx++;
  30317. }
  30318. }
  30319. var vertexData = new VertexData();
  30320. vertexData.indices = indices;
  30321. vertexData.positions = positions;
  30322. return vertexData;
  30323. };
  30324. VertexData.CreateDashedLines = function (options) {
  30325. var dashSize = options.dashSize || 3;
  30326. var gapSize = options.gapSize || 1;
  30327. var dashNb = options.dashNb || 200;
  30328. var points = options.points;
  30329. var positions = new Array();
  30330. var indices = new Array();
  30331. var curvect = BABYLON.Vector3.Zero();
  30332. var lg = 0;
  30333. var nb = 0;
  30334. var shft = 0;
  30335. var dashshft = 0;
  30336. var curshft = 0;
  30337. var idx = 0;
  30338. var i = 0;
  30339. for (i = 0; i < points.length - 1; i++) {
  30340. points[i + 1].subtractToRef(points[i], curvect);
  30341. lg += curvect.length();
  30342. }
  30343. shft = lg / dashNb;
  30344. dashshft = dashSize * shft / (dashSize + gapSize);
  30345. for (i = 0; i < points.length - 1; i++) {
  30346. points[i + 1].subtractToRef(points[i], curvect);
  30347. nb = Math.floor(curvect.length() / shft);
  30348. curvect.normalize();
  30349. for (var j = 0; j < nb; j++) {
  30350. curshft = shft * j;
  30351. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  30352. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  30353. indices.push(idx, idx + 1);
  30354. idx += 2;
  30355. }
  30356. }
  30357. // Result
  30358. var vertexData = new VertexData();
  30359. vertexData.positions = positions;
  30360. vertexData.indices = indices;
  30361. return vertexData;
  30362. };
  30363. VertexData.CreateGround = function (options) {
  30364. var indices = [];
  30365. var positions = [];
  30366. var normals = [];
  30367. var uvs = [];
  30368. var row, col;
  30369. var width = options.width || 1;
  30370. var height = options.height || 1;
  30371. var subdivisions = options.subdivisions || 1;
  30372. for (row = 0; row <= subdivisions; row++) {
  30373. for (col = 0; col <= subdivisions; col++) {
  30374. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  30375. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30376. positions.push(position.x, position.y, position.z);
  30377. normals.push(normal.x, normal.y, normal.z);
  30378. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  30379. }
  30380. }
  30381. for (row = 0; row < subdivisions; row++) {
  30382. for (col = 0; col < subdivisions; col++) {
  30383. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  30384. indices.push(col + 1 + row * (subdivisions + 1));
  30385. indices.push(col + row * (subdivisions + 1));
  30386. indices.push(col + (row + 1) * (subdivisions + 1));
  30387. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  30388. indices.push(col + row * (subdivisions + 1));
  30389. }
  30390. }
  30391. // Result
  30392. var vertexData = new VertexData();
  30393. vertexData.indices = indices;
  30394. vertexData.positions = positions;
  30395. vertexData.normals = normals;
  30396. vertexData.uvs = uvs;
  30397. return vertexData;
  30398. };
  30399. VertexData.CreateTiledGround = function (options) {
  30400. var xmin = options.xmin || -1.0;
  30401. var zmin = options.zmin || -1.0;
  30402. var xmax = options.xmax || 1.0;
  30403. var zmax = options.zmax || 1.0;
  30404. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  30405. var precision = options.precision || { w: 1, h: 1 };
  30406. var indices = [];
  30407. var positions = [];
  30408. var normals = [];
  30409. var uvs = [];
  30410. var row, col, tileRow, tileCol;
  30411. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  30412. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  30413. precision.w = (precision.w < 1) ? 1 : precision.w;
  30414. precision.h = (precision.h < 1) ? 1 : precision.h;
  30415. var tileSize = {
  30416. 'w': (xmax - xmin) / subdivisions.w,
  30417. 'h': (zmax - zmin) / subdivisions.h
  30418. };
  30419. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  30420. // Indices
  30421. var base = positions.length / 3;
  30422. var rowLength = precision.w + 1;
  30423. for (row = 0; row < precision.h; row++) {
  30424. for (col = 0; col < precision.w; col++) {
  30425. var square = [
  30426. base + col + row * rowLength,
  30427. base + (col + 1) + row * rowLength,
  30428. base + (col + 1) + (row + 1) * rowLength,
  30429. base + col + (row + 1) * rowLength
  30430. ];
  30431. indices.push(square[1]);
  30432. indices.push(square[2]);
  30433. indices.push(square[3]);
  30434. indices.push(square[0]);
  30435. indices.push(square[1]);
  30436. indices.push(square[3]);
  30437. }
  30438. }
  30439. // Position, normals and uvs
  30440. var position = BABYLON.Vector3.Zero();
  30441. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30442. for (row = 0; row <= precision.h; row++) {
  30443. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  30444. for (col = 0; col <= precision.w; col++) {
  30445. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  30446. position.y = 0;
  30447. positions.push(position.x, position.y, position.z);
  30448. normals.push(normal.x, normal.y, normal.z);
  30449. uvs.push(col / precision.w, row / precision.h);
  30450. }
  30451. }
  30452. }
  30453. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  30454. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  30455. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  30456. }
  30457. }
  30458. // Result
  30459. var vertexData = new VertexData();
  30460. vertexData.indices = indices;
  30461. vertexData.positions = positions;
  30462. vertexData.normals = normals;
  30463. vertexData.uvs = uvs;
  30464. return vertexData;
  30465. };
  30466. VertexData.CreateGroundFromHeightMap = function (options) {
  30467. var indices = [];
  30468. var positions = [];
  30469. var normals = [];
  30470. var uvs = [];
  30471. var row, col;
  30472. // Vertices
  30473. for (row = 0; row <= options.subdivisions; row++) {
  30474. for (col = 0; col <= options.subdivisions; col++) {
  30475. 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));
  30476. // Compute height
  30477. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  30478. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  30479. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  30480. var r = options.buffer[pos] / 255.0;
  30481. var g = options.buffer[pos + 1] / 255.0;
  30482. var b = options.buffer[pos + 2] / 255.0;
  30483. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  30484. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  30485. // Add vertex
  30486. positions.push(position.x, position.y, position.z);
  30487. normals.push(0, 0, 0);
  30488. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  30489. }
  30490. }
  30491. // Indices
  30492. for (row = 0; row < options.subdivisions; row++) {
  30493. for (col = 0; col < options.subdivisions; col++) {
  30494. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30495. indices.push(col + 1 + row * (options.subdivisions + 1));
  30496. indices.push(col + row * (options.subdivisions + 1));
  30497. indices.push(col + (row + 1) * (options.subdivisions + 1));
  30498. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30499. indices.push(col + row * (options.subdivisions + 1));
  30500. }
  30501. }
  30502. // Normals
  30503. VertexData.ComputeNormals(positions, indices, normals);
  30504. // Result
  30505. var vertexData = new VertexData();
  30506. vertexData.indices = indices;
  30507. vertexData.positions = positions;
  30508. vertexData.normals = normals;
  30509. vertexData.uvs = uvs;
  30510. return vertexData;
  30511. };
  30512. VertexData.CreatePlane = function (options) {
  30513. var indices = [];
  30514. var positions = [];
  30515. var normals = [];
  30516. var uvs = [];
  30517. var width = options.width || options.size || 1;
  30518. var height = options.height || options.size || 1;
  30519. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30520. // Vertices
  30521. var halfWidth = width / 2.0;
  30522. var halfHeight = height / 2.0;
  30523. positions.push(-halfWidth, -halfHeight, 0);
  30524. normals.push(0, 0, -1.0);
  30525. uvs.push(0.0, 0.0);
  30526. positions.push(halfWidth, -halfHeight, 0);
  30527. normals.push(0, 0, -1.0);
  30528. uvs.push(1.0, 0.0);
  30529. positions.push(halfWidth, halfHeight, 0);
  30530. normals.push(0, 0, -1.0);
  30531. uvs.push(1.0, 1.0);
  30532. positions.push(-halfWidth, halfHeight, 0);
  30533. normals.push(0, 0, -1.0);
  30534. uvs.push(0.0, 1.0);
  30535. // Indices
  30536. indices.push(0);
  30537. indices.push(1);
  30538. indices.push(2);
  30539. indices.push(0);
  30540. indices.push(2);
  30541. indices.push(3);
  30542. // Sides
  30543. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30544. // Result
  30545. var vertexData = new VertexData();
  30546. vertexData.indices = indices;
  30547. vertexData.positions = positions;
  30548. vertexData.normals = normals;
  30549. vertexData.uvs = uvs;
  30550. return vertexData;
  30551. };
  30552. VertexData.CreateDisc = function (options) {
  30553. var positions = [];
  30554. var indices = [];
  30555. var normals = [];
  30556. var uvs = [];
  30557. var radius = options.radius || 0.5;
  30558. var tessellation = options.tessellation || 64;
  30559. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30560. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30561. // positions and uvs
  30562. positions.push(0, 0, 0); // disc center first
  30563. uvs.push(0.5, 0.5);
  30564. var theta = Math.PI * 2 * arc;
  30565. var step = theta / tessellation;
  30566. for (var a = 0; a < theta; a += step) {
  30567. var x = Math.cos(a);
  30568. var y = Math.sin(a);
  30569. var u = (x + 1) / 2;
  30570. var v = (1 - y) / 2;
  30571. positions.push(radius * x, radius * y, 0);
  30572. uvs.push(u, v);
  30573. }
  30574. if (arc === 1) {
  30575. positions.push(positions[3], positions[4], positions[5]); // close the circle
  30576. uvs.push(uvs[2], uvs[3]);
  30577. }
  30578. //indices
  30579. var vertexNb = positions.length / 3;
  30580. for (var i = 1; i < vertexNb - 1; i++) {
  30581. indices.push(i + 1, 0, i);
  30582. }
  30583. // result
  30584. VertexData.ComputeNormals(positions, indices, normals);
  30585. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30586. var vertexData = new VertexData();
  30587. vertexData.indices = indices;
  30588. vertexData.positions = positions;
  30589. vertexData.normals = normals;
  30590. vertexData.uvs = uvs;
  30591. return vertexData;
  30592. };
  30593. VertexData.CreateIcoSphere = function (options) {
  30594. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30595. var radius = options.radius || 1;
  30596. var flat = (options.flat === undefined) ? true : options.flat;
  30597. var subdivisions = options.subdivisions || 4;
  30598. var radiusX = options.radiusX || radius;
  30599. var radiusY = options.radiusY || radius;
  30600. var radiusZ = options.radiusZ || radius;
  30601. var t = (1 + Math.sqrt(5)) / 2;
  30602. // 12 vertex x,y,z
  30603. var ico_vertices = [
  30604. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30605. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30606. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30607. ];
  30608. // index of 3 vertex makes a face of icopshere
  30609. var ico_indices = [
  30610. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30611. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30612. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30613. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30614. ];
  30615. // vertex for uv have aliased position, not for UV
  30616. var vertices_unalias_id = [
  30617. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30618. // vertex alias
  30619. 0,
  30620. 2,
  30621. 3,
  30622. 3,
  30623. 3,
  30624. 4,
  30625. 7,
  30626. 8,
  30627. 9,
  30628. 9,
  30629. 10,
  30630. 11 // 23: B + 12
  30631. ];
  30632. // uv as integer step (not pixels !)
  30633. var ico_vertexuv = [
  30634. 5, 1, 3, 1, 6, 4, 0, 0,
  30635. 5, 3, 4, 2, 2, 2, 4, 0,
  30636. 2, 0, 1, 1, 6, 0, 6, 2,
  30637. // vertex alias (for same vertex on different faces)
  30638. 0, 4,
  30639. 3, 3,
  30640. 4, 4,
  30641. 3, 1,
  30642. 4, 2,
  30643. 4, 4,
  30644. 0, 2,
  30645. 1, 1,
  30646. 2, 2,
  30647. 3, 3,
  30648. 1, 3,
  30649. 2, 4 // 23: B + 12
  30650. ];
  30651. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30652. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30653. // First island of uv mapping
  30654. // v = 4h 3+ 2
  30655. // v = 3h 9+ 4
  30656. // v = 2h 9+ 5 B
  30657. // v = 1h 9 1 0
  30658. // v = 0h 3 8 7 A
  30659. // u = 0 1 2 3 4 5 6 *a
  30660. // Second island of uv mapping
  30661. // v = 4h 0+ B+ 4+
  30662. // v = 3h A+ 2+
  30663. // v = 2h 7+ 6 3+
  30664. // v = 1h 8+ 3+
  30665. // v = 0h
  30666. // u = 0 1 2 3 4 5 6 *a
  30667. // Face layout on texture UV mapping
  30668. // ============
  30669. // \ 4 /\ 16 / ======
  30670. // \ / \ / /\ 11 /
  30671. // \/ 7 \/ / \ /
  30672. // ======= / 10 \/
  30673. // /\ 17 /\ =======
  30674. // / \ / \ \ 15 /\
  30675. // / 8 \/ 12 \ \ / \
  30676. // ============ \/ 6 \
  30677. // \ 18 /\ ============
  30678. // \ / \ \ 5 /\ 0 /
  30679. // \/ 13 \ \ / \ /
  30680. // ======= \/ 1 \/
  30681. // =============
  30682. // /\ 19 /\ 2 /\
  30683. // / \ / \ / \
  30684. // / 14 \/ 9 \/ 3 \
  30685. // ===================
  30686. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30687. var ustep = 138 / 1024;
  30688. var vstep = 239 / 1024;
  30689. var uoffset = 60 / 1024;
  30690. var voffset = 26 / 1024;
  30691. // Second island should have margin, not to touch the first island
  30692. // avoid any borderline artefact in pixel rounding
  30693. var island_u_offset = -40 / 1024;
  30694. var island_v_offset = +20 / 1024;
  30695. // face is either island 0 or 1 :
  30696. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30697. var island = [
  30698. 0, 0, 0, 0, 1,
  30699. 0, 0, 1, 1, 0,
  30700. 0, 0, 1, 1, 0,
  30701. 0, 1, 1, 1, 0 // 15 - 19
  30702. ];
  30703. var indices = [];
  30704. var positions = [];
  30705. var normals = [];
  30706. var uvs = [];
  30707. var current_indice = 0;
  30708. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30709. var face_vertex_pos = new Array(3);
  30710. var face_vertex_uv = new Array(3);
  30711. var v012;
  30712. for (v012 = 0; v012 < 3; v012++) {
  30713. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30714. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30715. }
  30716. // create all with normals
  30717. for (var face = 0; face < 20; face++) {
  30718. // 3 vertex per face
  30719. for (v012 = 0; v012 < 3; v012++) {
  30720. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30721. var v_id = ico_indices[3 * face + v012];
  30722. // vertex have 3D position (x,y,z)
  30723. 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]);
  30724. // Normalize to get normal, then scale to radius
  30725. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30726. // uv Coordinates from vertex ID
  30727. 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);
  30728. }
  30729. // Subdivide the face (interpolate pos, norm, uv)
  30730. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30731. // - norm is linear interpolation of vertex corner normal
  30732. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30733. // - uv is linear interpolation
  30734. //
  30735. // Topology is as below for sub-divide by 2
  30736. // vertex shown as v0,v1,v2
  30737. // interp index is i1 to progress in range [v0,v1[
  30738. // interp index is i2 to progress in range [v0,v2[
  30739. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30740. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30741. //
  30742. //
  30743. // i2 v2
  30744. // ^ ^
  30745. // / / \
  30746. // / / \
  30747. // / / \
  30748. // / / (0,1) \
  30749. // / #---------\
  30750. // / / \ (0,0)'/ \
  30751. // / / \ / \
  30752. // / / \ / \
  30753. // / / (0,0) \ / (1,0) \
  30754. // / #---------#---------\
  30755. // v0 v1
  30756. //
  30757. // --------------------> i1
  30758. //
  30759. // interp of (i1,i2):
  30760. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30761. // along i1 : lerp(x0,x1, i1/(S-i2))
  30762. //
  30763. // centroid of triangle is needed to get help normal computation
  30764. // (c1,c2) are used for centroid location
  30765. var interp_vertex = function (i1, i2, c1, c2) {
  30766. // vertex is interpolated from
  30767. // - face_vertex_pos[0..2]
  30768. // - face_vertex_uv[0..2]
  30769. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30770. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30771. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30772. pos_interp.normalize();
  30773. var vertex_normal;
  30774. if (flat) {
  30775. // in flat mode, recalculate normal as face centroid normal
  30776. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30777. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30778. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30779. }
  30780. else {
  30781. // in smooth mode, recalculate normal from each single vertex position
  30782. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30783. }
  30784. // Vertex normal need correction due to X,Y,Z radius scaling
  30785. vertex_normal.x /= radiusX;
  30786. vertex_normal.y /= radiusY;
  30787. vertex_normal.z /= radiusZ;
  30788. vertex_normal.normalize();
  30789. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30790. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30791. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30792. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30793. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30794. uvs.push(uv_interp.x, uv_interp.y);
  30795. // push each vertex has member of a face
  30796. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30797. indices.push(current_indice);
  30798. current_indice++;
  30799. };
  30800. for (var i2 = 0; i2 < subdivisions; i2++) {
  30801. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30802. // face : (i1,i2) for /\ :
  30803. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30804. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30805. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30806. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30807. if (i1 + i2 + 1 < subdivisions) {
  30808. // face : (i1,i2)' for \/ :
  30809. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30810. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30811. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30812. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30813. }
  30814. }
  30815. }
  30816. }
  30817. // Sides
  30818. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30819. // Result
  30820. var vertexData = new VertexData();
  30821. vertexData.indices = indices;
  30822. vertexData.positions = positions;
  30823. vertexData.normals = normals;
  30824. vertexData.uvs = uvs;
  30825. return vertexData;
  30826. };
  30827. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  30828. VertexData.CreatePolyhedron = function (options) {
  30829. // provided polyhedron types :
  30830. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  30831. // 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)
  30832. var polyhedra = [];
  30833. 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]] };
  30834. 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]] };
  30835. polyhedra[2] = {
  30836. 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]],
  30837. 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]]
  30838. };
  30839. polyhedra[3] = {
  30840. 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]],
  30841. 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]]
  30842. };
  30843. polyhedra[4] = {
  30844. 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]],
  30845. 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]]
  30846. };
  30847. 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]] };
  30848. 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]] };
  30849. 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]] };
  30850. 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]] };
  30851. 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]] };
  30852. 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]] };
  30853. 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]] };
  30854. 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]] };
  30855. 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]] };
  30856. polyhedra[14] = {
  30857. 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]],
  30858. 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]]
  30859. };
  30860. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  30861. var size = options.size;
  30862. var sizeX = options.sizeX || size || 1;
  30863. var sizeY = options.sizeY || size || 1;
  30864. var sizeZ = options.sizeZ || size || 1;
  30865. var data = options.custom || polyhedra[type];
  30866. var nbfaces = data.face.length;
  30867. var faceUV = options.faceUV || new Array(nbfaces);
  30868. var faceColors = options.faceColors;
  30869. var flat = (options.flat === undefined) ? true : options.flat;
  30870. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30871. var positions = [];
  30872. var indices = [];
  30873. var normals = [];
  30874. var uvs = [];
  30875. var colors = [];
  30876. var index = 0;
  30877. var faceIdx = 0; // face cursor in the array "indexes"
  30878. var indexes = [];
  30879. var i = 0;
  30880. var f = 0;
  30881. var u, v, ang, x, y, tmp;
  30882. // default face colors and UV if undefined
  30883. if (flat) {
  30884. for (f = 0; f < nbfaces; f++) {
  30885. if (faceColors && faceColors[f] === undefined) {
  30886. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30887. }
  30888. if (faceUV && faceUV[f] === undefined) {
  30889. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30890. }
  30891. }
  30892. }
  30893. if (!flat) {
  30894. for (i = 0; i < data.vertex.length; i++) {
  30895. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  30896. uvs.push(0, 0);
  30897. }
  30898. for (f = 0; f < nbfaces; f++) {
  30899. for (i = 0; i < data.face[f].length - 2; i++) {
  30900. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  30901. }
  30902. }
  30903. }
  30904. else {
  30905. for (f = 0; f < nbfaces; f++) {
  30906. var fl = data.face[f].length; // number of vertices of the current face
  30907. ang = 2 * Math.PI / fl;
  30908. x = 0.5 * Math.tan(ang / 2);
  30909. y = 0.5;
  30910. // positions, uvs, colors
  30911. for (i = 0; i < fl; i++) {
  30912. // positions
  30913. 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);
  30914. indexes.push(index);
  30915. index++;
  30916. // uvs
  30917. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  30918. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  30919. uvs.push(u, v);
  30920. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  30921. y = x * Math.sin(ang) + y * Math.cos(ang);
  30922. x = tmp;
  30923. // colors
  30924. if (faceColors) {
  30925. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  30926. }
  30927. }
  30928. // indices from indexes
  30929. for (i = 0; i < fl - 2; i++) {
  30930. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  30931. }
  30932. faceIdx += fl;
  30933. }
  30934. }
  30935. VertexData.ComputeNormals(positions, indices, normals);
  30936. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30937. var vertexData = new VertexData();
  30938. vertexData.positions = positions;
  30939. vertexData.indices = indices;
  30940. vertexData.normals = normals;
  30941. vertexData.uvs = uvs;
  30942. if (faceColors && flat) {
  30943. vertexData.colors = colors;
  30944. }
  30945. return vertexData;
  30946. };
  30947. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  30948. VertexData.CreateTorusKnot = function (options) {
  30949. var indices = [];
  30950. var positions = [];
  30951. var normals = [];
  30952. var uvs = [];
  30953. var radius = options.radius || 2;
  30954. var tube = options.tube || 0.5;
  30955. var radialSegments = options.radialSegments || 32;
  30956. var tubularSegments = options.tubularSegments || 32;
  30957. var p = options.p || 2;
  30958. var q = options.q || 3;
  30959. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30960. // Helper
  30961. var getPos = function (angle) {
  30962. var cu = Math.cos(angle);
  30963. var su = Math.sin(angle);
  30964. var quOverP = q / p * angle;
  30965. var cs = Math.cos(quOverP);
  30966. var tx = radius * (2 + cs) * 0.5 * cu;
  30967. var ty = radius * (2 + cs) * su * 0.5;
  30968. var tz = radius * Math.sin(quOverP) * 0.5;
  30969. return new BABYLON.Vector3(tx, ty, tz);
  30970. };
  30971. // Vertices
  30972. var i;
  30973. var j;
  30974. for (i = 0; i <= radialSegments; i++) {
  30975. var modI = i % radialSegments;
  30976. var u = modI / radialSegments * 2 * p * Math.PI;
  30977. var p1 = getPos(u);
  30978. var p2 = getPos(u + 0.01);
  30979. var tang = p2.subtract(p1);
  30980. var n = p2.add(p1);
  30981. var bitan = BABYLON.Vector3.Cross(tang, n);
  30982. n = BABYLON.Vector3.Cross(bitan, tang);
  30983. bitan.normalize();
  30984. n.normalize();
  30985. for (j = 0; j < tubularSegments; j++) {
  30986. var modJ = j % tubularSegments;
  30987. var v = modJ / tubularSegments * 2 * Math.PI;
  30988. var cx = -tube * Math.cos(v);
  30989. var cy = tube * Math.sin(v);
  30990. positions.push(p1.x + cx * n.x + cy * bitan.x);
  30991. positions.push(p1.y + cx * n.y + cy * bitan.y);
  30992. positions.push(p1.z + cx * n.z + cy * bitan.z);
  30993. uvs.push(i / radialSegments);
  30994. uvs.push(j / tubularSegments);
  30995. }
  30996. }
  30997. for (i = 0; i < radialSegments; i++) {
  30998. for (j = 0; j < tubularSegments; j++) {
  30999. var jNext = (j + 1) % tubularSegments;
  31000. var a = i * tubularSegments + j;
  31001. var b = (i + 1) * tubularSegments + j;
  31002. var c = (i + 1) * tubularSegments + jNext;
  31003. var d = i * tubularSegments + jNext;
  31004. indices.push(d);
  31005. indices.push(b);
  31006. indices.push(a);
  31007. indices.push(d);
  31008. indices.push(c);
  31009. indices.push(b);
  31010. }
  31011. }
  31012. // Normals
  31013. VertexData.ComputeNormals(positions, indices, normals);
  31014. // Sides
  31015. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31016. // Result
  31017. var vertexData = new VertexData();
  31018. vertexData.indices = indices;
  31019. vertexData.positions = positions;
  31020. vertexData.normals = normals;
  31021. vertexData.uvs = uvs;
  31022. return vertexData;
  31023. };
  31024. // Tools
  31025. /**
  31026. * @param {any} - positions (number[] or Float32Array)
  31027. * @param {any} - indices (number[] or Uint16Array)
  31028. * @param {any} - normals (number[] or Float32Array)
  31029. */
  31030. VertexData.ComputeNormals = function (positions, indices, normals) {
  31031. var index = 0;
  31032. var p1p2x = 0.0;
  31033. var p1p2y = 0.0;
  31034. var p1p2z = 0.0;
  31035. var p3p2x = 0.0;
  31036. var p3p2y = 0.0;
  31037. var p3p2z = 0.0;
  31038. var faceNormalx = 0.0;
  31039. var faceNormaly = 0.0;
  31040. var faceNormalz = 0.0;
  31041. var length = 0.0;
  31042. var i1 = 0;
  31043. var i2 = 0;
  31044. var i3 = 0;
  31045. for (index = 0; index < positions.length; index++) {
  31046. normals[index] = 0.0;
  31047. }
  31048. // indice triplet = 1 face
  31049. var nbFaces = indices.length / 3;
  31050. for (index = 0; index < nbFaces; index++) {
  31051. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  31052. i2 = indices[index * 3 + 1];
  31053. i3 = indices[index * 3 + 2];
  31054. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  31055. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  31056. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  31057. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  31058. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  31059. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  31060. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  31061. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  31062. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  31063. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31064. length = (length === 0) ? 1.0 : length;
  31065. faceNormalx /= length; // normalize this normal
  31066. faceNormaly /= length;
  31067. faceNormalz /= length;
  31068. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  31069. normals[i1 * 3 + 1] += faceNormaly;
  31070. normals[i1 * 3 + 2] += faceNormalz;
  31071. normals[i2 * 3] += faceNormalx;
  31072. normals[i2 * 3 + 1] += faceNormaly;
  31073. normals[i2 * 3 + 2] += faceNormalz;
  31074. normals[i3 * 3] += faceNormalx;
  31075. normals[i3 * 3 + 1] += faceNormaly;
  31076. normals[i3 * 3 + 2] += faceNormalz;
  31077. }
  31078. // last normalization of each normal
  31079. for (index = 0; index < normals.length / 3; index++) {
  31080. faceNormalx = normals[index * 3];
  31081. faceNormaly = normals[index * 3 + 1];
  31082. faceNormalz = normals[index * 3 + 2];
  31083. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31084. length = (length === 0) ? 1.0 : length;
  31085. faceNormalx /= length;
  31086. faceNormaly /= length;
  31087. faceNormalz /= length;
  31088. normals[index * 3] = faceNormalx;
  31089. normals[index * 3 + 1] = faceNormaly;
  31090. normals[index * 3 + 2] = faceNormalz;
  31091. }
  31092. };
  31093. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  31094. var li = indices.length;
  31095. var ln = normals.length;
  31096. var i;
  31097. var n;
  31098. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31099. switch (sideOrientation) {
  31100. case BABYLON.Mesh.FRONTSIDE:
  31101. // nothing changed
  31102. break;
  31103. case BABYLON.Mesh.BACKSIDE:
  31104. var tmp;
  31105. // indices
  31106. for (i = 0; i < li; i += 3) {
  31107. tmp = indices[i];
  31108. indices[i] = indices[i + 2];
  31109. indices[i + 2] = tmp;
  31110. }
  31111. // normals
  31112. for (n = 0; n < ln; n++) {
  31113. normals[n] = -normals[n];
  31114. }
  31115. break;
  31116. case BABYLON.Mesh.DOUBLESIDE:
  31117. // positions
  31118. var lp = positions.length;
  31119. var l = lp / 3;
  31120. for (var p = 0; p < lp; p++) {
  31121. positions[lp + p] = positions[p];
  31122. }
  31123. // indices
  31124. for (i = 0; i < li; i += 3) {
  31125. indices[i + li] = indices[i + 2] + l;
  31126. indices[i + 1 + li] = indices[i + 1] + l;
  31127. indices[i + 2 + li] = indices[i] + l;
  31128. }
  31129. // normals
  31130. for (n = 0; n < ln; n++) {
  31131. normals[ln + n] = -normals[n];
  31132. }
  31133. // uvs
  31134. var lu = uvs.length;
  31135. for (var u = 0; u < lu; u++) {
  31136. uvs[u + lu] = uvs[u];
  31137. }
  31138. break;
  31139. }
  31140. };
  31141. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  31142. var vertexData = new VertexData();
  31143. // positions
  31144. var positions = parsedVertexData.positions;
  31145. if (positions) {
  31146. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  31147. }
  31148. // normals
  31149. var normals = parsedVertexData.normals;
  31150. if (normals) {
  31151. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  31152. }
  31153. // uvs
  31154. var uvs = parsedVertexData.uvs;
  31155. if (uvs) {
  31156. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  31157. }
  31158. // uv2s
  31159. var uv2s = parsedVertexData.uv2s;
  31160. if (uv2s) {
  31161. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  31162. }
  31163. // uv3s
  31164. var uv3s = parsedVertexData.uv3s;
  31165. if (uv3s) {
  31166. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  31167. }
  31168. // uv4s
  31169. var uv4s = parsedVertexData.uv4s;
  31170. if (uv4s) {
  31171. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  31172. }
  31173. // uv5s
  31174. var uv5s = parsedVertexData.uv5s;
  31175. if (uv5s) {
  31176. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  31177. }
  31178. // uv6s
  31179. var uv6s = parsedVertexData.uv6s;
  31180. if (uv6s) {
  31181. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  31182. }
  31183. // colors
  31184. var colors = parsedVertexData.colors;
  31185. if (colors) {
  31186. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  31187. }
  31188. // matricesIndices
  31189. var matricesIndices = parsedVertexData.matricesIndices;
  31190. if (matricesIndices) {
  31191. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  31192. }
  31193. // matricesWeights
  31194. var matricesWeights = parsedVertexData.matricesWeights;
  31195. if (matricesWeights) {
  31196. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  31197. }
  31198. // indices
  31199. var indices = parsedVertexData.indices;
  31200. if (indices) {
  31201. vertexData.indices = indices;
  31202. }
  31203. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  31204. };
  31205. return VertexData;
  31206. }());
  31207. BABYLON.VertexData = VertexData;
  31208. })(BABYLON || (BABYLON = {}));
  31209. var BABYLON;
  31210. (function (BABYLON) {
  31211. var Tags = (function () {
  31212. function Tags() {
  31213. }
  31214. Tags.EnableFor = function (obj) {
  31215. obj._tags = obj._tags || {};
  31216. obj.hasTags = function () {
  31217. return Tags.HasTags(obj);
  31218. };
  31219. obj.addTags = function (tagsString) {
  31220. return Tags.AddTagsTo(obj, tagsString);
  31221. };
  31222. obj.removeTags = function (tagsString) {
  31223. return Tags.RemoveTagsFrom(obj, tagsString);
  31224. };
  31225. obj.matchesTagsQuery = function (tagsQuery) {
  31226. return Tags.MatchesQuery(obj, tagsQuery);
  31227. };
  31228. };
  31229. Tags.DisableFor = function (obj) {
  31230. delete obj._tags;
  31231. delete obj.hasTags;
  31232. delete obj.addTags;
  31233. delete obj.removeTags;
  31234. delete obj.matchesTagsQuery;
  31235. };
  31236. Tags.HasTags = function (obj) {
  31237. if (!obj._tags) {
  31238. return false;
  31239. }
  31240. return !BABYLON.Tools.IsEmpty(obj._tags);
  31241. };
  31242. Tags.GetTags = function (obj, asString) {
  31243. if (asString === void 0) { asString = true; }
  31244. if (!obj._tags) {
  31245. return null;
  31246. }
  31247. if (asString) {
  31248. var tagsArray = [];
  31249. for (var tag in obj._tags) {
  31250. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  31251. tagsArray.push(tag);
  31252. }
  31253. }
  31254. return tagsArray.join(" ");
  31255. }
  31256. else {
  31257. return obj._tags;
  31258. }
  31259. };
  31260. // the tags 'true' and 'false' are reserved and cannot be used as tags
  31261. // a tag cannot start with '||', '&&', and '!'
  31262. // it cannot contain whitespaces
  31263. Tags.AddTagsTo = function (obj, tagsString) {
  31264. if (!tagsString) {
  31265. return;
  31266. }
  31267. if (typeof tagsString !== "string") {
  31268. return;
  31269. }
  31270. var tags = tagsString.split(" ");
  31271. for (var t in tags) {
  31272. Tags._AddTagTo(obj, tags[t]);
  31273. }
  31274. };
  31275. Tags._AddTagTo = function (obj, tag) {
  31276. tag = tag.trim();
  31277. if (tag === "" || tag === "true" || tag === "false") {
  31278. return;
  31279. }
  31280. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  31281. return;
  31282. }
  31283. Tags.EnableFor(obj);
  31284. obj._tags[tag] = true;
  31285. };
  31286. Tags.RemoveTagsFrom = function (obj, tagsString) {
  31287. if (!Tags.HasTags(obj)) {
  31288. return;
  31289. }
  31290. var tags = tagsString.split(" ");
  31291. for (var t in tags) {
  31292. Tags._RemoveTagFrom(obj, tags[t]);
  31293. }
  31294. };
  31295. Tags._RemoveTagFrom = function (obj, tag) {
  31296. delete obj._tags[tag];
  31297. };
  31298. Tags.MatchesQuery = function (obj, tagsQuery) {
  31299. if (tagsQuery === undefined) {
  31300. return true;
  31301. }
  31302. if (tagsQuery === "") {
  31303. return Tags.HasTags(obj);
  31304. }
  31305. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  31306. };
  31307. return Tags;
  31308. }());
  31309. BABYLON.Tags = Tags;
  31310. })(BABYLON || (BABYLON = {}));
  31311. var BABYLON;
  31312. (function (BABYLON) {
  31313. var Internals;
  31314. (function (Internals) {
  31315. var AndOrNotEvaluator = (function () {
  31316. function AndOrNotEvaluator() {
  31317. }
  31318. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  31319. if (!query.match(/\([^\(\)]*\)/g)) {
  31320. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  31321. }
  31322. else {
  31323. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  31324. // remove parenthesis
  31325. r = r.slice(1, r.length - 1);
  31326. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  31327. });
  31328. }
  31329. if (query === "true") {
  31330. return true;
  31331. }
  31332. if (query === "false") {
  31333. return false;
  31334. }
  31335. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  31336. };
  31337. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  31338. evaluateCallback = evaluateCallback || (function (r) {
  31339. return r === "true" ? true : false;
  31340. });
  31341. var result;
  31342. var or = parenthesisContent.split("||");
  31343. for (var i in or) {
  31344. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  31345. var and = ori.split("&&");
  31346. if (and.length > 1) {
  31347. for (var j = 0; j < and.length; ++j) {
  31348. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  31349. if (andj !== "true" && andj !== "false") {
  31350. if (andj[0] === "!") {
  31351. result = !evaluateCallback(andj.substring(1));
  31352. }
  31353. else {
  31354. result = evaluateCallback(andj);
  31355. }
  31356. }
  31357. else {
  31358. result = andj === "true" ? true : false;
  31359. }
  31360. if (!result) {
  31361. ori = "false";
  31362. break;
  31363. }
  31364. }
  31365. }
  31366. if (result || ori === "true") {
  31367. result = true;
  31368. break;
  31369. }
  31370. // result equals false (or undefined)
  31371. if (ori !== "true" && ori !== "false") {
  31372. if (ori[0] === "!") {
  31373. result = !evaluateCallback(ori.substring(1));
  31374. }
  31375. else {
  31376. result = evaluateCallback(ori);
  31377. }
  31378. }
  31379. else {
  31380. result = ori === "true" ? true : false;
  31381. }
  31382. }
  31383. // the whole parenthesis scope is replaced by 'true' or 'false'
  31384. return result ? "true" : "false";
  31385. };
  31386. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  31387. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  31388. // remove whitespaces
  31389. r = r.replace(/[\s]/g, function () { return ""; });
  31390. return r.length % 2 ? "!" : "";
  31391. });
  31392. booleanString = booleanString.trim();
  31393. if (booleanString === "!true") {
  31394. booleanString = "false";
  31395. }
  31396. else if (booleanString === "!false") {
  31397. booleanString = "true";
  31398. }
  31399. return booleanString;
  31400. };
  31401. return AndOrNotEvaluator;
  31402. }());
  31403. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  31404. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31405. })(BABYLON || (BABYLON = {}));
  31406. var BABYLON;
  31407. (function (BABYLON) {
  31408. var PostProcessRenderPass = (function () {
  31409. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  31410. this._enabled = true;
  31411. this._refCount = 0;
  31412. this._name = name;
  31413. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  31414. this.setRenderList(renderList);
  31415. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  31416. this._renderTexture.onAfterRenderObservable.add(afterRender);
  31417. this._scene = scene;
  31418. this._renderList = renderList;
  31419. }
  31420. // private
  31421. PostProcessRenderPass.prototype._incRefCount = function () {
  31422. if (this._refCount === 0) {
  31423. this._scene.customRenderTargets.push(this._renderTexture);
  31424. }
  31425. return ++this._refCount;
  31426. };
  31427. PostProcessRenderPass.prototype._decRefCount = function () {
  31428. this._refCount--;
  31429. if (this._refCount <= 0) {
  31430. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  31431. }
  31432. return this._refCount;
  31433. };
  31434. PostProcessRenderPass.prototype._update = function () {
  31435. this.setRenderList(this._renderList);
  31436. };
  31437. // public
  31438. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  31439. this._renderTexture.renderList = renderList;
  31440. };
  31441. PostProcessRenderPass.prototype.getRenderTexture = function () {
  31442. return this._renderTexture;
  31443. };
  31444. return PostProcessRenderPass;
  31445. }());
  31446. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  31447. })(BABYLON || (BABYLON = {}));
  31448. var BABYLON;
  31449. (function (BABYLON) {
  31450. var PostProcessRenderEffect = (function () {
  31451. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  31452. this._engine = engine;
  31453. this._name = name;
  31454. this._singleInstance = singleInstance || true;
  31455. this._getPostProcess = getPostProcess;
  31456. this._cameras = [];
  31457. this._indicesForCamera = [];
  31458. this._postProcesses = {};
  31459. this._renderPasses = {};
  31460. this._renderEffectAsPasses = {};
  31461. }
  31462. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  31463. get: function () {
  31464. for (var index in this._postProcesses) {
  31465. if (!this._postProcesses[index].isSupported) {
  31466. return false;
  31467. }
  31468. }
  31469. return true;
  31470. },
  31471. enumerable: true,
  31472. configurable: true
  31473. });
  31474. PostProcessRenderEffect.prototype._update = function () {
  31475. for (var renderPassName in this._renderPasses) {
  31476. this._renderPasses[renderPassName]._update();
  31477. }
  31478. };
  31479. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  31480. this._renderPasses[renderPass._name] = renderPass;
  31481. this._linkParameters();
  31482. };
  31483. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  31484. delete this._renderPasses[renderPass._name];
  31485. this._linkParameters();
  31486. };
  31487. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  31488. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  31489. this._linkParameters();
  31490. };
  31491. PostProcessRenderEffect.prototype.getPass = function (passName) {
  31492. for (var renderPassName in this._renderPasses) {
  31493. if (renderPassName === passName) {
  31494. return this._renderPasses[passName];
  31495. }
  31496. }
  31497. };
  31498. PostProcessRenderEffect.prototype.emptyPasses = function () {
  31499. this._renderPasses = {};
  31500. this._linkParameters();
  31501. };
  31502. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  31503. var cameraKey;
  31504. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31505. for (var i = 0; i < _cam.length; i++) {
  31506. var camera = _cam[i];
  31507. var cameraName = camera.name;
  31508. if (this._singleInstance) {
  31509. cameraKey = 0;
  31510. }
  31511. else {
  31512. cameraKey = cameraName;
  31513. }
  31514. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  31515. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  31516. if (!this._indicesForCamera[cameraName]) {
  31517. this._indicesForCamera[cameraName] = [];
  31518. }
  31519. this._indicesForCamera[cameraName].push(index);
  31520. if (this._cameras.indexOf(camera) === -1) {
  31521. this._cameras[cameraName] = camera;
  31522. }
  31523. for (var passName in this._renderPasses) {
  31524. this._renderPasses[passName]._incRefCount();
  31525. }
  31526. }
  31527. this._linkParameters();
  31528. };
  31529. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  31530. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31531. for (var i = 0; i < _cam.length; i++) {
  31532. var camera = _cam[i];
  31533. var cameraName = camera.name;
  31534. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  31535. var index = this._cameras.indexOf(cameraName);
  31536. this._indicesForCamera.splice(index, 1);
  31537. this._cameras.splice(index, 1);
  31538. for (var passName in this._renderPasses) {
  31539. this._renderPasses[passName]._decRefCount();
  31540. }
  31541. }
  31542. };
  31543. PostProcessRenderEffect.prototype._enable = function (cameras) {
  31544. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31545. for (var i = 0; i < _cam.length; i++) {
  31546. var camera = _cam[i];
  31547. var cameraName = camera.name;
  31548. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  31549. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  31550. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  31551. }
  31552. }
  31553. for (var passName in this._renderPasses) {
  31554. this._renderPasses[passName]._incRefCount();
  31555. }
  31556. }
  31557. };
  31558. PostProcessRenderEffect.prototype._disable = function (cameras) {
  31559. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31560. for (var i = 0; i < _cam.length; i++) {
  31561. var camera = _cam[i];
  31562. var cameraName = camera.Name;
  31563. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  31564. for (var passName in this._renderPasses) {
  31565. this._renderPasses[passName]._decRefCount();
  31566. }
  31567. }
  31568. };
  31569. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  31570. if (this._singleInstance) {
  31571. return this._postProcesses[0];
  31572. }
  31573. else {
  31574. return this._postProcesses[camera.name];
  31575. }
  31576. };
  31577. PostProcessRenderEffect.prototype._linkParameters = function () {
  31578. var _this = this;
  31579. for (var index in this._postProcesses) {
  31580. if (this.applyParameters) {
  31581. this.applyParameters(this._postProcesses[index]);
  31582. }
  31583. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  31584. _this._linkTextures(effect);
  31585. });
  31586. }
  31587. };
  31588. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  31589. for (var renderPassName in this._renderPasses) {
  31590. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  31591. }
  31592. for (var renderEffectName in this._renderEffectAsPasses) {
  31593. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  31594. }
  31595. };
  31596. return PostProcessRenderEffect;
  31597. }());
  31598. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  31599. })(BABYLON || (BABYLON = {}));
  31600. var BABYLON;
  31601. (function (BABYLON) {
  31602. var PostProcessRenderPipeline = (function () {
  31603. function PostProcessRenderPipeline(engine, name) {
  31604. this._engine = engine;
  31605. this._name = name;
  31606. this._renderEffects = {};
  31607. this._renderEffectsForIsolatedPass = {};
  31608. this._cameras = [];
  31609. }
  31610. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  31611. get: function () {
  31612. for (var renderEffectName in this._renderEffects) {
  31613. if (!this._renderEffects[renderEffectName].isSupported) {
  31614. return false;
  31615. }
  31616. }
  31617. return true;
  31618. },
  31619. enumerable: true,
  31620. configurable: true
  31621. });
  31622. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  31623. this._renderEffects[renderEffect._name] = renderEffect;
  31624. };
  31625. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  31626. var renderEffects = this._renderEffects[renderEffectName];
  31627. if (!renderEffects) {
  31628. return;
  31629. }
  31630. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  31631. };
  31632. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  31633. var renderEffects = this._renderEffects[renderEffectName];
  31634. if (!renderEffects) {
  31635. return;
  31636. }
  31637. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  31638. };
  31639. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  31640. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31641. var indicesToDelete = [];
  31642. var i;
  31643. for (i = 0; i < _cam.length; i++) {
  31644. var camera = _cam[i];
  31645. var cameraName = camera.name;
  31646. if (this._cameras.indexOf(camera) === -1) {
  31647. this._cameras[cameraName] = camera;
  31648. }
  31649. else if (unique) {
  31650. indicesToDelete.push(i);
  31651. }
  31652. }
  31653. for (i = 0; i < indicesToDelete.length; i++) {
  31654. cameras.splice(indicesToDelete[i], 1);
  31655. }
  31656. for (var renderEffectName in this._renderEffects) {
  31657. this._renderEffects[renderEffectName]._attachCameras(_cam);
  31658. }
  31659. };
  31660. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  31661. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31662. for (var renderEffectName in this._renderEffects) {
  31663. this._renderEffects[renderEffectName]._detachCameras(_cam);
  31664. }
  31665. for (var i = 0; i < _cam.length; i++) {
  31666. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  31667. }
  31668. };
  31669. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  31670. var _this = this;
  31671. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31672. var pass = null;
  31673. var renderEffectName;
  31674. for (renderEffectName in this._renderEffects) {
  31675. pass = this._renderEffects[renderEffectName].getPass(passName);
  31676. if (pass != null) {
  31677. break;
  31678. }
  31679. }
  31680. if (pass === null) {
  31681. return;
  31682. }
  31683. for (renderEffectName in this._renderEffects) {
  31684. this._renderEffects[renderEffectName]._disable(_cam);
  31685. }
  31686. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  31687. for (var i = 0; i < _cam.length; i++) {
  31688. var camera = _cam[i];
  31689. var cameraName = camera.name;
  31690. 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); });
  31691. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  31692. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  31693. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  31694. }
  31695. };
  31696. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  31697. var _this = this;
  31698. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31699. for (var i = 0; i < _cam.length; i++) {
  31700. var camera = _cam[i];
  31701. var cameraName = camera.name;
  31702. 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); });
  31703. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  31704. }
  31705. for (var renderEffectName in this._renderEffects) {
  31706. this._renderEffects[renderEffectName]._enable(_cam);
  31707. }
  31708. };
  31709. PostProcessRenderPipeline.prototype._update = function () {
  31710. for (var renderEffectName in this._renderEffects) {
  31711. this._renderEffects[renderEffectName]._update();
  31712. }
  31713. for (var i = 0; i < this._cameras.length; i++) {
  31714. var cameraName = this._cameras[i].name;
  31715. if (this._renderEffectsForIsolatedPass[cameraName]) {
  31716. this._renderEffectsForIsolatedPass[cameraName]._update();
  31717. }
  31718. }
  31719. };
  31720. PostProcessRenderPipeline.prototype.dispose = function () {
  31721. // Must be implemented by children
  31722. };
  31723. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  31724. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  31725. return PostProcessRenderPipeline;
  31726. }());
  31727. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  31728. })(BABYLON || (BABYLON = {}));
  31729. var BABYLON;
  31730. (function (BABYLON) {
  31731. var PostProcessRenderPipelineManager = (function () {
  31732. function PostProcessRenderPipelineManager() {
  31733. this._renderPipelines = {};
  31734. }
  31735. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  31736. this._renderPipelines[renderPipeline._name] = renderPipeline;
  31737. };
  31738. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  31739. var renderPipeline = this._renderPipelines[renderPipelineName];
  31740. if (!renderPipeline) {
  31741. return;
  31742. }
  31743. renderPipeline._attachCameras(cameras, unique);
  31744. };
  31745. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  31746. var renderPipeline = this._renderPipelines[renderPipelineName];
  31747. if (!renderPipeline) {
  31748. return;
  31749. }
  31750. renderPipeline._detachCameras(cameras);
  31751. };
  31752. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  31753. var renderPipeline = this._renderPipelines[renderPipelineName];
  31754. if (!renderPipeline) {
  31755. return;
  31756. }
  31757. renderPipeline._enableEffect(renderEffectName, cameras);
  31758. };
  31759. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  31760. var renderPipeline = this._renderPipelines[renderPipelineName];
  31761. if (!renderPipeline) {
  31762. return;
  31763. }
  31764. renderPipeline._disableEffect(renderEffectName, cameras);
  31765. };
  31766. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  31767. var renderPipeline = this._renderPipelines[renderPipelineName];
  31768. if (!renderPipeline) {
  31769. return;
  31770. }
  31771. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  31772. };
  31773. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  31774. var renderPipeline = this._renderPipelines[renderPipelineName];
  31775. if (!renderPipeline) {
  31776. return;
  31777. }
  31778. renderPipeline._disableDisplayOnlyPass(cameras);
  31779. };
  31780. PostProcessRenderPipelineManager.prototype.update = function () {
  31781. for (var renderPipelineName in this._renderPipelines) {
  31782. var pipeline = this._renderPipelines[renderPipelineName];
  31783. if (!pipeline.isSupported) {
  31784. pipeline.dispose();
  31785. delete this._renderPipelines[renderPipelineName];
  31786. }
  31787. else {
  31788. pipeline._update();
  31789. }
  31790. }
  31791. };
  31792. return PostProcessRenderPipelineManager;
  31793. }());
  31794. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  31795. })(BABYLON || (BABYLON = {}));
  31796. var BABYLON;
  31797. (function (BABYLON) {
  31798. var BoundingBoxRenderer = (function () {
  31799. function BoundingBoxRenderer(scene) {
  31800. this.frontColor = new BABYLON.Color3(1, 1, 1);
  31801. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  31802. this.showBackLines = true;
  31803. this.renderList = new BABYLON.SmartArray(32);
  31804. this._vertexBuffers = {};
  31805. this._scene = scene;
  31806. }
  31807. BoundingBoxRenderer.prototype._prepareRessources = function () {
  31808. if (this._colorShader) {
  31809. return;
  31810. }
  31811. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  31812. attributes: [BABYLON.VertexBuffer.PositionKind],
  31813. uniforms: ["worldViewProjection", "color"]
  31814. });
  31815. var engine = this._scene.getEngine();
  31816. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  31817. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  31818. 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]);
  31819. };
  31820. BoundingBoxRenderer.prototype.reset = function () {
  31821. this.renderList.reset();
  31822. };
  31823. BoundingBoxRenderer.prototype.render = function () {
  31824. if (this.renderList.length === 0) {
  31825. return;
  31826. }
  31827. this._prepareRessources();
  31828. if (!this._colorShader.isReady()) {
  31829. return;
  31830. }
  31831. var engine = this._scene.getEngine();
  31832. engine.setDepthWrite(false);
  31833. this._colorShader._preBind();
  31834. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  31835. var boundingBox = this.renderList.data[boundingBoxIndex];
  31836. var min = boundingBox.minimum;
  31837. var max = boundingBox.maximum;
  31838. var diff = max.subtract(min);
  31839. var median = min.add(diff.scale(0.5));
  31840. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  31841. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  31842. .multiply(boundingBox.getWorldMatrix());
  31843. // VBOs
  31844. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  31845. if (this.showBackLines) {
  31846. // Back
  31847. engine.setDepthFunctionToGreaterOrEqual();
  31848. this._scene.resetCachedMaterial();
  31849. this._colorShader.setColor4("color", this.backColor.toColor4());
  31850. this._colorShader.bind(worldMatrix);
  31851. // Draw order
  31852. engine.draw(false, 0, 24);
  31853. }
  31854. // Front
  31855. engine.setDepthFunctionToLess();
  31856. this._scene.resetCachedMaterial();
  31857. this._colorShader.setColor4("color", this.frontColor.toColor4());
  31858. this._colorShader.bind(worldMatrix);
  31859. // Draw order
  31860. engine.draw(false, 0, 24);
  31861. }
  31862. this._colorShader.unbind();
  31863. engine.setDepthFunctionToLessOrEqual();
  31864. engine.setDepthWrite(true);
  31865. };
  31866. BoundingBoxRenderer.prototype.dispose = function () {
  31867. if (!this._colorShader) {
  31868. return;
  31869. }
  31870. this._colorShader.dispose();
  31871. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31872. if (buffer) {
  31873. buffer.dispose();
  31874. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31875. }
  31876. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31877. };
  31878. return BoundingBoxRenderer;
  31879. }());
  31880. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  31881. })(BABYLON || (BABYLON = {}));
  31882. var BABYLON;
  31883. (function (BABYLON) {
  31884. var Condition = (function () {
  31885. function Condition(actionManager) {
  31886. this._actionManager = actionManager;
  31887. }
  31888. Condition.prototype.isValid = function () {
  31889. return true;
  31890. };
  31891. Condition.prototype._getProperty = function (propertyPath) {
  31892. return this._actionManager._getProperty(propertyPath);
  31893. };
  31894. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  31895. return this._actionManager._getEffectiveTarget(target, propertyPath);
  31896. };
  31897. Condition.prototype.serialize = function () {
  31898. };
  31899. Condition.prototype._serialize = function (serializedCondition) {
  31900. return {
  31901. type: 2,
  31902. children: [],
  31903. name: serializedCondition.name,
  31904. properties: serializedCondition.properties
  31905. };
  31906. };
  31907. return Condition;
  31908. }());
  31909. BABYLON.Condition = Condition;
  31910. var ValueCondition = (function (_super) {
  31911. __extends(ValueCondition, _super);
  31912. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  31913. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  31914. _super.call(this, actionManager);
  31915. this.propertyPath = propertyPath;
  31916. this.value = value;
  31917. this.operator = operator;
  31918. this._target = target;
  31919. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  31920. this._property = this._getProperty(this.propertyPath);
  31921. }
  31922. Object.defineProperty(ValueCondition, "IsEqual", {
  31923. get: function () {
  31924. return ValueCondition._IsEqual;
  31925. },
  31926. enumerable: true,
  31927. configurable: true
  31928. });
  31929. Object.defineProperty(ValueCondition, "IsDifferent", {
  31930. get: function () {
  31931. return ValueCondition._IsDifferent;
  31932. },
  31933. enumerable: true,
  31934. configurable: true
  31935. });
  31936. Object.defineProperty(ValueCondition, "IsGreater", {
  31937. get: function () {
  31938. return ValueCondition._IsGreater;
  31939. },
  31940. enumerable: true,
  31941. configurable: true
  31942. });
  31943. Object.defineProperty(ValueCondition, "IsLesser", {
  31944. get: function () {
  31945. return ValueCondition._IsLesser;
  31946. },
  31947. enumerable: true,
  31948. configurable: true
  31949. });
  31950. // Methods
  31951. ValueCondition.prototype.isValid = function () {
  31952. switch (this.operator) {
  31953. case ValueCondition.IsGreater:
  31954. return this._effectiveTarget[this._property] > this.value;
  31955. case ValueCondition.IsLesser:
  31956. return this._effectiveTarget[this._property] < this.value;
  31957. case ValueCondition.IsEqual:
  31958. case ValueCondition.IsDifferent:
  31959. var check;
  31960. if (this.value.equals) {
  31961. check = this.value.equals(this._effectiveTarget[this._property]);
  31962. }
  31963. else {
  31964. check = this.value === this._effectiveTarget[this._property];
  31965. }
  31966. return this.operator === ValueCondition.IsEqual ? check : !check;
  31967. }
  31968. return false;
  31969. };
  31970. ValueCondition.prototype.serialize = function () {
  31971. return this._serialize({
  31972. name: "ValueCondition",
  31973. properties: [
  31974. BABYLON.Action._GetTargetProperty(this._target),
  31975. { name: "propertyPath", value: this.propertyPath },
  31976. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  31977. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  31978. ]
  31979. });
  31980. };
  31981. ValueCondition.GetOperatorName = function (operator) {
  31982. switch (operator) {
  31983. case ValueCondition._IsEqual: return "IsEqual";
  31984. case ValueCondition._IsDifferent: return "IsDifferent";
  31985. case ValueCondition._IsGreater: return "IsGreater";
  31986. case ValueCondition._IsLesser: return "IsLesser";
  31987. default: return "";
  31988. }
  31989. };
  31990. // Statics
  31991. ValueCondition._IsEqual = 0;
  31992. ValueCondition._IsDifferent = 1;
  31993. ValueCondition._IsGreater = 2;
  31994. ValueCondition._IsLesser = 3;
  31995. return ValueCondition;
  31996. }(Condition));
  31997. BABYLON.ValueCondition = ValueCondition;
  31998. var PredicateCondition = (function (_super) {
  31999. __extends(PredicateCondition, _super);
  32000. function PredicateCondition(actionManager, predicate) {
  32001. _super.call(this, actionManager);
  32002. this.predicate = predicate;
  32003. }
  32004. PredicateCondition.prototype.isValid = function () {
  32005. return this.predicate();
  32006. };
  32007. return PredicateCondition;
  32008. }(Condition));
  32009. BABYLON.PredicateCondition = PredicateCondition;
  32010. var StateCondition = (function (_super) {
  32011. __extends(StateCondition, _super);
  32012. function StateCondition(actionManager, target, value) {
  32013. _super.call(this, actionManager);
  32014. this.value = value;
  32015. this._target = target;
  32016. }
  32017. // Methods
  32018. StateCondition.prototype.isValid = function () {
  32019. return this._target.state === this.value;
  32020. };
  32021. StateCondition.prototype.serialize = function () {
  32022. return this._serialize({
  32023. name: "StateCondition",
  32024. properties: [
  32025. BABYLON.Action._GetTargetProperty(this._target),
  32026. { name: "value", value: this.value }
  32027. ]
  32028. });
  32029. };
  32030. return StateCondition;
  32031. }(Condition));
  32032. BABYLON.StateCondition = StateCondition;
  32033. })(BABYLON || (BABYLON = {}));
  32034. var BABYLON;
  32035. (function (BABYLON) {
  32036. var Action = (function () {
  32037. function Action(triggerOptions, condition) {
  32038. this.triggerOptions = triggerOptions;
  32039. if (triggerOptions.parameter) {
  32040. this.trigger = triggerOptions.trigger;
  32041. this._triggerParameter = triggerOptions.parameter;
  32042. }
  32043. else {
  32044. this.trigger = triggerOptions;
  32045. }
  32046. this._nextActiveAction = this;
  32047. this._condition = condition;
  32048. }
  32049. // Methods
  32050. Action.prototype._prepare = function () {
  32051. };
  32052. Action.prototype.getTriggerParameter = function () {
  32053. return this._triggerParameter;
  32054. };
  32055. Action.prototype._executeCurrent = function (evt) {
  32056. if (this._nextActiveAction._condition) {
  32057. var condition = this._nextActiveAction._condition;
  32058. var currentRenderId = this._actionManager.getScene().getRenderId();
  32059. // We cache the current evaluation for the current frame
  32060. if (condition._evaluationId === currentRenderId) {
  32061. if (!condition._currentResult) {
  32062. return;
  32063. }
  32064. }
  32065. else {
  32066. condition._evaluationId = currentRenderId;
  32067. if (!condition.isValid()) {
  32068. condition._currentResult = false;
  32069. return;
  32070. }
  32071. condition._currentResult = true;
  32072. }
  32073. }
  32074. this._nextActiveAction.execute(evt);
  32075. this.skipToNextActiveAction();
  32076. };
  32077. Action.prototype.execute = function (evt) {
  32078. };
  32079. Action.prototype.skipToNextActiveAction = function () {
  32080. if (this._nextActiveAction._child) {
  32081. if (!this._nextActiveAction._child._actionManager) {
  32082. this._nextActiveAction._child._actionManager = this._actionManager;
  32083. }
  32084. this._nextActiveAction = this._nextActiveAction._child;
  32085. }
  32086. else {
  32087. this._nextActiveAction = this;
  32088. }
  32089. };
  32090. Action.prototype.then = function (action) {
  32091. this._child = action;
  32092. action._actionManager = this._actionManager;
  32093. action._prepare();
  32094. return action;
  32095. };
  32096. Action.prototype._getProperty = function (propertyPath) {
  32097. return this._actionManager._getProperty(propertyPath);
  32098. };
  32099. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  32100. return this._actionManager._getEffectiveTarget(target, propertyPath);
  32101. };
  32102. Action.prototype.serialize = function (parent) {
  32103. };
  32104. // Called by BABYLON.Action objects in serialize(...). Internal use
  32105. Action.prototype._serialize = function (serializedAction, parent) {
  32106. var serializationObject = {
  32107. type: 1,
  32108. children: [],
  32109. name: serializedAction.name,
  32110. properties: serializedAction.properties || []
  32111. };
  32112. // Serialize child
  32113. if (this._child) {
  32114. this._child.serialize(serializationObject);
  32115. }
  32116. // Check if "this" has a condition
  32117. if (this._condition) {
  32118. var serializedCondition = this._condition.serialize();
  32119. serializedCondition.children.push(serializationObject);
  32120. if (parent) {
  32121. parent.children.push(serializedCondition);
  32122. }
  32123. return serializedCondition;
  32124. }
  32125. if (parent) {
  32126. parent.children.push(serializationObject);
  32127. }
  32128. return serializationObject;
  32129. };
  32130. Action._SerializeValueAsString = function (value) {
  32131. if (typeof value === "number") {
  32132. return value.toString();
  32133. }
  32134. if (typeof value === "boolean") {
  32135. return value ? "true" : "false";
  32136. }
  32137. if (value instanceof BABYLON.Vector2) {
  32138. return value.x + ", " + value.y;
  32139. }
  32140. if (value instanceof BABYLON.Vector3) {
  32141. return value.x + ", " + value.y + ", " + value.z;
  32142. }
  32143. if (value instanceof BABYLON.Color3) {
  32144. return value.r + ", " + value.g + ", " + value.b;
  32145. }
  32146. if (value instanceof BABYLON.Color4) {
  32147. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  32148. }
  32149. return value; // string
  32150. };
  32151. Action._GetTargetProperty = function (target) {
  32152. return {
  32153. name: "target",
  32154. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  32155. : target instanceof BABYLON.Light ? "LightProperties"
  32156. : target instanceof BABYLON.Camera ? "CameraProperties"
  32157. : "SceneProperties",
  32158. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  32159. };
  32160. };
  32161. return Action;
  32162. }());
  32163. BABYLON.Action = Action;
  32164. })(BABYLON || (BABYLON = {}));
  32165. var BABYLON;
  32166. (function (BABYLON) {
  32167. /**
  32168. * ActionEvent is the event beint sent when an action is triggered.
  32169. */
  32170. var ActionEvent = (function () {
  32171. /**
  32172. * @constructor
  32173. * @param source The mesh or sprite that triggered the action.
  32174. * @param pointerX The X mouse cursor position at the time of the event
  32175. * @param pointerY The Y mouse cursor position at the time of the event
  32176. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  32177. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  32178. */
  32179. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  32180. this.source = source;
  32181. this.pointerX = pointerX;
  32182. this.pointerY = pointerY;
  32183. this.meshUnderPointer = meshUnderPointer;
  32184. this.sourceEvent = sourceEvent;
  32185. this.additionalData = additionalData;
  32186. }
  32187. /**
  32188. * Helper function to auto-create an ActionEvent from a source mesh.
  32189. * @param source The source mesh that triggered the event
  32190. * @param evt {Event} The original (browser) event
  32191. */
  32192. ActionEvent.CreateNew = function (source, evt, additionalData) {
  32193. var scene = source.getScene();
  32194. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  32195. };
  32196. /**
  32197. * Helper function to auto-create an ActionEvent from a source mesh.
  32198. * @param source The source sprite that triggered the event
  32199. * @param scene Scene associated with the sprite
  32200. * @param evt {Event} The original (browser) event
  32201. */
  32202. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  32203. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  32204. };
  32205. /**
  32206. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  32207. * @param scene the scene where the event occurred
  32208. * @param evt {Event} The original (browser) event
  32209. */
  32210. ActionEvent.CreateNewFromScene = function (scene, evt) {
  32211. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  32212. };
  32213. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  32214. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  32215. };
  32216. return ActionEvent;
  32217. }());
  32218. BABYLON.ActionEvent = ActionEvent;
  32219. /**
  32220. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  32221. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  32222. */
  32223. var ActionManager = (function () {
  32224. function ActionManager(scene) {
  32225. // Members
  32226. this.actions = new Array();
  32227. this._scene = scene;
  32228. scene._actionManagers.push(this);
  32229. }
  32230. Object.defineProperty(ActionManager, "NothingTrigger", {
  32231. get: function () {
  32232. return ActionManager._NothingTrigger;
  32233. },
  32234. enumerable: true,
  32235. configurable: true
  32236. });
  32237. Object.defineProperty(ActionManager, "OnPickTrigger", {
  32238. get: function () {
  32239. return ActionManager._OnPickTrigger;
  32240. },
  32241. enumerable: true,
  32242. configurable: true
  32243. });
  32244. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  32245. get: function () {
  32246. return ActionManager._OnLeftPickTrigger;
  32247. },
  32248. enumerable: true,
  32249. configurable: true
  32250. });
  32251. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  32252. get: function () {
  32253. return ActionManager._OnRightPickTrigger;
  32254. },
  32255. enumerable: true,
  32256. configurable: true
  32257. });
  32258. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  32259. get: function () {
  32260. return ActionManager._OnCenterPickTrigger;
  32261. },
  32262. enumerable: true,
  32263. configurable: true
  32264. });
  32265. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  32266. get: function () {
  32267. return ActionManager._OnPickDownTrigger;
  32268. },
  32269. enumerable: true,
  32270. configurable: true
  32271. });
  32272. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  32273. get: function () {
  32274. return ActionManager._OnPickUpTrigger;
  32275. },
  32276. enumerable: true,
  32277. configurable: true
  32278. });
  32279. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  32280. /// This trigger will only be raised if you also declared a OnPickDown
  32281. get: function () {
  32282. return ActionManager._OnPickOutTrigger;
  32283. },
  32284. enumerable: true,
  32285. configurable: true
  32286. });
  32287. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  32288. get: function () {
  32289. return ActionManager._OnLongPressTrigger;
  32290. },
  32291. enumerable: true,
  32292. configurable: true
  32293. });
  32294. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  32295. get: function () {
  32296. return ActionManager._OnPointerOverTrigger;
  32297. },
  32298. enumerable: true,
  32299. configurable: true
  32300. });
  32301. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  32302. get: function () {
  32303. return ActionManager._OnPointerOutTrigger;
  32304. },
  32305. enumerable: true,
  32306. configurable: true
  32307. });
  32308. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  32309. get: function () {
  32310. return ActionManager._OnEveryFrameTrigger;
  32311. },
  32312. enumerable: true,
  32313. configurable: true
  32314. });
  32315. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  32316. get: function () {
  32317. return ActionManager._OnIntersectionEnterTrigger;
  32318. },
  32319. enumerable: true,
  32320. configurable: true
  32321. });
  32322. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  32323. get: function () {
  32324. return ActionManager._OnIntersectionExitTrigger;
  32325. },
  32326. enumerable: true,
  32327. configurable: true
  32328. });
  32329. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  32330. get: function () {
  32331. return ActionManager._OnKeyDownTrigger;
  32332. },
  32333. enumerable: true,
  32334. configurable: true
  32335. });
  32336. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  32337. get: function () {
  32338. return ActionManager._OnKeyUpTrigger;
  32339. },
  32340. enumerable: true,
  32341. configurable: true
  32342. });
  32343. // Methods
  32344. ActionManager.prototype.dispose = function () {
  32345. var index = this._scene._actionManagers.indexOf(this);
  32346. if (index > -1) {
  32347. this._scene._actionManagers.splice(index, 1);
  32348. }
  32349. };
  32350. ActionManager.prototype.getScene = function () {
  32351. return this._scene;
  32352. };
  32353. /**
  32354. * Does this action manager handles actions of any of the given triggers
  32355. * @param {number[]} triggers - the triggers to be tested
  32356. * @return {boolean} whether one (or more) of the triggers is handeled
  32357. */
  32358. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  32359. for (var index = 0; index < this.actions.length; index++) {
  32360. var action = this.actions[index];
  32361. if (triggers.indexOf(action.trigger) > -1) {
  32362. return true;
  32363. }
  32364. }
  32365. return false;
  32366. };
  32367. /**
  32368. * Does this action manager handles actions of a given trigger
  32369. * @param {number} trigger - the trigger to be tested
  32370. * @return {boolean} whether the trigger is handeled
  32371. */
  32372. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  32373. for (var index = 0; index < this.actions.length; index++) {
  32374. var action = this.actions[index];
  32375. if (action.trigger === trigger) {
  32376. return true;
  32377. }
  32378. }
  32379. return false;
  32380. };
  32381. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  32382. /**
  32383. * Does this action manager has pointer triggers
  32384. * @return {boolean} whether or not it has pointer triggers
  32385. */
  32386. get: function () {
  32387. for (var index = 0; index < this.actions.length; index++) {
  32388. var action = this.actions[index];
  32389. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  32390. return true;
  32391. }
  32392. }
  32393. return false;
  32394. },
  32395. enumerable: true,
  32396. configurable: true
  32397. });
  32398. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  32399. /**
  32400. * Does this action manager has pick triggers
  32401. * @return {boolean} whether or not it has pick triggers
  32402. */
  32403. get: function () {
  32404. for (var index = 0; index < this.actions.length; index++) {
  32405. var action = this.actions[index];
  32406. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  32407. return true;
  32408. }
  32409. }
  32410. return false;
  32411. },
  32412. enumerable: true,
  32413. configurable: true
  32414. });
  32415. /**
  32416. * Registers an action to this action manager
  32417. * @param {BABYLON.Action} action - the action to be registered
  32418. * @return {BABYLON.Action} the action amended (prepared) after registration
  32419. */
  32420. ActionManager.prototype.registerAction = function (action) {
  32421. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  32422. if (this.getScene().actionManager !== this) {
  32423. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  32424. return null;
  32425. }
  32426. }
  32427. this.actions.push(action);
  32428. action._actionManager = this;
  32429. action._prepare();
  32430. return action;
  32431. };
  32432. /**
  32433. * Process a specific trigger
  32434. * @param {number} trigger - the trigger to process
  32435. * @param evt {BABYLON.ActionEvent} the event details to be processed
  32436. */
  32437. ActionManager.prototype.processTrigger = function (trigger, evt) {
  32438. for (var index = 0; index < this.actions.length; index++) {
  32439. var action = this.actions[index];
  32440. if (action.trigger === trigger) {
  32441. if (trigger === ActionManager.OnKeyUpTrigger
  32442. || trigger === ActionManager.OnKeyDownTrigger) {
  32443. var parameter = action.getTriggerParameter();
  32444. if (parameter) {
  32445. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  32446. var actualkey = String.fromCharCode(unicode).toLowerCase();
  32447. if (actualkey !== parameter.toLowerCase()) {
  32448. continue;
  32449. }
  32450. }
  32451. }
  32452. action._executeCurrent(evt);
  32453. }
  32454. }
  32455. };
  32456. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  32457. var properties = propertyPath.split(".");
  32458. for (var index = 0; index < properties.length - 1; index++) {
  32459. target = target[properties[index]];
  32460. }
  32461. return target;
  32462. };
  32463. ActionManager.prototype._getProperty = function (propertyPath) {
  32464. var properties = propertyPath.split(".");
  32465. return properties[properties.length - 1];
  32466. };
  32467. ActionManager.prototype.serialize = function (name) {
  32468. var root = {
  32469. children: [],
  32470. name: name,
  32471. type: 3,
  32472. properties: [] // Empty for root but required
  32473. };
  32474. for (var i = 0; i < this.actions.length; i++) {
  32475. var triggerObject = {
  32476. type: 0,
  32477. children: [],
  32478. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  32479. properties: []
  32480. };
  32481. var triggerOptions = this.actions[i].triggerOptions;
  32482. if (triggerOptions && typeof triggerOptions !== "number") {
  32483. if (triggerOptions.parameter instanceof BABYLON.Node) {
  32484. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  32485. }
  32486. else {
  32487. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  32488. }
  32489. }
  32490. // Serialize child action, recursively
  32491. this.actions[i].serialize(triggerObject);
  32492. // Add serialized trigger
  32493. root.children.push(triggerObject);
  32494. }
  32495. return root;
  32496. };
  32497. ActionManager.Parse = function (parsedActions, object, scene) {
  32498. var actionManager = new BABYLON.ActionManager(scene);
  32499. if (object === null)
  32500. scene.actionManager = actionManager;
  32501. else
  32502. object.actionManager = actionManager;
  32503. // instanciate a new object
  32504. var instanciate = function (name, params) {
  32505. var newInstance = Object.create(BABYLON[name].prototype);
  32506. newInstance.constructor.apply(newInstance, params);
  32507. return newInstance;
  32508. };
  32509. var parseParameter = function (name, value, target, propertyPath) {
  32510. if (propertyPath === null) {
  32511. // String, boolean or float
  32512. var floatValue = parseFloat(value);
  32513. if (value === "true" || value === "false")
  32514. return value === "true";
  32515. else
  32516. return isNaN(floatValue) ? value : floatValue;
  32517. }
  32518. var effectiveTarget = propertyPath.split(".");
  32519. var values = value.split(",");
  32520. // Get effective Target
  32521. for (var i = 0; i < effectiveTarget.length; i++) {
  32522. target = target[effectiveTarget[i]];
  32523. }
  32524. // Return appropriate value with its type
  32525. if (typeof (target) === "boolean")
  32526. return values[0] === "true";
  32527. if (typeof (target) === "string")
  32528. return values[0];
  32529. // Parameters with multiple values such as Vector3 etc.
  32530. var split = new Array();
  32531. for (var i = 0; i < values.length; i++)
  32532. split.push(parseFloat(values[i]));
  32533. if (target instanceof BABYLON.Vector3)
  32534. return BABYLON.Vector3.FromArray(split);
  32535. if (target instanceof BABYLON.Vector4)
  32536. return BABYLON.Vector4.FromArray(split);
  32537. if (target instanceof BABYLON.Color3)
  32538. return BABYLON.Color3.FromArray(split);
  32539. if (target instanceof BABYLON.Color4)
  32540. return BABYLON.Color4.FromArray(split);
  32541. return parseFloat(values[0]);
  32542. };
  32543. // traverse graph per trigger
  32544. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  32545. if (combineArray === void 0) { combineArray = null; }
  32546. if (parsedAction.detached)
  32547. return;
  32548. var parameters = new Array();
  32549. var target = null;
  32550. var propertyPath = null;
  32551. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  32552. // Parameters
  32553. if (parsedAction.type === 2)
  32554. parameters.push(actionManager);
  32555. else
  32556. parameters.push(trigger);
  32557. if (combine) {
  32558. var actions = new Array();
  32559. for (var j = 0; j < parsedAction.combine.length; j++) {
  32560. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  32561. }
  32562. parameters.push(actions);
  32563. }
  32564. else {
  32565. for (var i = 0; i < parsedAction.properties.length; i++) {
  32566. var value = parsedAction.properties[i].value;
  32567. var name = parsedAction.properties[i].name;
  32568. var targetType = parsedAction.properties[i].targetType;
  32569. if (name === "target")
  32570. if (targetType !== null && targetType === "SceneProperties")
  32571. value = target = scene;
  32572. else
  32573. value = target = scene.getNodeByName(value);
  32574. else if (name === "parent")
  32575. value = scene.getNodeByName(value);
  32576. else if (name === "sound")
  32577. value = scene.getSoundByName(value);
  32578. else if (name !== "propertyPath") {
  32579. if (parsedAction.type === 2 && name === "operator")
  32580. value = BABYLON.ValueCondition[value];
  32581. else
  32582. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  32583. }
  32584. else {
  32585. propertyPath = value;
  32586. }
  32587. parameters.push(value);
  32588. }
  32589. }
  32590. if (combineArray === null) {
  32591. parameters.push(condition);
  32592. }
  32593. else {
  32594. parameters.push(null);
  32595. }
  32596. // If interpolate value action
  32597. if (parsedAction.name === "InterpolateValueAction") {
  32598. var param = parameters[parameters.length - 2];
  32599. parameters[parameters.length - 1] = param;
  32600. parameters[parameters.length - 2] = condition;
  32601. }
  32602. // Action or condition(s) and not CombineAction
  32603. var newAction = instanciate(parsedAction.name, parameters);
  32604. if (newAction instanceof BABYLON.Condition && condition !== null) {
  32605. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  32606. if (action)
  32607. action.then(nothing);
  32608. else
  32609. actionManager.registerAction(nothing);
  32610. action = nothing;
  32611. }
  32612. if (combineArray === null) {
  32613. if (newAction instanceof BABYLON.Condition) {
  32614. condition = newAction;
  32615. newAction = action;
  32616. }
  32617. else {
  32618. condition = null;
  32619. if (action)
  32620. action.then(newAction);
  32621. else
  32622. actionManager.registerAction(newAction);
  32623. }
  32624. }
  32625. else {
  32626. combineArray.push(newAction);
  32627. }
  32628. for (var i = 0; i < parsedAction.children.length; i++)
  32629. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  32630. };
  32631. // triggers
  32632. for (var i = 0; i < parsedActions.children.length; i++) {
  32633. var triggerParams;
  32634. var trigger = parsedActions.children[i];
  32635. if (trigger.properties.length > 0) {
  32636. var param = trigger.properties[0].value;
  32637. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  32638. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  32639. }
  32640. else
  32641. triggerParams = BABYLON.ActionManager[trigger.name];
  32642. for (var j = 0; j < trigger.children.length; j++) {
  32643. if (!trigger.detached)
  32644. traverse(trigger.children[j], triggerParams, null, null);
  32645. }
  32646. }
  32647. };
  32648. ActionManager.GetTriggerName = function (trigger) {
  32649. switch (trigger) {
  32650. case 0: return "NothingTrigger";
  32651. case 1: return "OnPickTrigger";
  32652. case 2: return "OnLeftPickTrigger";
  32653. case 3: return "OnRightPickTrigger";
  32654. case 4: return "OnCenterPickTrigger";
  32655. case 5: return "OnPickDownTrigger";
  32656. case 6: return "OnPickUpTrigger";
  32657. case 7: return "OnLongPressTrigger";
  32658. case 8: return "OnPointerOverTrigger";
  32659. case 9: return "OnPointerOutTrigger";
  32660. case 10: return "OnEveryFrameTrigger";
  32661. case 11: return "OnIntersectionEnterTrigger";
  32662. case 12: return "OnIntersectionExitTrigger";
  32663. case 13: return "OnKeyDownTrigger";
  32664. case 14: return "OnKeyUpTrigger";
  32665. case 15: return "OnPickOutTrigger";
  32666. default: return "";
  32667. }
  32668. };
  32669. // Statics
  32670. ActionManager._NothingTrigger = 0;
  32671. ActionManager._OnPickTrigger = 1;
  32672. ActionManager._OnLeftPickTrigger = 2;
  32673. ActionManager._OnRightPickTrigger = 3;
  32674. ActionManager._OnCenterPickTrigger = 4;
  32675. ActionManager._OnPickDownTrigger = 5;
  32676. ActionManager._OnPickUpTrigger = 6;
  32677. ActionManager._OnLongPressTrigger = 7;
  32678. ActionManager._OnPointerOverTrigger = 8;
  32679. ActionManager._OnPointerOutTrigger = 9;
  32680. ActionManager._OnEveryFrameTrigger = 10;
  32681. ActionManager._OnIntersectionEnterTrigger = 11;
  32682. ActionManager._OnIntersectionExitTrigger = 12;
  32683. ActionManager._OnKeyDownTrigger = 13;
  32684. ActionManager._OnKeyUpTrigger = 14;
  32685. ActionManager._OnPickOutTrigger = 15;
  32686. ActionManager.DragMovementThreshold = 10; // in pixels
  32687. ActionManager.LongPressDelay = 500; // in milliseconds
  32688. return ActionManager;
  32689. }());
  32690. BABYLON.ActionManager = ActionManager;
  32691. })(BABYLON || (BABYLON = {}));
  32692. var BABYLON;
  32693. (function (BABYLON) {
  32694. var InterpolateValueAction = (function (_super) {
  32695. __extends(InterpolateValueAction, _super);
  32696. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  32697. if (duration === void 0) { duration = 1000; }
  32698. _super.call(this, triggerOptions, condition);
  32699. this.propertyPath = propertyPath;
  32700. this.value = value;
  32701. this.duration = duration;
  32702. this.stopOtherAnimations = stopOtherAnimations;
  32703. this.onInterpolationDone = onInterpolationDone;
  32704. this._target = this._effectiveTarget = target;
  32705. }
  32706. InterpolateValueAction.prototype._prepare = function () {
  32707. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32708. this._property = this._getProperty(this.propertyPath);
  32709. };
  32710. InterpolateValueAction.prototype.execute = function () {
  32711. var scene = this._actionManager.getScene();
  32712. var keys = [
  32713. {
  32714. frame: 0,
  32715. value: this._effectiveTarget[this._property]
  32716. }, {
  32717. frame: 100,
  32718. value: this.value
  32719. }
  32720. ];
  32721. var dataType;
  32722. if (typeof this.value === "number") {
  32723. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  32724. }
  32725. else if (this.value instanceof BABYLON.Color3) {
  32726. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  32727. }
  32728. else if (this.value instanceof BABYLON.Vector3) {
  32729. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  32730. }
  32731. else if (this.value instanceof BABYLON.Matrix) {
  32732. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  32733. }
  32734. else if (this.value instanceof BABYLON.Quaternion) {
  32735. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  32736. }
  32737. else {
  32738. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  32739. return;
  32740. }
  32741. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  32742. animation.setKeys(keys);
  32743. if (this.stopOtherAnimations) {
  32744. scene.stopAnimation(this._effectiveTarget);
  32745. }
  32746. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  32747. };
  32748. InterpolateValueAction.prototype.serialize = function (parent) {
  32749. return _super.prototype._serialize.call(this, {
  32750. name: "InterpolateValueAction",
  32751. properties: [
  32752. BABYLON.Action._GetTargetProperty(this._target),
  32753. { name: "propertyPath", value: this.propertyPath },
  32754. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  32755. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  32756. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  32757. ]
  32758. }, parent);
  32759. };
  32760. return InterpolateValueAction;
  32761. }(BABYLON.Action));
  32762. BABYLON.InterpolateValueAction = InterpolateValueAction;
  32763. })(BABYLON || (BABYLON = {}));
  32764. var BABYLON;
  32765. (function (BABYLON) {
  32766. var SwitchBooleanAction = (function (_super) {
  32767. __extends(SwitchBooleanAction, _super);
  32768. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  32769. _super.call(this, triggerOptions, condition);
  32770. this.propertyPath = propertyPath;
  32771. this._target = this._effectiveTarget = target;
  32772. }
  32773. SwitchBooleanAction.prototype._prepare = function () {
  32774. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32775. this._property = this._getProperty(this.propertyPath);
  32776. };
  32777. SwitchBooleanAction.prototype.execute = function () {
  32778. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  32779. };
  32780. SwitchBooleanAction.prototype.serialize = function (parent) {
  32781. return _super.prototype._serialize.call(this, {
  32782. name: "SwitchBooleanAction",
  32783. properties: [
  32784. BABYLON.Action._GetTargetProperty(this._target),
  32785. { name: "propertyPath", value: this.propertyPath }
  32786. ]
  32787. }, parent);
  32788. };
  32789. return SwitchBooleanAction;
  32790. }(BABYLON.Action));
  32791. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  32792. var SetStateAction = (function (_super) {
  32793. __extends(SetStateAction, _super);
  32794. function SetStateAction(triggerOptions, target, value, condition) {
  32795. _super.call(this, triggerOptions, condition);
  32796. this.value = value;
  32797. this._target = target;
  32798. }
  32799. SetStateAction.prototype.execute = function () {
  32800. this._target.state = this.value;
  32801. };
  32802. SetStateAction.prototype.serialize = function (parent) {
  32803. return _super.prototype._serialize.call(this, {
  32804. name: "SetStateAction",
  32805. properties: [
  32806. BABYLON.Action._GetTargetProperty(this._target),
  32807. { name: "value", value: this.value }
  32808. ]
  32809. }, parent);
  32810. };
  32811. return SetStateAction;
  32812. }(BABYLON.Action));
  32813. BABYLON.SetStateAction = SetStateAction;
  32814. var SetValueAction = (function (_super) {
  32815. __extends(SetValueAction, _super);
  32816. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  32817. _super.call(this, triggerOptions, condition);
  32818. this.propertyPath = propertyPath;
  32819. this.value = value;
  32820. this._target = this._effectiveTarget = target;
  32821. }
  32822. SetValueAction.prototype._prepare = function () {
  32823. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32824. this._property = this._getProperty(this.propertyPath);
  32825. };
  32826. SetValueAction.prototype.execute = function () {
  32827. this._effectiveTarget[this._property] = this.value;
  32828. if (this._target.markAsDirty) {
  32829. this._target.markAsDirty(this._property);
  32830. }
  32831. };
  32832. SetValueAction.prototype.serialize = function (parent) {
  32833. return _super.prototype._serialize.call(this, {
  32834. name: "SetValueAction",
  32835. properties: [
  32836. BABYLON.Action._GetTargetProperty(this._target),
  32837. { name: "propertyPath", value: this.propertyPath },
  32838. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  32839. ]
  32840. }, parent);
  32841. };
  32842. return SetValueAction;
  32843. }(BABYLON.Action));
  32844. BABYLON.SetValueAction = SetValueAction;
  32845. var IncrementValueAction = (function (_super) {
  32846. __extends(IncrementValueAction, _super);
  32847. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  32848. _super.call(this, triggerOptions, condition);
  32849. this.propertyPath = propertyPath;
  32850. this.value = value;
  32851. this._target = this._effectiveTarget = target;
  32852. }
  32853. IncrementValueAction.prototype._prepare = function () {
  32854. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32855. this._property = this._getProperty(this.propertyPath);
  32856. if (typeof this._effectiveTarget[this._property] !== "number") {
  32857. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  32858. }
  32859. };
  32860. IncrementValueAction.prototype.execute = function () {
  32861. this._effectiveTarget[this._property] += this.value;
  32862. if (this._target.markAsDirty) {
  32863. this._target.markAsDirty(this._property);
  32864. }
  32865. };
  32866. IncrementValueAction.prototype.serialize = function (parent) {
  32867. return _super.prototype._serialize.call(this, {
  32868. name: "IncrementValueAction",
  32869. properties: [
  32870. BABYLON.Action._GetTargetProperty(this._target),
  32871. { name: "propertyPath", value: this.propertyPath },
  32872. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  32873. ]
  32874. }, parent);
  32875. };
  32876. return IncrementValueAction;
  32877. }(BABYLON.Action));
  32878. BABYLON.IncrementValueAction = IncrementValueAction;
  32879. var PlayAnimationAction = (function (_super) {
  32880. __extends(PlayAnimationAction, _super);
  32881. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  32882. _super.call(this, triggerOptions, condition);
  32883. this.from = from;
  32884. this.to = to;
  32885. this.loop = loop;
  32886. this._target = target;
  32887. }
  32888. PlayAnimationAction.prototype._prepare = function () {
  32889. };
  32890. PlayAnimationAction.prototype.execute = function () {
  32891. var scene = this._actionManager.getScene();
  32892. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  32893. };
  32894. PlayAnimationAction.prototype.serialize = function (parent) {
  32895. return _super.prototype._serialize.call(this, {
  32896. name: "PlayAnimationAction",
  32897. properties: [
  32898. BABYLON.Action._GetTargetProperty(this._target),
  32899. { name: "from", value: String(this.from) },
  32900. { name: "to", value: String(this.to) },
  32901. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  32902. ]
  32903. }, parent);
  32904. };
  32905. return PlayAnimationAction;
  32906. }(BABYLON.Action));
  32907. BABYLON.PlayAnimationAction = PlayAnimationAction;
  32908. var StopAnimationAction = (function (_super) {
  32909. __extends(StopAnimationAction, _super);
  32910. function StopAnimationAction(triggerOptions, target, condition) {
  32911. _super.call(this, triggerOptions, condition);
  32912. this._target = target;
  32913. }
  32914. StopAnimationAction.prototype._prepare = function () {
  32915. };
  32916. StopAnimationAction.prototype.execute = function () {
  32917. var scene = this._actionManager.getScene();
  32918. scene.stopAnimation(this._target);
  32919. };
  32920. StopAnimationAction.prototype.serialize = function (parent) {
  32921. return _super.prototype._serialize.call(this, {
  32922. name: "StopAnimationAction",
  32923. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  32924. }, parent);
  32925. };
  32926. return StopAnimationAction;
  32927. }(BABYLON.Action));
  32928. BABYLON.StopAnimationAction = StopAnimationAction;
  32929. var DoNothingAction = (function (_super) {
  32930. __extends(DoNothingAction, _super);
  32931. function DoNothingAction(triggerOptions, condition) {
  32932. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  32933. _super.call(this, triggerOptions, condition);
  32934. }
  32935. DoNothingAction.prototype.execute = function () {
  32936. };
  32937. DoNothingAction.prototype.serialize = function (parent) {
  32938. return _super.prototype._serialize.call(this, {
  32939. name: "DoNothingAction",
  32940. properties: []
  32941. }, parent);
  32942. };
  32943. return DoNothingAction;
  32944. }(BABYLON.Action));
  32945. BABYLON.DoNothingAction = DoNothingAction;
  32946. var CombineAction = (function (_super) {
  32947. __extends(CombineAction, _super);
  32948. function CombineAction(triggerOptions, children, condition) {
  32949. _super.call(this, triggerOptions, condition);
  32950. this.children = children;
  32951. }
  32952. CombineAction.prototype._prepare = function () {
  32953. for (var index = 0; index < this.children.length; index++) {
  32954. this.children[index]._actionManager = this._actionManager;
  32955. this.children[index]._prepare();
  32956. }
  32957. };
  32958. CombineAction.prototype.execute = function (evt) {
  32959. for (var index = 0; index < this.children.length; index++) {
  32960. this.children[index].execute(evt);
  32961. }
  32962. };
  32963. CombineAction.prototype.serialize = function (parent) {
  32964. var serializationObject = _super.prototype._serialize.call(this, {
  32965. name: "CombineAction",
  32966. properties: [],
  32967. combine: []
  32968. }, parent);
  32969. for (var i = 0; i < this.children.length; i++) {
  32970. serializationObject.combine.push(this.children[i].serialize(null));
  32971. }
  32972. return serializationObject;
  32973. };
  32974. return CombineAction;
  32975. }(BABYLON.Action));
  32976. BABYLON.CombineAction = CombineAction;
  32977. var ExecuteCodeAction = (function (_super) {
  32978. __extends(ExecuteCodeAction, _super);
  32979. function ExecuteCodeAction(triggerOptions, func, condition) {
  32980. _super.call(this, triggerOptions, condition);
  32981. this.func = func;
  32982. }
  32983. ExecuteCodeAction.prototype.execute = function (evt) {
  32984. this.func(evt);
  32985. };
  32986. return ExecuteCodeAction;
  32987. }(BABYLON.Action));
  32988. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  32989. var SetParentAction = (function (_super) {
  32990. __extends(SetParentAction, _super);
  32991. function SetParentAction(triggerOptions, target, parent, condition) {
  32992. _super.call(this, triggerOptions, condition);
  32993. this._target = target;
  32994. this._parent = parent;
  32995. }
  32996. SetParentAction.prototype._prepare = function () {
  32997. };
  32998. SetParentAction.prototype.execute = function () {
  32999. if (this._target.parent === this._parent) {
  33000. return;
  33001. }
  33002. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  33003. invertParentWorldMatrix.invert();
  33004. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  33005. this._target.parent = this._parent;
  33006. };
  33007. SetParentAction.prototype.serialize = function (parent) {
  33008. return _super.prototype._serialize.call(this, {
  33009. name: "SetParentAction",
  33010. properties: [
  33011. BABYLON.Action._GetTargetProperty(this._target),
  33012. BABYLON.Action._GetTargetProperty(this._parent),
  33013. ]
  33014. }, parent);
  33015. };
  33016. return SetParentAction;
  33017. }(BABYLON.Action));
  33018. BABYLON.SetParentAction = SetParentAction;
  33019. var PlaySoundAction = (function (_super) {
  33020. __extends(PlaySoundAction, _super);
  33021. function PlaySoundAction(triggerOptions, sound, condition) {
  33022. _super.call(this, triggerOptions, condition);
  33023. this._sound = sound;
  33024. }
  33025. PlaySoundAction.prototype._prepare = function () {
  33026. };
  33027. PlaySoundAction.prototype.execute = function () {
  33028. if (this._sound !== undefined)
  33029. this._sound.play();
  33030. };
  33031. PlaySoundAction.prototype.serialize = function (parent) {
  33032. return _super.prototype._serialize.call(this, {
  33033. name: "PlaySoundAction",
  33034. properties: [{ name: "sound", value: this._sound.name }]
  33035. }, parent);
  33036. };
  33037. return PlaySoundAction;
  33038. }(BABYLON.Action));
  33039. BABYLON.PlaySoundAction = PlaySoundAction;
  33040. var StopSoundAction = (function (_super) {
  33041. __extends(StopSoundAction, _super);
  33042. function StopSoundAction(triggerOptions, sound, condition) {
  33043. _super.call(this, triggerOptions, condition);
  33044. this._sound = sound;
  33045. }
  33046. StopSoundAction.prototype._prepare = function () {
  33047. };
  33048. StopSoundAction.prototype.execute = function () {
  33049. if (this._sound !== undefined)
  33050. this._sound.stop();
  33051. };
  33052. StopSoundAction.prototype.serialize = function (parent) {
  33053. return _super.prototype._serialize.call(this, {
  33054. name: "StopSoundAction",
  33055. properties: [{ name: "sound", value: this._sound.name }]
  33056. }, parent);
  33057. };
  33058. return StopSoundAction;
  33059. }(BABYLON.Action));
  33060. BABYLON.StopSoundAction = StopSoundAction;
  33061. })(BABYLON || (BABYLON = {}));
  33062. var BABYLON;
  33063. (function (BABYLON) {
  33064. var Geometry = (function () {
  33065. function Geometry(id, scene, vertexData, updatable, mesh) {
  33066. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33067. this._totalVertices = 0;
  33068. this._isDisposed = false;
  33069. this.id = id;
  33070. this._engine = scene.getEngine();
  33071. this._meshes = [];
  33072. this._scene = scene;
  33073. //Init vertex buffer cache
  33074. this._vertexBuffers = {};
  33075. this._indices = [];
  33076. // vertexData
  33077. if (vertexData) {
  33078. this.setAllVerticesData(vertexData, updatable);
  33079. }
  33080. else {
  33081. this._totalVertices = 0;
  33082. this._indices = [];
  33083. }
  33084. // applyToMesh
  33085. if (mesh) {
  33086. if (mesh instanceof BABYLON.LinesMesh) {
  33087. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  33088. this.updateExtend();
  33089. }
  33090. this.applyToMesh(mesh);
  33091. mesh.computeWorldMatrix(true);
  33092. }
  33093. }
  33094. Object.defineProperty(Geometry.prototype, "boundingBias", {
  33095. /**
  33096. * 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
  33097. * @returns The Bias Vector
  33098. */
  33099. get: function () {
  33100. return this._boundingBias;
  33101. },
  33102. set: function (value) {
  33103. if (this._boundingBias && this._boundingBias.equals(value)) {
  33104. return;
  33105. }
  33106. this._boundingBias = value.clone();
  33107. this.updateBoundingInfo(true, null);
  33108. },
  33109. enumerable: true,
  33110. configurable: true
  33111. });
  33112. Object.defineProperty(Geometry.prototype, "extend", {
  33113. get: function () {
  33114. return this._extend;
  33115. },
  33116. enumerable: true,
  33117. configurable: true
  33118. });
  33119. Geometry.prototype.getScene = function () {
  33120. return this._scene;
  33121. };
  33122. Geometry.prototype.getEngine = function () {
  33123. return this._engine;
  33124. };
  33125. Geometry.prototype.isReady = function () {
  33126. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  33127. };
  33128. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  33129. vertexData.applyToGeometry(this, updatable);
  33130. this.notifyUpdate();
  33131. };
  33132. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  33133. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  33134. this.setVerticesBuffer(buffer);
  33135. };
  33136. Geometry.prototype.setVerticesBuffer = function (buffer) {
  33137. var kind = buffer.getKind();
  33138. if (this._vertexBuffers[kind]) {
  33139. this._vertexBuffers[kind].dispose();
  33140. }
  33141. this._vertexBuffers[kind] = buffer;
  33142. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33143. var data = buffer.getData();
  33144. var stride = buffer.getStrideSize();
  33145. this._totalVertices = data.length / stride;
  33146. this.updateExtend(data, stride);
  33147. var meshes = this._meshes;
  33148. var numOfMeshes = meshes.length;
  33149. for (var index = 0; index < numOfMeshes; index++) {
  33150. var mesh = meshes[index];
  33151. mesh._resetPointsArrayCache();
  33152. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33153. mesh._createGlobalSubMesh();
  33154. mesh.computeWorldMatrix(true);
  33155. }
  33156. }
  33157. this.notifyUpdate(kind);
  33158. };
  33159. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  33160. var vertexBuffer = this.getVertexBuffer(kind);
  33161. if (!vertexBuffer) {
  33162. return;
  33163. }
  33164. vertexBuffer.updateDirectly(data, offset);
  33165. this.notifyUpdate(kind);
  33166. };
  33167. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  33168. var vertexBuffer = this.getVertexBuffer(kind);
  33169. if (!vertexBuffer) {
  33170. return;
  33171. }
  33172. vertexBuffer.update(data);
  33173. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33174. var stride = vertexBuffer.getStrideSize();
  33175. this._totalVertices = data.length / stride;
  33176. this.updateBoundingInfo(updateExtends, data);
  33177. }
  33178. this.notifyUpdate(kind);
  33179. };
  33180. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  33181. if (updateExtends) {
  33182. this.updateExtend(data);
  33183. }
  33184. var meshes = this._meshes;
  33185. var numOfMeshes = meshes.length;
  33186. for (var index = 0; index < numOfMeshes; index++) {
  33187. var mesh = meshes[index];
  33188. mesh._resetPointsArrayCache();
  33189. if (updateExtends) {
  33190. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33191. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  33192. var subMesh = mesh.subMeshes[subIndex];
  33193. subMesh.refreshBoundingInfo();
  33194. }
  33195. }
  33196. }
  33197. };
  33198. Geometry.prototype.getTotalVertices = function () {
  33199. if (!this.isReady()) {
  33200. return 0;
  33201. }
  33202. return this._totalVertices;
  33203. };
  33204. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  33205. var vertexBuffer = this.getVertexBuffer(kind);
  33206. if (!vertexBuffer) {
  33207. return null;
  33208. }
  33209. var orig = vertexBuffer.getData();
  33210. if (!copyWhenShared || this._meshes.length === 1) {
  33211. return orig;
  33212. }
  33213. else {
  33214. var len = orig.length;
  33215. var copy = [];
  33216. for (var i = 0; i < len; i++) {
  33217. copy.push(orig[i]);
  33218. }
  33219. return copy;
  33220. }
  33221. };
  33222. Geometry.prototype.getVertexBuffer = function (kind) {
  33223. if (!this.isReady()) {
  33224. return null;
  33225. }
  33226. return this._vertexBuffers[kind];
  33227. };
  33228. Geometry.prototype.getVertexBuffers = function () {
  33229. if (!this.isReady()) {
  33230. return null;
  33231. }
  33232. return this._vertexBuffers;
  33233. };
  33234. Geometry.prototype.isVerticesDataPresent = function (kind) {
  33235. if (!this._vertexBuffers) {
  33236. if (this._delayInfo) {
  33237. return this._delayInfo.indexOf(kind) !== -1;
  33238. }
  33239. return false;
  33240. }
  33241. return this._vertexBuffers[kind] !== undefined;
  33242. };
  33243. Geometry.prototype.getVerticesDataKinds = function () {
  33244. var result = [];
  33245. var kind;
  33246. if (!this._vertexBuffers && this._delayInfo) {
  33247. for (kind in this._delayInfo) {
  33248. result.push(kind);
  33249. }
  33250. }
  33251. else {
  33252. for (kind in this._vertexBuffers) {
  33253. result.push(kind);
  33254. }
  33255. }
  33256. return result;
  33257. };
  33258. Geometry.prototype.setIndices = function (indices, totalVertices) {
  33259. if (this._indexBuffer) {
  33260. this._engine._releaseBuffer(this._indexBuffer);
  33261. }
  33262. this._indices = indices;
  33263. if (this._meshes.length !== 0 && this._indices) {
  33264. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33265. }
  33266. if (totalVertices !== undefined) {
  33267. this._totalVertices = totalVertices;
  33268. }
  33269. var meshes = this._meshes;
  33270. var numOfMeshes = meshes.length;
  33271. for (var index = 0; index < numOfMeshes; index++) {
  33272. meshes[index]._createGlobalSubMesh();
  33273. }
  33274. this.notifyUpdate();
  33275. };
  33276. Geometry.prototype.getTotalIndices = function () {
  33277. if (!this.isReady()) {
  33278. return 0;
  33279. }
  33280. return this._indices.length;
  33281. };
  33282. Geometry.prototype.getIndices = function (copyWhenShared) {
  33283. if (!this.isReady()) {
  33284. return null;
  33285. }
  33286. var orig = this._indices;
  33287. if (!copyWhenShared || this._meshes.length === 1) {
  33288. return orig;
  33289. }
  33290. else {
  33291. var len = orig.length;
  33292. var copy = [];
  33293. for (var i = 0; i < len; i++) {
  33294. copy.push(orig[i]);
  33295. }
  33296. return copy;
  33297. }
  33298. };
  33299. Geometry.prototype.getIndexBuffer = function () {
  33300. if (!this.isReady()) {
  33301. return null;
  33302. }
  33303. return this._indexBuffer;
  33304. };
  33305. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  33306. var meshes = this._meshes;
  33307. var index = meshes.indexOf(mesh);
  33308. if (index === -1) {
  33309. return;
  33310. }
  33311. for (var kind in this._vertexBuffers) {
  33312. this._vertexBuffers[kind].dispose();
  33313. }
  33314. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  33315. this._indexBuffer = null;
  33316. }
  33317. meshes.splice(index, 1);
  33318. mesh._geometry = null;
  33319. if (meshes.length === 0 && shouldDispose) {
  33320. this.dispose();
  33321. }
  33322. };
  33323. Geometry.prototype.applyToMesh = function (mesh) {
  33324. if (mesh._geometry === this) {
  33325. return;
  33326. }
  33327. var previousGeometry = mesh._geometry;
  33328. if (previousGeometry) {
  33329. previousGeometry.releaseForMesh(mesh);
  33330. }
  33331. var meshes = this._meshes;
  33332. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  33333. mesh._geometry = this;
  33334. this._scene.pushGeometry(this);
  33335. meshes.push(mesh);
  33336. if (this.isReady()) {
  33337. this._applyToMesh(mesh);
  33338. }
  33339. else {
  33340. mesh._boundingInfo = this._boundingInfo;
  33341. }
  33342. };
  33343. Geometry.prototype.updateExtend = function (data, stride) {
  33344. if (data === void 0) { data = null; }
  33345. if (!data) {
  33346. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  33347. }
  33348. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  33349. };
  33350. Geometry.prototype._applyToMesh = function (mesh) {
  33351. var numOfMeshes = this._meshes.length;
  33352. // vertexBuffers
  33353. for (var kind in this._vertexBuffers) {
  33354. if (numOfMeshes === 1) {
  33355. this._vertexBuffers[kind].create();
  33356. }
  33357. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  33358. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33359. mesh._resetPointsArrayCache();
  33360. if (!this._extend) {
  33361. this.updateExtend(this._vertexBuffers[kind].getData());
  33362. }
  33363. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33364. mesh._createGlobalSubMesh();
  33365. //bounding info was just created again, world matrix should be applied again.
  33366. mesh._updateBoundingInfo();
  33367. }
  33368. }
  33369. // indexBuffer
  33370. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  33371. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33372. }
  33373. if (this._indexBuffer) {
  33374. this._indexBuffer.references = numOfMeshes;
  33375. }
  33376. };
  33377. Geometry.prototype.notifyUpdate = function (kind) {
  33378. if (this.onGeometryUpdated) {
  33379. this.onGeometryUpdated(this, kind);
  33380. }
  33381. };
  33382. Geometry.prototype.load = function (scene, onLoaded) {
  33383. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33384. return;
  33385. }
  33386. if (this.isReady()) {
  33387. if (onLoaded) {
  33388. onLoaded();
  33389. }
  33390. return;
  33391. }
  33392. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33393. this._queueLoad(scene, onLoaded);
  33394. };
  33395. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  33396. var _this = this;
  33397. scene._addPendingData(this);
  33398. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  33399. _this._delayLoadingFunction(JSON.parse(data), _this);
  33400. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33401. _this._delayInfo = [];
  33402. scene._removePendingData(_this);
  33403. var meshes = _this._meshes;
  33404. var numOfMeshes = meshes.length;
  33405. for (var index = 0; index < numOfMeshes; index++) {
  33406. _this._applyToMesh(meshes[index]);
  33407. }
  33408. if (onLoaded) {
  33409. onLoaded();
  33410. }
  33411. }, function () { }, scene.database);
  33412. };
  33413. /**
  33414. * Invert the geometry to move from a right handed system to a left handed one.
  33415. */
  33416. Geometry.prototype.toLeftHanded = function () {
  33417. // Flip faces
  33418. var tIndices = this.getIndices(false);
  33419. if (tIndices != null && tIndices.length > 0) {
  33420. for (var i = 0; i < tIndices.length; i += 3) {
  33421. var tTemp = tIndices[i + 0];
  33422. tIndices[i + 0] = tIndices[i + 2];
  33423. tIndices[i + 2] = tTemp;
  33424. }
  33425. this.setIndices(tIndices);
  33426. }
  33427. // Negate position.z
  33428. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  33429. if (tPositions != null && tPositions.length > 0) {
  33430. for (var i = 0; i < tPositions.length; i += 3) {
  33431. tPositions[i + 2] = -tPositions[i + 2];
  33432. }
  33433. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  33434. }
  33435. // Negate normal.z
  33436. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  33437. if (tNormals != null && tNormals.length > 0) {
  33438. for (var i = 0; i < tNormals.length; i += 3) {
  33439. tNormals[i + 2] = -tNormals[i + 2];
  33440. }
  33441. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  33442. }
  33443. };
  33444. Geometry.prototype.isDisposed = function () {
  33445. return this._isDisposed;
  33446. };
  33447. Geometry.prototype.dispose = function () {
  33448. var meshes = this._meshes;
  33449. var numOfMeshes = meshes.length;
  33450. var index;
  33451. for (index = 0; index < numOfMeshes; index++) {
  33452. this.releaseForMesh(meshes[index]);
  33453. }
  33454. this._meshes = [];
  33455. for (var kind in this._vertexBuffers) {
  33456. this._vertexBuffers[kind].dispose();
  33457. }
  33458. this._vertexBuffers = {};
  33459. this._totalVertices = 0;
  33460. if (this._indexBuffer) {
  33461. this._engine._releaseBuffer(this._indexBuffer);
  33462. }
  33463. this._indexBuffer = null;
  33464. this._indices = [];
  33465. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33466. this.delayLoadingFile = null;
  33467. this._delayLoadingFunction = null;
  33468. this._delayInfo = [];
  33469. this._boundingInfo = null;
  33470. this._scene.removeGeometry(this);
  33471. this._isDisposed = true;
  33472. };
  33473. Geometry.prototype.copy = function (id) {
  33474. var vertexData = new BABYLON.VertexData();
  33475. vertexData.indices = [];
  33476. var indices = this.getIndices();
  33477. for (var index = 0; index < indices.length; index++) {
  33478. vertexData.indices.push(indices[index]);
  33479. }
  33480. var updatable = false;
  33481. var stopChecking = false;
  33482. var kind;
  33483. for (kind in this._vertexBuffers) {
  33484. // using slice() to make a copy of the array and not just reference it
  33485. var data = this.getVerticesData(kind);
  33486. if (data instanceof Float32Array) {
  33487. vertexData.set(new Float32Array(data), kind);
  33488. }
  33489. else {
  33490. vertexData.set(data.slice(0), kind);
  33491. }
  33492. if (!stopChecking) {
  33493. updatable = this.getVertexBuffer(kind).isUpdatable();
  33494. stopChecking = !updatable;
  33495. }
  33496. }
  33497. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  33498. geometry.delayLoadState = this.delayLoadState;
  33499. geometry.delayLoadingFile = this.delayLoadingFile;
  33500. geometry._delayLoadingFunction = this._delayLoadingFunction;
  33501. for (kind in this._delayInfo) {
  33502. geometry._delayInfo = geometry._delayInfo || [];
  33503. geometry._delayInfo.push(kind);
  33504. }
  33505. // Bounding info
  33506. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33507. return geometry;
  33508. };
  33509. Geometry.prototype.serialize = function () {
  33510. var serializationObject = {};
  33511. serializationObject.id = this.id;
  33512. if (BABYLON.Tags.HasTags(this)) {
  33513. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33514. }
  33515. return serializationObject;
  33516. };
  33517. Geometry.prototype.serializeVerticeData = function () {
  33518. var serializationObject = this.serialize();
  33519. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33520. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33521. }
  33522. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33523. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33524. }
  33525. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33526. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33527. }
  33528. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33529. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  33530. }
  33531. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33532. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  33533. }
  33534. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33535. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  33536. }
  33537. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33538. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  33539. }
  33540. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33541. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  33542. }
  33543. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33544. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  33545. }
  33546. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33547. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33548. serializationObject.matricesIndices._isExpanded = true;
  33549. }
  33550. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33551. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33552. }
  33553. serializationObject.indices = this.getIndices();
  33554. return serializationObject;
  33555. };
  33556. // Statics
  33557. Geometry.ExtractFromMesh = function (mesh, id) {
  33558. var geometry = mesh._geometry;
  33559. if (!geometry) {
  33560. return null;
  33561. }
  33562. return geometry.copy(id);
  33563. };
  33564. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  33565. // be aware Math.random() could cause collisions
  33566. Geometry.RandomId = function () {
  33567. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  33568. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  33569. return v.toString(16);
  33570. });
  33571. };
  33572. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  33573. var scene = mesh.getScene();
  33574. // Geometry
  33575. var geometryId = parsedGeometry.geometryId;
  33576. if (geometryId) {
  33577. var geometry = scene.getGeometryByID(geometryId);
  33578. if (geometry) {
  33579. geometry.applyToMesh(mesh);
  33580. }
  33581. }
  33582. else if (parsedGeometry instanceof ArrayBuffer) {
  33583. var binaryInfo = mesh._binaryInfo;
  33584. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  33585. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  33586. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  33587. }
  33588. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  33589. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  33590. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  33591. }
  33592. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  33593. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  33594. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  33595. }
  33596. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  33597. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  33598. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  33599. }
  33600. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  33601. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  33602. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  33603. }
  33604. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  33605. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  33606. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  33607. }
  33608. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  33609. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  33610. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  33611. }
  33612. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  33613. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  33614. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  33615. }
  33616. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  33617. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  33618. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  33619. }
  33620. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  33621. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  33622. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  33623. }
  33624. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  33625. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  33626. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  33627. }
  33628. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  33629. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  33630. mesh.setIndices(indicesData);
  33631. }
  33632. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  33633. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  33634. mesh.subMeshes = [];
  33635. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  33636. var materialIndex = subMeshesData[(i * 5) + 0];
  33637. var verticesStart = subMeshesData[(i * 5) + 1];
  33638. var verticesCount = subMeshesData[(i * 5) + 2];
  33639. var indexStart = subMeshesData[(i * 5) + 3];
  33640. var indexCount = subMeshesData[(i * 5) + 4];
  33641. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  33642. }
  33643. }
  33644. }
  33645. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  33646. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  33647. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  33648. if (parsedGeometry.uvs) {
  33649. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  33650. }
  33651. if (parsedGeometry.uvs2) {
  33652. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  33653. }
  33654. if (parsedGeometry.uvs3) {
  33655. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  33656. }
  33657. if (parsedGeometry.uvs4) {
  33658. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  33659. }
  33660. if (parsedGeometry.uvs5) {
  33661. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  33662. }
  33663. if (parsedGeometry.uvs6) {
  33664. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  33665. }
  33666. if (parsedGeometry.colors) {
  33667. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  33668. }
  33669. if (parsedGeometry.matricesIndices) {
  33670. if (!parsedGeometry.matricesIndices._isExpanded) {
  33671. var floatIndices = [];
  33672. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  33673. var matricesIndex = parsedGeometry.matricesIndices[i];
  33674. floatIndices.push(matricesIndex & 0x000000FF);
  33675. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33676. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33677. floatIndices.push(matricesIndex >> 24);
  33678. }
  33679. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  33680. }
  33681. else {
  33682. delete parsedGeometry.matricesIndices._isExpanded;
  33683. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  33684. }
  33685. }
  33686. if (parsedGeometry.matricesIndicesExtra) {
  33687. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  33688. var floatIndices = [];
  33689. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  33690. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  33691. floatIndices.push(matricesIndex & 0x000000FF);
  33692. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33693. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33694. floatIndices.push(matricesIndex >> 24);
  33695. }
  33696. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  33697. }
  33698. else {
  33699. delete parsedGeometry.matricesIndices._isExpanded;
  33700. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  33701. }
  33702. }
  33703. if (parsedGeometry.matricesWeights) {
  33704. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  33705. }
  33706. if (parsedGeometry.matricesWeightsExtra) {
  33707. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  33708. }
  33709. mesh.setIndices(parsedGeometry.indices);
  33710. }
  33711. // SubMeshes
  33712. if (parsedGeometry.subMeshes) {
  33713. mesh.subMeshes = [];
  33714. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  33715. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  33716. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  33717. }
  33718. }
  33719. // Flat shading
  33720. if (mesh._shouldGenerateFlatShading) {
  33721. mesh.convertToFlatShadedMesh();
  33722. delete mesh._shouldGenerateFlatShading;
  33723. }
  33724. // Update
  33725. mesh.computeWorldMatrix(true);
  33726. // Octree
  33727. if (scene['_selectionOctree']) {
  33728. scene['_selectionOctree'].addMesh(mesh);
  33729. }
  33730. };
  33731. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  33732. if (scene.getGeometryByID(parsedVertexData.id)) {
  33733. return null; // null since geometry could be something else than a box...
  33734. }
  33735. var geometry = new Geometry(parsedVertexData.id, scene);
  33736. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  33737. if (parsedVertexData.delayLoadingFile) {
  33738. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33739. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  33740. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  33741. geometry._delayInfo = [];
  33742. if (parsedVertexData.hasUVs) {
  33743. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33744. }
  33745. if (parsedVertexData.hasUVs2) {
  33746. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33747. }
  33748. if (parsedVertexData.hasUVs3) {
  33749. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33750. }
  33751. if (parsedVertexData.hasUVs4) {
  33752. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33753. }
  33754. if (parsedVertexData.hasUVs5) {
  33755. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33756. }
  33757. if (parsedVertexData.hasUVs6) {
  33758. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33759. }
  33760. if (parsedVertexData.hasColors) {
  33761. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33762. }
  33763. if (parsedVertexData.hasMatricesIndices) {
  33764. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33765. }
  33766. if (parsedVertexData.hasMatricesWeights) {
  33767. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33768. }
  33769. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  33770. }
  33771. else {
  33772. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  33773. }
  33774. scene.pushGeometry(geometry, true);
  33775. return geometry;
  33776. };
  33777. return Geometry;
  33778. }());
  33779. BABYLON.Geometry = Geometry;
  33780. /////// Primitives //////////////////////////////////////////////
  33781. var Geometry;
  33782. (function (Geometry) {
  33783. var Primitives;
  33784. (function (Primitives) {
  33785. /// Abstract class
  33786. var _Primitive = (function (_super) {
  33787. __extends(_Primitive, _super);
  33788. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  33789. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  33790. this._canBeRegenerated = _canBeRegenerated;
  33791. this._beingRegenerated = true;
  33792. this.regenerate();
  33793. this._beingRegenerated = false;
  33794. }
  33795. _Primitive.prototype.canBeRegenerated = function () {
  33796. return this._canBeRegenerated;
  33797. };
  33798. _Primitive.prototype.regenerate = function () {
  33799. if (!this._canBeRegenerated) {
  33800. return;
  33801. }
  33802. this._beingRegenerated = true;
  33803. this.setAllVerticesData(this._regenerateVertexData(), false);
  33804. this._beingRegenerated = false;
  33805. };
  33806. _Primitive.prototype.asNewGeometry = function (id) {
  33807. return _super.prototype.copy.call(this, id);
  33808. };
  33809. // overrides
  33810. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  33811. if (!this._beingRegenerated) {
  33812. return;
  33813. }
  33814. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  33815. };
  33816. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  33817. if (!this._beingRegenerated) {
  33818. return;
  33819. }
  33820. _super.prototype.setVerticesData.call(this, kind, data, false);
  33821. };
  33822. // to override
  33823. // protected
  33824. _Primitive.prototype._regenerateVertexData = function () {
  33825. throw new Error("Abstract method");
  33826. };
  33827. _Primitive.prototype.copy = function (id) {
  33828. throw new Error("Must be overriden in sub-classes.");
  33829. };
  33830. _Primitive.prototype.serialize = function () {
  33831. var serializationObject = _super.prototype.serialize.call(this);
  33832. serializationObject.canBeRegenerated = this.canBeRegenerated();
  33833. return serializationObject;
  33834. };
  33835. return _Primitive;
  33836. }(Geometry));
  33837. Primitives._Primitive = _Primitive;
  33838. var Ribbon = (function (_super) {
  33839. __extends(Ribbon, _super);
  33840. // Members
  33841. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  33842. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33843. _super.call(this, id, scene, canBeRegenerated, mesh);
  33844. this.pathArray = pathArray;
  33845. this.closeArray = closeArray;
  33846. this.closePath = closePath;
  33847. this.offset = offset;
  33848. this.side = side;
  33849. }
  33850. Ribbon.prototype._regenerateVertexData = function () {
  33851. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  33852. };
  33853. Ribbon.prototype.copy = function (id) {
  33854. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  33855. };
  33856. return Ribbon;
  33857. }(_Primitive));
  33858. Primitives.Ribbon = Ribbon;
  33859. var Box = (function (_super) {
  33860. __extends(Box, _super);
  33861. // Members
  33862. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  33863. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33864. _super.call(this, id, scene, canBeRegenerated, mesh);
  33865. this.size = size;
  33866. this.side = side;
  33867. }
  33868. Box.prototype._regenerateVertexData = function () {
  33869. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  33870. };
  33871. Box.prototype.copy = function (id) {
  33872. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  33873. };
  33874. Box.prototype.serialize = function () {
  33875. var serializationObject = _super.prototype.serialize.call(this);
  33876. serializationObject.size = this.size;
  33877. return serializationObject;
  33878. };
  33879. Box.Parse = function (parsedBox, scene) {
  33880. if (scene.getGeometryByID(parsedBox.id)) {
  33881. return null; // null since geometry could be something else than a box...
  33882. }
  33883. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  33884. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  33885. scene.pushGeometry(box, true);
  33886. return box;
  33887. };
  33888. return Box;
  33889. }(_Primitive));
  33890. Primitives.Box = Box;
  33891. var Sphere = (function (_super) {
  33892. __extends(Sphere, _super);
  33893. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  33894. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33895. _super.call(this, id, scene, canBeRegenerated, mesh);
  33896. this.segments = segments;
  33897. this.diameter = diameter;
  33898. this.side = side;
  33899. }
  33900. Sphere.prototype._regenerateVertexData = function () {
  33901. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  33902. };
  33903. Sphere.prototype.copy = function (id) {
  33904. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  33905. };
  33906. Sphere.prototype.serialize = function () {
  33907. var serializationObject = _super.prototype.serialize.call(this);
  33908. serializationObject.segments = this.segments;
  33909. serializationObject.diameter = this.diameter;
  33910. return serializationObject;
  33911. };
  33912. Sphere.Parse = function (parsedSphere, scene) {
  33913. if (scene.getGeometryByID(parsedSphere.id)) {
  33914. return null; // null since geometry could be something else than a sphere...
  33915. }
  33916. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  33917. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  33918. scene.pushGeometry(sphere, true);
  33919. return sphere;
  33920. };
  33921. return Sphere;
  33922. }(_Primitive));
  33923. Primitives.Sphere = Sphere;
  33924. var Disc = (function (_super) {
  33925. __extends(Disc, _super);
  33926. // Members
  33927. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  33928. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33929. _super.call(this, id, scene, canBeRegenerated, mesh);
  33930. this.radius = radius;
  33931. this.tessellation = tessellation;
  33932. this.side = side;
  33933. }
  33934. Disc.prototype._regenerateVertexData = function () {
  33935. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  33936. };
  33937. Disc.prototype.copy = function (id) {
  33938. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  33939. };
  33940. return Disc;
  33941. }(_Primitive));
  33942. Primitives.Disc = Disc;
  33943. var Cylinder = (function (_super) {
  33944. __extends(Cylinder, _super);
  33945. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  33946. if (subdivisions === void 0) { subdivisions = 1; }
  33947. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33948. _super.call(this, id, scene, canBeRegenerated, mesh);
  33949. this.height = height;
  33950. this.diameterTop = diameterTop;
  33951. this.diameterBottom = diameterBottom;
  33952. this.tessellation = tessellation;
  33953. this.subdivisions = subdivisions;
  33954. this.side = side;
  33955. }
  33956. Cylinder.prototype._regenerateVertexData = function () {
  33957. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  33958. };
  33959. Cylinder.prototype.copy = function (id) {
  33960. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  33961. };
  33962. Cylinder.prototype.serialize = function () {
  33963. var serializationObject = _super.prototype.serialize.call(this);
  33964. serializationObject.height = this.height;
  33965. serializationObject.diameterTop = this.diameterTop;
  33966. serializationObject.diameterBottom = this.diameterBottom;
  33967. serializationObject.tessellation = this.tessellation;
  33968. return serializationObject;
  33969. };
  33970. Cylinder.Parse = function (parsedCylinder, scene) {
  33971. if (scene.getGeometryByID(parsedCylinder.id)) {
  33972. return null; // null since geometry could be something else than a cylinder...
  33973. }
  33974. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  33975. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  33976. scene.pushGeometry(cylinder, true);
  33977. return cylinder;
  33978. };
  33979. return Cylinder;
  33980. }(_Primitive));
  33981. Primitives.Cylinder = Cylinder;
  33982. var Torus = (function (_super) {
  33983. __extends(Torus, _super);
  33984. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  33985. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33986. _super.call(this, id, scene, canBeRegenerated, mesh);
  33987. this.diameter = diameter;
  33988. this.thickness = thickness;
  33989. this.tessellation = tessellation;
  33990. this.side = side;
  33991. }
  33992. Torus.prototype._regenerateVertexData = function () {
  33993. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  33994. };
  33995. Torus.prototype.copy = function (id) {
  33996. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  33997. };
  33998. Torus.prototype.serialize = function () {
  33999. var serializationObject = _super.prototype.serialize.call(this);
  34000. serializationObject.diameter = this.diameter;
  34001. serializationObject.thickness = this.thickness;
  34002. serializationObject.tessellation = this.tessellation;
  34003. return serializationObject;
  34004. };
  34005. Torus.Parse = function (parsedTorus, scene) {
  34006. if (scene.getGeometryByID(parsedTorus.id)) {
  34007. return null; // null since geometry could be something else than a torus...
  34008. }
  34009. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  34010. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  34011. scene.pushGeometry(torus, true);
  34012. return torus;
  34013. };
  34014. return Torus;
  34015. }(_Primitive));
  34016. Primitives.Torus = Torus;
  34017. var Ground = (function (_super) {
  34018. __extends(Ground, _super);
  34019. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  34020. _super.call(this, id, scene, canBeRegenerated, mesh);
  34021. this.width = width;
  34022. this.height = height;
  34023. this.subdivisions = subdivisions;
  34024. }
  34025. Ground.prototype._regenerateVertexData = function () {
  34026. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  34027. };
  34028. Ground.prototype.copy = function (id) {
  34029. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  34030. };
  34031. Ground.prototype.serialize = function () {
  34032. var serializationObject = _super.prototype.serialize.call(this);
  34033. serializationObject.width = this.width;
  34034. serializationObject.height = this.height;
  34035. serializationObject.subdivisions = this.subdivisions;
  34036. return serializationObject;
  34037. };
  34038. Ground.Parse = function (parsedGround, scene) {
  34039. if (scene.getGeometryByID(parsedGround.id)) {
  34040. return null; // null since geometry could be something else than a ground...
  34041. }
  34042. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  34043. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  34044. scene.pushGeometry(ground, true);
  34045. return ground;
  34046. };
  34047. return Ground;
  34048. }(_Primitive));
  34049. Primitives.Ground = Ground;
  34050. var TiledGround = (function (_super) {
  34051. __extends(TiledGround, _super);
  34052. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  34053. _super.call(this, id, scene, canBeRegenerated, mesh);
  34054. this.xmin = xmin;
  34055. this.zmin = zmin;
  34056. this.xmax = xmax;
  34057. this.zmax = zmax;
  34058. this.subdivisions = subdivisions;
  34059. this.precision = precision;
  34060. }
  34061. TiledGround.prototype._regenerateVertexData = function () {
  34062. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  34063. };
  34064. TiledGround.prototype.copy = function (id) {
  34065. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  34066. };
  34067. return TiledGround;
  34068. }(_Primitive));
  34069. Primitives.TiledGround = TiledGround;
  34070. var Plane = (function (_super) {
  34071. __extends(Plane, _super);
  34072. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  34073. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34074. _super.call(this, id, scene, canBeRegenerated, mesh);
  34075. this.size = size;
  34076. this.side = side;
  34077. }
  34078. Plane.prototype._regenerateVertexData = function () {
  34079. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  34080. };
  34081. Plane.prototype.copy = function (id) {
  34082. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  34083. };
  34084. Plane.prototype.serialize = function () {
  34085. var serializationObject = _super.prototype.serialize.call(this);
  34086. serializationObject.size = this.size;
  34087. return serializationObject;
  34088. };
  34089. Plane.Parse = function (parsedPlane, scene) {
  34090. if (scene.getGeometryByID(parsedPlane.id)) {
  34091. return null; // null since geometry could be something else than a ground...
  34092. }
  34093. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  34094. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  34095. scene.pushGeometry(plane, true);
  34096. return plane;
  34097. };
  34098. return Plane;
  34099. }(_Primitive));
  34100. Primitives.Plane = Plane;
  34101. var TorusKnot = (function (_super) {
  34102. __extends(TorusKnot, _super);
  34103. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  34104. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34105. _super.call(this, id, scene, canBeRegenerated, mesh);
  34106. this.radius = radius;
  34107. this.tube = tube;
  34108. this.radialSegments = radialSegments;
  34109. this.tubularSegments = tubularSegments;
  34110. this.p = p;
  34111. this.q = q;
  34112. this.side = side;
  34113. }
  34114. TorusKnot.prototype._regenerateVertexData = function () {
  34115. 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 });
  34116. };
  34117. TorusKnot.prototype.copy = function (id) {
  34118. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  34119. };
  34120. TorusKnot.prototype.serialize = function () {
  34121. var serializationObject = _super.prototype.serialize.call(this);
  34122. serializationObject.radius = this.radius;
  34123. serializationObject.tube = this.tube;
  34124. serializationObject.radialSegments = this.radialSegments;
  34125. serializationObject.tubularSegments = this.tubularSegments;
  34126. serializationObject.p = this.p;
  34127. serializationObject.q = this.q;
  34128. return serializationObject;
  34129. };
  34130. ;
  34131. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  34132. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  34133. return null; // null since geometry could be something else than a ground...
  34134. }
  34135. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  34136. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  34137. scene.pushGeometry(torusKnot, true);
  34138. return torusKnot;
  34139. };
  34140. return TorusKnot;
  34141. }(_Primitive));
  34142. Primitives.TorusKnot = TorusKnot;
  34143. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  34144. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  34145. })(BABYLON || (BABYLON = {}));
  34146. var BABYLON;
  34147. (function (BABYLON) {
  34148. var GroundMesh = (function (_super) {
  34149. __extends(GroundMesh, _super);
  34150. function GroundMesh(name, scene) {
  34151. _super.call(this, name, scene);
  34152. this.generateOctree = false;
  34153. this._worldInverse = new BABYLON.Matrix();
  34154. }
  34155. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  34156. get: function () {
  34157. return this._subdivisions;
  34158. },
  34159. enumerable: true,
  34160. configurable: true
  34161. });
  34162. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  34163. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  34164. this._subdivisions = chunksCount;
  34165. this.subdivide(this._subdivisions);
  34166. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  34167. };
  34168. /**
  34169. * Returns a height (y) value in the Worl system :
  34170. * the ground altitude at the coordinates (x, z) expressed in the World system.
  34171. * Returns the ground y position if (x, z) are outside the ground surface.
  34172. * Not pertinent if the ground is rotated.
  34173. */
  34174. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  34175. // express x and y in the ground local system
  34176. x -= this.position.x;
  34177. z -= this.position.z;
  34178. x /= this.scaling.x;
  34179. z /= this.scaling.z;
  34180. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  34181. return this.position.y;
  34182. }
  34183. if (!this._heightQuads || this._heightQuads.length == 0) {
  34184. this._initHeightQuads();
  34185. this._computeHeightQuads();
  34186. }
  34187. var facet = this._getFacetAt(x, z);
  34188. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  34189. // return y in the World system
  34190. return y * this.scaling.y + this.position.y;
  34191. };
  34192. /**
  34193. * Returns a normalized vector (Vector3) orthogonal to the ground
  34194. * at the ground coordinates (x, z) expressed in the World system.
  34195. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  34196. * Not pertinent if the ground is rotated.
  34197. */
  34198. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  34199. var normal = new BABYLON.Vector3(0, 1, 0);
  34200. this.getNormalAtCoordinatesToRef(x, z, normal);
  34201. return normal;
  34202. };
  34203. /**
  34204. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  34205. * at the ground coordinates (x, z) expressed in the World system.
  34206. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  34207. * Not pertinent if the ground is rotated.
  34208. */
  34209. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  34210. // express x and y in the ground local system
  34211. x -= this.position.x;
  34212. z -= this.position.z;
  34213. x /= this.scaling.x;
  34214. z /= this.scaling.z;
  34215. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  34216. return;
  34217. }
  34218. if (!this._heightQuads || this._heightQuads.length == 0) {
  34219. this._initHeightQuads();
  34220. this._computeHeightQuads();
  34221. }
  34222. var facet = this._getFacetAt(x, z);
  34223. ref.x = facet.x;
  34224. ref.y = facet.y;
  34225. ref.z = facet.z;
  34226. };
  34227. /**
  34228. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  34229. * if the ground has been updated.
  34230. * This can be used in the render loop
  34231. */
  34232. GroundMesh.prototype.updateCoordinateHeights = function () {
  34233. if (!this._heightQuads || this._heightQuads.length == 0) {
  34234. this._initHeightQuads();
  34235. }
  34236. this._computeHeightQuads();
  34237. };
  34238. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  34239. GroundMesh.prototype._getFacetAt = function (x, z) {
  34240. // retrieve col and row from x, z coordinates in the ground local system
  34241. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  34242. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  34243. var quad = this._heightQuads[row * this._subdivisions + col];
  34244. var facet;
  34245. if (z < quad.slope.x * x + quad.slope.y) {
  34246. facet = quad.facet1;
  34247. }
  34248. else {
  34249. facet = quad.facet2;
  34250. }
  34251. return facet;
  34252. };
  34253. // Creates and populates the heightMap array with "facet" elements :
  34254. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  34255. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  34256. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  34257. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  34258. GroundMesh.prototype._initHeightQuads = function () {
  34259. this._heightQuads = new Array();
  34260. for (var row = 0; row < this._subdivisions; row++) {
  34261. for (var col = 0; col < this._subdivisions; col++) {
  34262. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  34263. this._heightQuads[row * this._subdivisions + col] = quad;
  34264. }
  34265. }
  34266. };
  34267. // Compute each quad element values and update the the heightMap array :
  34268. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  34269. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  34270. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  34271. GroundMesh.prototype._computeHeightQuads = function () {
  34272. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34273. var v1 = BABYLON.Tmp.Vector3[3];
  34274. var v2 = BABYLON.Tmp.Vector3[2];
  34275. var v3 = BABYLON.Tmp.Vector3[1];
  34276. var v4 = BABYLON.Tmp.Vector3[0];
  34277. var v1v2 = BABYLON.Tmp.Vector3[4];
  34278. var v1v3 = BABYLON.Tmp.Vector3[5];
  34279. var v1v4 = BABYLON.Tmp.Vector3[6];
  34280. var norm1 = BABYLON.Tmp.Vector3[7];
  34281. var norm2 = BABYLON.Tmp.Vector3[8];
  34282. var i = 0;
  34283. var j = 0;
  34284. var k = 0;
  34285. var cd = 0; // 2D slope coefficient : z = cd * x + h
  34286. var h = 0;
  34287. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  34288. var d2 = 0;
  34289. for (var row = 0; row < this._subdivisions; row++) {
  34290. for (var col = 0; col < this._subdivisions; col++) {
  34291. i = col * 3;
  34292. j = row * (this._subdivisions + 1) * 3;
  34293. k = (row + 1) * (this._subdivisions + 1) * 3;
  34294. v1.x = positions[j + i];
  34295. v1.y = positions[j + i + 1];
  34296. v1.z = positions[j + i + 2];
  34297. v2.x = positions[j + i + 3];
  34298. v2.y = positions[j + i + 4];
  34299. v2.z = positions[j + i + 5];
  34300. v3.x = positions[k + i];
  34301. v3.y = positions[k + i + 1];
  34302. v3.z = positions[k + i + 2];
  34303. v4.x = positions[k + i + 3];
  34304. v4.y = positions[k + i + 4];
  34305. v4.z = positions[k + i + 5];
  34306. // 2D slope V1V4
  34307. cd = (v4.z - v1.z) / (v4.x - v1.x);
  34308. h = v1.z - cd * v1.x; // v1 belongs to the slope
  34309. // facet equations :
  34310. // we compute each facet normal vector
  34311. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  34312. // we compute the value d by applying the equation to v1 which belongs to the plane
  34313. // then we store the facet equation in a Vector4
  34314. v2.subtractToRef(v1, v1v2);
  34315. v3.subtractToRef(v1, v1v3);
  34316. v4.subtractToRef(v1, v1v4);
  34317. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  34318. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  34319. norm1.normalize();
  34320. norm2.normalize();
  34321. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  34322. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  34323. var quad = this._heightQuads[row * this._subdivisions + col];
  34324. quad.slope.copyFromFloats(cd, h);
  34325. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  34326. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  34327. }
  34328. }
  34329. };
  34330. return GroundMesh;
  34331. }(BABYLON.Mesh));
  34332. BABYLON.GroundMesh = GroundMesh;
  34333. })(BABYLON || (BABYLON = {}));
  34334. var BABYLON;
  34335. (function (BABYLON) {
  34336. var LinesMesh = (function (_super) {
  34337. __extends(LinesMesh, _super);
  34338. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  34339. if (parent === void 0) { parent = null; }
  34340. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  34341. this.color = new BABYLON.Color3(1, 1, 1);
  34342. this.alpha = 1;
  34343. this._positionBuffer = {};
  34344. if (source) {
  34345. this.color = source.color.clone();
  34346. this.alpha = source.alpha;
  34347. }
  34348. this._intersectionThreshold = 0.1;
  34349. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  34350. attributes: [BABYLON.VertexBuffer.PositionKind],
  34351. uniforms: ["worldViewProjection", "color"],
  34352. needAlphaBlending: true
  34353. });
  34354. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  34355. }
  34356. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  34357. /**
  34358. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  34359. * This margin is expressed in world space coordinates, so its value may vary.
  34360. * Default value is 0.1
  34361. * @returns the intersection Threshold value.
  34362. */
  34363. get: function () {
  34364. return this._intersectionThreshold;
  34365. },
  34366. /**
  34367. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  34368. * This margin is expressed in world space coordinates, so its value may vary.
  34369. * @param value the new threshold to apply
  34370. */
  34371. set: function (value) {
  34372. if (this._intersectionThreshold === value) {
  34373. return;
  34374. }
  34375. this._intersectionThreshold = value;
  34376. if (this.geometry) {
  34377. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  34378. }
  34379. },
  34380. enumerable: true,
  34381. configurable: true
  34382. });
  34383. Object.defineProperty(LinesMesh.prototype, "material", {
  34384. get: function () {
  34385. return this._colorShader;
  34386. },
  34387. enumerable: true,
  34388. configurable: true
  34389. });
  34390. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  34391. get: function () {
  34392. return false;
  34393. },
  34394. enumerable: true,
  34395. configurable: true
  34396. });
  34397. LinesMesh.prototype.createInstance = function (name) {
  34398. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  34399. return null;
  34400. };
  34401. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  34402. var engine = this.getScene().getEngine();
  34403. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  34404. // VBOs
  34405. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  34406. // Color
  34407. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  34408. };
  34409. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  34410. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  34411. return;
  34412. }
  34413. var engine = this.getScene().getEngine();
  34414. // Draw order
  34415. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  34416. };
  34417. LinesMesh.prototype.dispose = function (doNotRecurse) {
  34418. this._colorShader.dispose();
  34419. _super.prototype.dispose.call(this, doNotRecurse);
  34420. };
  34421. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  34422. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  34423. };
  34424. return LinesMesh;
  34425. }(BABYLON.Mesh));
  34426. BABYLON.LinesMesh = LinesMesh;
  34427. })(BABYLON || (BABYLON = {}));
  34428. var BABYLON;
  34429. (function (BABYLON) {
  34430. var DefaultLoadingScreen = (function () {
  34431. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  34432. var _this = this;
  34433. if (_loadingText === void 0) { _loadingText = ""; }
  34434. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  34435. this._renderingCanvas = _renderingCanvas;
  34436. this._loadingText = _loadingText;
  34437. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  34438. // Resize
  34439. this._resizeLoadingUI = function () {
  34440. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  34441. _this._loadingDiv.style.position = "absolute";
  34442. _this._loadingDiv.style.left = canvasRect.left + "px";
  34443. _this._loadingDiv.style.top = canvasRect.top + "px";
  34444. _this._loadingDiv.style.width = canvasRect.width + "px";
  34445. _this._loadingDiv.style.height = canvasRect.height + "px";
  34446. };
  34447. }
  34448. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  34449. var _this = this;
  34450. if (this._loadingDiv) {
  34451. // Do not add a loading screen if there is already one
  34452. return;
  34453. }
  34454. this._loadingDiv = document.createElement("div");
  34455. this._loadingDiv.id = "babylonjsLoadingDiv";
  34456. this._loadingDiv.style.opacity = "0";
  34457. this._loadingDiv.style.transition = "opacity 1.5s ease";
  34458. // Loading text
  34459. this._loadingTextDiv = document.createElement("div");
  34460. this._loadingTextDiv.style.position = "absolute";
  34461. this._loadingTextDiv.style.left = "0";
  34462. this._loadingTextDiv.style.top = "50%";
  34463. this._loadingTextDiv.style.marginTop = "80px";
  34464. this._loadingTextDiv.style.width = "100%";
  34465. this._loadingTextDiv.style.height = "20px";
  34466. this._loadingTextDiv.style.fontFamily = "Arial";
  34467. this._loadingTextDiv.style.fontSize = "14px";
  34468. this._loadingTextDiv.style.color = "white";
  34469. this._loadingTextDiv.style.textAlign = "center";
  34470. this._loadingTextDiv.innerHTML = "Loading";
  34471. this._loadingDiv.appendChild(this._loadingTextDiv);
  34472. //set the predefined text
  34473. this._loadingTextDiv.innerHTML = this._loadingText;
  34474. // Loading img
  34475. var imgBack = new Image();
  34476. 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==";
  34477. imgBack.style.position = "absolute";
  34478. imgBack.style.left = "50%";
  34479. imgBack.style.top = "50%";
  34480. imgBack.style.marginLeft = "-50px";
  34481. imgBack.style.marginTop = "-50px";
  34482. imgBack.style.transition = "transform 1.0s ease";
  34483. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  34484. var deg = 360;
  34485. var onTransitionEnd = function () {
  34486. deg += 360;
  34487. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  34488. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  34489. };
  34490. imgBack.addEventListener("transitionend", onTransitionEnd);
  34491. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  34492. this._loadingDiv.appendChild(imgBack);
  34493. // front image
  34494. var imgFront = new Image();
  34495. 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=";
  34496. imgFront.style.position = "absolute";
  34497. imgFront.style.left = "50%";
  34498. imgFront.style.top = "50%";
  34499. imgFront.style.marginLeft = "-50px";
  34500. imgFront.style.marginTop = "-50px";
  34501. this._loadingDiv.appendChild(imgFront);
  34502. this._resizeLoadingUI();
  34503. window.addEventListener("resize", this._resizeLoadingUI);
  34504. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  34505. document.body.appendChild(this._loadingDiv);
  34506. setTimeout(function () {
  34507. _this._loadingDiv.style.opacity = "1";
  34508. imgBack.style.transform = "rotateZ(360deg)";
  34509. imgBack.style.webkitTransform = "rotateZ(360deg)";
  34510. }, 0);
  34511. };
  34512. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  34513. var _this = this;
  34514. if (!this._loadingDiv) {
  34515. return;
  34516. }
  34517. var onTransitionEnd = function () {
  34518. if (!_this._loadingDiv) {
  34519. return;
  34520. }
  34521. document.body.removeChild(_this._loadingDiv);
  34522. window.removeEventListener("resize", _this._resizeLoadingUI);
  34523. _this._loadingDiv = null;
  34524. };
  34525. this._loadingDiv.style.opacity = "0";
  34526. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  34527. };
  34528. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  34529. set: function (text) {
  34530. this._loadingText = text;
  34531. if (this._loadingTextDiv) {
  34532. this._loadingTextDiv.innerHTML = this._loadingText;
  34533. }
  34534. },
  34535. enumerable: true,
  34536. configurable: true
  34537. });
  34538. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  34539. get: function () {
  34540. return this._loadingDivBackgroundColor;
  34541. },
  34542. set: function (color) {
  34543. this._loadingDivBackgroundColor = color;
  34544. if (!this._loadingDiv) {
  34545. return;
  34546. }
  34547. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  34548. },
  34549. enumerable: true,
  34550. configurable: true
  34551. });
  34552. return DefaultLoadingScreen;
  34553. }());
  34554. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  34555. })(BABYLON || (BABYLON = {}));
  34556. var BABYLON;
  34557. (function (BABYLON) {
  34558. var AudioEngine = (function () {
  34559. function AudioEngine() {
  34560. this._audioContext = null;
  34561. this._audioContextInitialized = false;
  34562. this.canUseWebAudio = false;
  34563. this.WarnedWebAudioUnsupported = false;
  34564. this.unlocked = false;
  34565. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  34566. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  34567. this.canUseWebAudio = true;
  34568. }
  34569. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  34570. this._unlockiOSaudio();
  34571. }
  34572. else {
  34573. this.unlocked = true;
  34574. }
  34575. }
  34576. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  34577. get: function () {
  34578. if (!this._audioContextInitialized) {
  34579. this._initializeAudioContext();
  34580. }
  34581. return this._audioContext;
  34582. },
  34583. enumerable: true,
  34584. configurable: true
  34585. });
  34586. AudioEngine.prototype._unlockiOSaudio = function () {
  34587. var _this = this;
  34588. var unlockaudio = function () {
  34589. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  34590. var source = _this.audioContext.createBufferSource();
  34591. source.buffer = buffer;
  34592. source.connect(_this.audioContext.destination);
  34593. source.start(0);
  34594. setTimeout(function () {
  34595. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  34596. _this.unlocked = true;
  34597. window.removeEventListener('touchend', unlockaudio, false);
  34598. if (_this.onAudioUnlocked) {
  34599. _this.onAudioUnlocked();
  34600. }
  34601. }
  34602. }, 0);
  34603. };
  34604. window.addEventListener('touchend', unlockaudio, false);
  34605. };
  34606. AudioEngine.prototype._initializeAudioContext = function () {
  34607. try {
  34608. if (this.canUseWebAudio) {
  34609. this._audioContext = new AudioContext();
  34610. // create a global volume gain node
  34611. this.masterGain = this._audioContext.createGain();
  34612. this.masterGain.gain.value = 1;
  34613. this.masterGain.connect(this._audioContext.destination);
  34614. this._audioContextInitialized = true;
  34615. }
  34616. }
  34617. catch (e) {
  34618. this.canUseWebAudio = false;
  34619. BABYLON.Tools.Error("Web Audio: " + e.message);
  34620. }
  34621. };
  34622. AudioEngine.prototype.dispose = function () {
  34623. if (this.canUseWebAudio && this._audioContextInitialized) {
  34624. if (this._connectedAnalyser) {
  34625. this._connectedAnalyser.stopDebugCanvas();
  34626. this._connectedAnalyser.dispose();
  34627. this.masterGain.disconnect();
  34628. this.masterGain.connect(this._audioContext.destination);
  34629. this._connectedAnalyser = null;
  34630. }
  34631. this.masterGain.gain.value = 1;
  34632. }
  34633. this.WarnedWebAudioUnsupported = false;
  34634. };
  34635. AudioEngine.prototype.getGlobalVolume = function () {
  34636. if (this.canUseWebAudio && this._audioContextInitialized) {
  34637. return this.masterGain.gain.value;
  34638. }
  34639. else {
  34640. return -1;
  34641. }
  34642. };
  34643. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  34644. if (this.canUseWebAudio && this._audioContextInitialized) {
  34645. this.masterGain.gain.value = newVolume;
  34646. }
  34647. };
  34648. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  34649. if (this._connectedAnalyser) {
  34650. this._connectedAnalyser.stopDebugCanvas();
  34651. }
  34652. if (this.canUseWebAudio && this._audioContextInitialized) {
  34653. this._connectedAnalyser = analyser;
  34654. this.masterGain.disconnect();
  34655. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  34656. }
  34657. };
  34658. return AudioEngine;
  34659. }());
  34660. BABYLON.AudioEngine = AudioEngine;
  34661. })(BABYLON || (BABYLON = {}));
  34662. var BABYLON;
  34663. (function (BABYLON) {
  34664. var Sound = (function () {
  34665. /**
  34666. * Create a sound and attach it to a scene
  34667. * @param name Name of your sound
  34668. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  34669. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  34670. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  34671. */
  34672. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  34673. var _this = this;
  34674. this.autoplay = false;
  34675. this.loop = false;
  34676. this.useCustomAttenuation = false;
  34677. this.spatialSound = false;
  34678. this.refDistance = 1;
  34679. this.rolloffFactor = 1;
  34680. this.maxDistance = 100;
  34681. this.distanceModel = "linear";
  34682. this._panningModel = "equalpower";
  34683. this._playbackRate = 1;
  34684. this._streaming = false;
  34685. this._startTime = 0;
  34686. this._startOffset = 0;
  34687. this._position = BABYLON.Vector3.Zero();
  34688. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  34689. this._volume = 1;
  34690. this._isLoaded = false;
  34691. this._isReadyToPlay = false;
  34692. this.isPlaying = false;
  34693. this.isPaused = false;
  34694. this._isDirectional = false;
  34695. // Used if you'd like to create a directional sound.
  34696. // If not set, the sound will be omnidirectional
  34697. this._coneInnerAngle = 360;
  34698. this._coneOuterAngle = 360;
  34699. this._coneOuterGain = 0;
  34700. this._isOutputConnected = false;
  34701. this.name = name;
  34702. this._scene = scene;
  34703. this._readyToPlayCallback = readyToPlayCallback;
  34704. // Default custom attenuation function is a linear attenuation
  34705. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  34706. if (currentDistance < maxDistance) {
  34707. return currentVolume * (1 - currentDistance / maxDistance);
  34708. }
  34709. else {
  34710. return 0;
  34711. }
  34712. };
  34713. if (options) {
  34714. this.autoplay = options.autoplay || false;
  34715. this.loop = options.loop || false;
  34716. // if volume === 0, we need another way to check this option
  34717. if (options.volume !== undefined) {
  34718. this._volume = options.volume;
  34719. }
  34720. this.spatialSound = options.spatialSound || false;
  34721. this.maxDistance = options.maxDistance || 100;
  34722. this.useCustomAttenuation = options.useCustomAttenuation || false;
  34723. this.rolloffFactor = options.rolloffFactor || 1;
  34724. this.refDistance = options.refDistance || 1;
  34725. this.distanceModel = options.distanceModel || "linear";
  34726. this._playbackRate = options.playbackRate || 1;
  34727. this._streaming = options.streaming || false;
  34728. }
  34729. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34730. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  34731. this._soundGain.gain.value = this._volume;
  34732. this._inputAudioNode = this._soundGain;
  34733. this._ouputAudioNode = this._soundGain;
  34734. if (this.spatialSound) {
  34735. this._createSpatialParameters();
  34736. }
  34737. this._scene.mainSoundTrack.AddSound(this);
  34738. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  34739. if (urlOrArrayBuffer) {
  34740. // If it's an URL
  34741. if (typeof (urlOrArrayBuffer) === "string") {
  34742. // Loading sound using XHR2
  34743. if (!this._streaming) {
  34744. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  34745. }
  34746. else {
  34747. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  34748. this._htmlAudioElement.controls = false;
  34749. this._htmlAudioElement.loop = this.loop;
  34750. this._htmlAudioElement.crossOrigin = "anonymous";
  34751. this._htmlAudioElement.preload = "auto";
  34752. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  34753. _this._isReadyToPlay = true;
  34754. if (_this.autoplay) {
  34755. _this.play();
  34756. }
  34757. if (_this._readyToPlayCallback) {
  34758. _this._readyToPlayCallback();
  34759. }
  34760. });
  34761. document.body.appendChild(this._htmlAudioElement);
  34762. }
  34763. }
  34764. else {
  34765. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  34766. if (urlOrArrayBuffer.byteLength > 0) {
  34767. this._soundLoaded(urlOrArrayBuffer);
  34768. }
  34769. }
  34770. else {
  34771. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  34772. }
  34773. }
  34774. }
  34775. }
  34776. else {
  34777. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  34778. this._scene.mainSoundTrack.AddSound(this);
  34779. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  34780. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  34781. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  34782. }
  34783. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  34784. if (this._readyToPlayCallback) {
  34785. window.setTimeout(function () {
  34786. _this._readyToPlayCallback();
  34787. }, 1000);
  34788. }
  34789. }
  34790. }
  34791. Sound.prototype.dispose = function () {
  34792. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  34793. if (this.isPlaying) {
  34794. this.stop();
  34795. }
  34796. this._isReadyToPlay = false;
  34797. if (this.soundTrackId === -1) {
  34798. this._scene.mainSoundTrack.RemoveSound(this);
  34799. }
  34800. else {
  34801. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  34802. }
  34803. if (this._soundGain) {
  34804. this._soundGain.disconnect();
  34805. this._soundGain = null;
  34806. }
  34807. if (this._soundPanner) {
  34808. this._soundPanner.disconnect();
  34809. this._soundPanner = null;
  34810. }
  34811. if (this._soundSource) {
  34812. this._soundSource.disconnect();
  34813. this._soundSource = null;
  34814. }
  34815. this._audioBuffer = null;
  34816. if (this._htmlAudioElement) {
  34817. this._htmlAudioElement.pause();
  34818. this._htmlAudioElement.src = "";
  34819. document.body.removeChild(this._htmlAudioElement);
  34820. }
  34821. if (this._connectedMesh) {
  34822. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34823. this._connectedMesh = null;
  34824. }
  34825. }
  34826. };
  34827. Sound.prototype._soundLoaded = function (audioData) {
  34828. var _this = this;
  34829. this._isLoaded = true;
  34830. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  34831. _this._audioBuffer = buffer;
  34832. _this._isReadyToPlay = true;
  34833. if (_this.autoplay) {
  34834. _this.play();
  34835. }
  34836. if (_this._readyToPlayCallback) {
  34837. _this._readyToPlayCallback();
  34838. }
  34839. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  34840. };
  34841. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  34842. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34843. this._audioBuffer = audioBuffer;
  34844. this._isReadyToPlay = true;
  34845. }
  34846. };
  34847. Sound.prototype.updateOptions = function (options) {
  34848. if (options) {
  34849. this.loop = options.loop || this.loop;
  34850. this.maxDistance = options.maxDistance || this.maxDistance;
  34851. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  34852. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  34853. this.refDistance = options.refDistance || this.refDistance;
  34854. this.distanceModel = options.distanceModel || this.distanceModel;
  34855. this._playbackRate = options.playbackRate || this._playbackRate;
  34856. this._updateSpatialParameters();
  34857. if (this.isPlaying) {
  34858. if (this._streaming) {
  34859. this._htmlAudioElement.playbackRate = this._playbackRate;
  34860. }
  34861. else {
  34862. this._soundSource.playbackRate.value = this._playbackRate;
  34863. }
  34864. }
  34865. }
  34866. };
  34867. Sound.prototype._createSpatialParameters = function () {
  34868. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34869. if (this._scene.headphone) {
  34870. this._panningModel = "HRTF";
  34871. }
  34872. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  34873. this._updateSpatialParameters();
  34874. this._soundPanner.connect(this._ouputAudioNode);
  34875. this._inputAudioNode = this._soundPanner;
  34876. }
  34877. };
  34878. Sound.prototype._updateSpatialParameters = function () {
  34879. if (this.spatialSound) {
  34880. if (this.useCustomAttenuation) {
  34881. // Tricks to disable in a way embedded Web Audio attenuation
  34882. this._soundPanner.distanceModel = "linear";
  34883. this._soundPanner.maxDistance = Number.MAX_VALUE;
  34884. this._soundPanner.refDistance = 1;
  34885. this._soundPanner.rolloffFactor = 1;
  34886. this._soundPanner.panningModel = this._panningModel;
  34887. }
  34888. else {
  34889. this._soundPanner.distanceModel = this.distanceModel;
  34890. this._soundPanner.maxDistance = this.maxDistance;
  34891. this._soundPanner.refDistance = this.refDistance;
  34892. this._soundPanner.rolloffFactor = this.rolloffFactor;
  34893. this._soundPanner.panningModel = this._panningModel;
  34894. }
  34895. }
  34896. };
  34897. Sound.prototype.switchPanningModelToHRTF = function () {
  34898. this._panningModel = "HRTF";
  34899. this._switchPanningModel();
  34900. };
  34901. Sound.prototype.switchPanningModelToEqualPower = function () {
  34902. this._panningModel = "equalpower";
  34903. this._switchPanningModel();
  34904. };
  34905. Sound.prototype._switchPanningModel = function () {
  34906. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34907. this._soundPanner.panningModel = this._panningModel;
  34908. }
  34909. };
  34910. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  34911. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34912. if (this._isOutputConnected) {
  34913. this._ouputAudioNode.disconnect();
  34914. }
  34915. this._ouputAudioNode.connect(soundTrackAudioNode);
  34916. this._isOutputConnected = true;
  34917. }
  34918. };
  34919. /**
  34920. * Transform this sound into a directional source
  34921. * @param coneInnerAngle Size of the inner cone in degree
  34922. * @param coneOuterAngle Size of the outer cone in degree
  34923. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  34924. */
  34925. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  34926. if (coneOuterAngle < coneInnerAngle) {
  34927. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  34928. return;
  34929. }
  34930. this._coneInnerAngle = coneInnerAngle;
  34931. this._coneOuterAngle = coneOuterAngle;
  34932. this._coneOuterGain = coneOuterGain;
  34933. this._isDirectional = true;
  34934. if (this.isPlaying && this.loop) {
  34935. this.stop();
  34936. this.play();
  34937. }
  34938. };
  34939. Sound.prototype.setPosition = function (newPosition) {
  34940. this._position = newPosition;
  34941. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34942. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34943. }
  34944. };
  34945. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  34946. this._localDirection = newLocalDirection;
  34947. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  34948. this._updateDirection();
  34949. }
  34950. };
  34951. Sound.prototype._updateDirection = function () {
  34952. var mat = this._connectedMesh.getWorldMatrix();
  34953. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  34954. direction.normalize();
  34955. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  34956. };
  34957. Sound.prototype.updateDistanceFromListener = function () {
  34958. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  34959. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  34960. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  34961. }
  34962. };
  34963. Sound.prototype.setAttenuationFunction = function (callback) {
  34964. this._customAttenuationFunction = callback;
  34965. };
  34966. /**
  34967. * Play the sound
  34968. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  34969. * @param offset (optional) Start the sound setting it at a specific time
  34970. */
  34971. Sound.prototype.play = function (time, offset) {
  34972. var _this = this;
  34973. if (this._isReadyToPlay && this._scene.audioEnabled) {
  34974. try {
  34975. if (this._startOffset < 0) {
  34976. time = -this._startOffset;
  34977. this._startOffset = 0;
  34978. }
  34979. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34980. if (!this._soundSource || !this._streamingSource) {
  34981. if (this.spatialSound) {
  34982. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34983. if (this._isDirectional) {
  34984. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  34985. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  34986. this._soundPanner.coneOuterGain = this._coneOuterGain;
  34987. if (this._connectedMesh) {
  34988. this._updateDirection();
  34989. }
  34990. else {
  34991. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  34992. }
  34993. }
  34994. }
  34995. }
  34996. if (this._streaming) {
  34997. if (!this._streamingSource) {
  34998. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  34999. this._htmlAudioElement.onended = function () { _this._onended(); };
  35000. this._htmlAudioElement.playbackRate = this._playbackRate;
  35001. }
  35002. this._streamingSource.disconnect();
  35003. this._streamingSource.connect(this._inputAudioNode);
  35004. this._htmlAudioElement.play();
  35005. }
  35006. else {
  35007. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  35008. this._soundSource.buffer = this._audioBuffer;
  35009. this._soundSource.connect(this._inputAudioNode);
  35010. this._soundSource.loop = this.loop;
  35011. this._soundSource.playbackRate.value = this._playbackRate;
  35012. this._soundSource.onended = function () { _this._onended(); };
  35013. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  35014. }
  35015. this._startTime = startTime;
  35016. this.isPlaying = true;
  35017. this.isPaused = false;
  35018. }
  35019. catch (ex) {
  35020. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  35021. }
  35022. }
  35023. };
  35024. Sound.prototype._onended = function () {
  35025. this.isPlaying = false;
  35026. if (this.onended) {
  35027. this.onended();
  35028. }
  35029. };
  35030. /**
  35031. * Stop the sound
  35032. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  35033. */
  35034. Sound.prototype.stop = function (time) {
  35035. if (this.isPlaying) {
  35036. if (this._streaming) {
  35037. this._htmlAudioElement.pause();
  35038. // Test needed for Firefox or it will generate an Invalid State Error
  35039. if (this._htmlAudioElement.currentTime > 0) {
  35040. this._htmlAudioElement.currentTime = 0;
  35041. }
  35042. }
  35043. else {
  35044. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35045. this._soundSource.stop(stopTime);
  35046. this._soundSource.onended = null;
  35047. if (!this.isPaused) {
  35048. this._startOffset = 0;
  35049. }
  35050. }
  35051. this.isPlaying = false;
  35052. }
  35053. };
  35054. Sound.prototype.pause = function () {
  35055. if (this.isPlaying) {
  35056. this.isPaused = true;
  35057. if (this._streaming) {
  35058. this._htmlAudioElement.pause();
  35059. }
  35060. else {
  35061. this.stop(0);
  35062. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  35063. }
  35064. }
  35065. };
  35066. Sound.prototype.setVolume = function (newVolume, time) {
  35067. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35068. if (time) {
  35069. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  35070. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  35071. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  35072. }
  35073. else {
  35074. this._soundGain.gain.value = newVolume;
  35075. }
  35076. }
  35077. this._volume = newVolume;
  35078. };
  35079. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  35080. this._playbackRate = newPlaybackRate;
  35081. if (this.isPlaying) {
  35082. if (this._streaming) {
  35083. this._htmlAudioElement.playbackRate = this._playbackRate;
  35084. }
  35085. else {
  35086. this._soundSource.playbackRate.value = this._playbackRate;
  35087. }
  35088. }
  35089. };
  35090. Sound.prototype.getVolume = function () {
  35091. return this._volume;
  35092. };
  35093. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  35094. var _this = this;
  35095. if (this._connectedMesh) {
  35096. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35097. this._registerFunc = null;
  35098. }
  35099. this._connectedMesh = meshToConnectTo;
  35100. if (!this.spatialSound) {
  35101. this.spatialSound = true;
  35102. this._createSpatialParameters();
  35103. if (this.isPlaying && this.loop) {
  35104. this.stop();
  35105. this.play();
  35106. }
  35107. }
  35108. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  35109. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  35110. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  35111. };
  35112. Sound.prototype.detachFromMesh = function () {
  35113. if (this._connectedMesh) {
  35114. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35115. this._registerFunc = null;
  35116. this._connectedMesh = null;
  35117. }
  35118. };
  35119. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  35120. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  35121. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  35122. this._updateDirection();
  35123. }
  35124. };
  35125. Sound.prototype.clone = function () {
  35126. var _this = this;
  35127. if (!this._streaming) {
  35128. var setBufferAndRun = function () {
  35129. if (_this._isReadyToPlay) {
  35130. clonedSound._audioBuffer = _this.getAudioBuffer();
  35131. clonedSound._isReadyToPlay = true;
  35132. if (clonedSound.autoplay) {
  35133. clonedSound.play();
  35134. }
  35135. }
  35136. else {
  35137. window.setTimeout(setBufferAndRun, 300);
  35138. }
  35139. };
  35140. var currentOptions = {
  35141. autoplay: this.autoplay, loop: this.loop,
  35142. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  35143. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  35144. refDistance: this.refDistance, distanceModel: this.distanceModel
  35145. };
  35146. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  35147. if (this.useCustomAttenuation) {
  35148. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  35149. }
  35150. clonedSound.setPosition(this._position);
  35151. clonedSound.setPlaybackRate(this._playbackRate);
  35152. setBufferAndRun();
  35153. return clonedSound;
  35154. }
  35155. else {
  35156. return null;
  35157. }
  35158. };
  35159. Sound.prototype.getAudioBuffer = function () {
  35160. return this._audioBuffer;
  35161. };
  35162. Sound.prototype.serialize = function () {
  35163. var serializationObject = {
  35164. name: this.name,
  35165. url: this.name,
  35166. autoplay: this.autoplay,
  35167. loop: this.loop,
  35168. volume: this._volume,
  35169. spatialSound: this.spatialSound,
  35170. maxDistance: this.maxDistance,
  35171. rolloffFactor: this.rolloffFactor,
  35172. refDistance: this.refDistance,
  35173. distanceModel: this.distanceModel,
  35174. playbackRate: this._playbackRate,
  35175. panningModel: this._panningModel,
  35176. soundTrackId: this.soundTrackId
  35177. };
  35178. if (this.spatialSound) {
  35179. if (this._connectedMesh)
  35180. serializationObject.connectedMeshId = this._connectedMesh.id;
  35181. serializationObject.position = this._position.asArray();
  35182. serializationObject.refDistance = this.refDistance;
  35183. serializationObject.distanceModel = this.distanceModel;
  35184. serializationObject.isDirectional = this._isDirectional;
  35185. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  35186. serializationObject.coneInnerAngle = this._coneInnerAngle;
  35187. serializationObject.coneOuterAngle = this._coneOuterAngle;
  35188. serializationObject.coneOuterGain = this._coneOuterGain;
  35189. }
  35190. return serializationObject;
  35191. };
  35192. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  35193. var soundName = parsedSound.name;
  35194. var soundUrl;
  35195. if (parsedSound.url) {
  35196. soundUrl = rootUrl + parsedSound.url;
  35197. }
  35198. else {
  35199. soundUrl = rootUrl + soundName;
  35200. }
  35201. var options = {
  35202. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  35203. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  35204. rolloffFactor: parsedSound.rolloffFactor,
  35205. refDistance: parsedSound.refDistance,
  35206. distanceModel: parsedSound.distanceModel,
  35207. playbackRate: parsedSound.playbackRate
  35208. };
  35209. var newSound;
  35210. if (!sourceSound) {
  35211. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  35212. scene._addPendingData(newSound);
  35213. }
  35214. else {
  35215. var setBufferAndRun = function () {
  35216. if (sourceSound._isReadyToPlay) {
  35217. newSound._audioBuffer = sourceSound.getAudioBuffer();
  35218. newSound._isReadyToPlay = true;
  35219. if (newSound.autoplay) {
  35220. newSound.play();
  35221. }
  35222. }
  35223. else {
  35224. window.setTimeout(setBufferAndRun, 300);
  35225. }
  35226. };
  35227. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  35228. setBufferAndRun();
  35229. }
  35230. if (parsedSound.position) {
  35231. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  35232. newSound.setPosition(soundPosition);
  35233. }
  35234. if (parsedSound.isDirectional) {
  35235. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  35236. if (parsedSound.localDirectionToMesh) {
  35237. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  35238. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  35239. }
  35240. }
  35241. if (parsedSound.connectedMeshId) {
  35242. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  35243. if (connectedMesh) {
  35244. newSound.attachToMesh(connectedMesh);
  35245. }
  35246. }
  35247. return newSound;
  35248. };
  35249. return Sound;
  35250. }());
  35251. BABYLON.Sound = Sound;
  35252. })(BABYLON || (BABYLON = {}));
  35253. var BABYLON;
  35254. (function (BABYLON) {
  35255. var SoundTrack = (function () {
  35256. function SoundTrack(scene, options) {
  35257. this.id = -1;
  35258. this._isMainTrack = false;
  35259. this._isInitialized = false;
  35260. this._scene = scene;
  35261. this.soundCollection = new Array();
  35262. this._options = options;
  35263. if (!this._isMainTrack) {
  35264. this._scene.soundTracks.push(this);
  35265. this.id = this._scene.soundTracks.length - 1;
  35266. }
  35267. }
  35268. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  35269. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35270. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  35271. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  35272. if (this._options) {
  35273. if (this._options.volume) {
  35274. this._outputAudioNode.gain.value = this._options.volume;
  35275. }
  35276. if (this._options.mainTrack) {
  35277. this._isMainTrack = this._options.mainTrack;
  35278. }
  35279. }
  35280. this._isInitialized = true;
  35281. }
  35282. };
  35283. SoundTrack.prototype.dispose = function () {
  35284. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35285. if (this._connectedAnalyser) {
  35286. this._connectedAnalyser.stopDebugCanvas();
  35287. }
  35288. while (this.soundCollection.length) {
  35289. this.soundCollection[0].dispose();
  35290. }
  35291. if (this._outputAudioNode) {
  35292. this._outputAudioNode.disconnect();
  35293. }
  35294. this._outputAudioNode = null;
  35295. }
  35296. };
  35297. SoundTrack.prototype.AddSound = function (sound) {
  35298. if (!this._isInitialized) {
  35299. this._initializeSoundTrackAudioGraph();
  35300. }
  35301. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35302. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  35303. }
  35304. if (sound.soundTrackId) {
  35305. if (sound.soundTrackId === -1) {
  35306. this._scene.mainSoundTrack.RemoveSound(sound);
  35307. }
  35308. else {
  35309. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  35310. }
  35311. }
  35312. this.soundCollection.push(sound);
  35313. sound.soundTrackId = this.id;
  35314. };
  35315. SoundTrack.prototype.RemoveSound = function (sound) {
  35316. var index = this.soundCollection.indexOf(sound);
  35317. if (index !== -1) {
  35318. this.soundCollection.splice(index, 1);
  35319. }
  35320. };
  35321. SoundTrack.prototype.setVolume = function (newVolume) {
  35322. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35323. this._outputAudioNode.gain.value = newVolume;
  35324. }
  35325. };
  35326. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  35327. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35328. for (var i = 0; i < this.soundCollection.length; i++) {
  35329. this.soundCollection[i].switchPanningModelToHRTF();
  35330. }
  35331. }
  35332. };
  35333. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  35334. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35335. for (var i = 0; i < this.soundCollection.length; i++) {
  35336. this.soundCollection[i].switchPanningModelToEqualPower();
  35337. }
  35338. }
  35339. };
  35340. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  35341. if (this._connectedAnalyser) {
  35342. this._connectedAnalyser.stopDebugCanvas();
  35343. }
  35344. this._connectedAnalyser = analyser;
  35345. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35346. this._outputAudioNode.disconnect();
  35347. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  35348. }
  35349. };
  35350. return SoundTrack;
  35351. }());
  35352. BABYLON.SoundTrack = SoundTrack;
  35353. })(BABYLON || (BABYLON = {}));
  35354. var BABYLON;
  35355. (function (BABYLON) {
  35356. var SIMDVector3 = (function () {
  35357. function SIMDVector3() {
  35358. }
  35359. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  35360. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  35361. var m0 = SIMD.float32x4.load(transformation.m, 0);
  35362. var m1 = SIMD.float32x4.load(transformation.m, 4);
  35363. var m2 = SIMD.float32x4.load(transformation.m, 8);
  35364. var m3 = SIMD.float32x4.load(transformation.m, 12);
  35365. 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));
  35366. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  35367. SIMD.float32x4.storeXYZ(result._data, 0, r);
  35368. };
  35369. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  35370. var v0 = SIMD.float32x4.splat(x);
  35371. var v1 = SIMD.float32x4.splat(y);
  35372. var v2 = SIMD.float32x4.splat(z);
  35373. var m0 = SIMD.float32x4.load(transformation.m, 0);
  35374. var m1 = SIMD.float32x4.load(transformation.m, 4);
  35375. var m2 = SIMD.float32x4.load(transformation.m, 8);
  35376. var m3 = SIMD.float32x4.load(transformation.m, 12);
  35377. 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));
  35378. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  35379. SIMD.float32x4.storeXYZ(result._data, 0, r);
  35380. };
  35381. return SIMDVector3;
  35382. }());
  35383. BABYLON.SIMDVector3 = SIMDVector3;
  35384. var SIMDMatrix = (function () {
  35385. function SIMDMatrix() {
  35386. }
  35387. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  35388. if (offset === void 0) { offset = 0; }
  35389. var tm = this.m;
  35390. var om = other.m;
  35391. var om0 = SIMD.float32x4.load(om, 0);
  35392. var om1 = SIMD.float32x4.load(om, 4);
  35393. var om2 = SIMD.float32x4.load(om, 8);
  35394. var om3 = SIMD.float32x4.load(om, 12);
  35395. var tm0 = SIMD.float32x4.load(tm, 0);
  35396. 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)))));
  35397. var tm1 = SIMD.float32x4.load(tm, 4);
  35398. 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)))));
  35399. var tm2 = SIMD.float32x4.load(tm, 8);
  35400. 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)))));
  35401. var tm3 = SIMD.float32x4.load(tm, 12);
  35402. 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)))));
  35403. };
  35404. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  35405. var src = this.m;
  35406. var dest = other.m;
  35407. var row0, row1, row2, row3;
  35408. var tmp1;
  35409. var minor0, minor1, minor2, minor3;
  35410. var det;
  35411. // Load the 4 rows
  35412. var src0 = SIMD.float32x4.load(src, 0);
  35413. var src1 = SIMD.float32x4.load(src, 4);
  35414. var src2 = SIMD.float32x4.load(src, 8);
  35415. var src3 = SIMD.float32x4.load(src, 12);
  35416. // Transpose the source matrix. Sort of. Not a true transpose operation
  35417. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  35418. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  35419. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  35420. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  35421. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  35422. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  35423. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  35424. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  35425. // This is a true transposition, but it will lead to an incorrect result
  35426. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  35427. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  35428. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  35429. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  35430. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  35431. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  35432. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  35433. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  35434. // ----
  35435. tmp1 = SIMD.float32x4.mul(row2, row3);
  35436. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35437. minor0 = SIMD.float32x4.mul(row1, tmp1);
  35438. minor1 = SIMD.float32x4.mul(row0, tmp1);
  35439. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35440. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  35441. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  35442. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  35443. // ----
  35444. tmp1 = SIMD.float32x4.mul(row1, row2);
  35445. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35446. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  35447. minor3 = SIMD.float32x4.mul(row0, tmp1);
  35448. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35449. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  35450. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  35451. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  35452. // ----
  35453. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  35454. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35455. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  35456. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  35457. minor2 = SIMD.float32x4.mul(row0, tmp1);
  35458. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35459. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  35460. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  35461. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  35462. // ----
  35463. tmp1 = SIMD.float32x4.mul(row0, row1);
  35464. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35465. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  35466. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  35467. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35468. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  35469. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  35470. // ----
  35471. tmp1 = SIMD.float32x4.mul(row0, row3);
  35472. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35473. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  35474. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  35475. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35476. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  35477. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  35478. // ----
  35479. tmp1 = SIMD.float32x4.mul(row0, row2);
  35480. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35481. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  35482. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  35483. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35484. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  35485. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  35486. // Compute determinant
  35487. det = SIMD.float32x4.mul(row0, minor0);
  35488. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  35489. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  35490. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  35491. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  35492. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  35493. // These shuffles aren't necessary if the faulty transposition is done
  35494. // up at the top of this function.
  35495. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  35496. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  35497. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  35498. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  35499. // Compute final values by multiplying with 1/det
  35500. minor0 = SIMD.float32x4.mul(det, minor0);
  35501. minor1 = SIMD.float32x4.mul(det, minor1);
  35502. minor2 = SIMD.float32x4.mul(det, minor2);
  35503. minor3 = SIMD.float32x4.mul(det, minor3);
  35504. SIMD.float32x4.store(dest, 0, minor0);
  35505. SIMD.float32x4.store(dest, 4, minor1);
  35506. SIMD.float32x4.store(dest, 8, minor2);
  35507. SIMD.float32x4.store(dest, 12, minor3);
  35508. return this;
  35509. };
  35510. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  35511. var out = result.m;
  35512. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  35513. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  35514. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  35515. // cc.kmVec3Subtract(f, pCenter, pEye);
  35516. var f = SIMD.float32x4.sub(center, eye);
  35517. // cc.kmVec3Normalize(f, f);
  35518. var tmp = SIMD.float32x4.mul(f, f);
  35519. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  35520. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  35521. // cc.kmVec3Assign(up, pUp);
  35522. // cc.kmVec3Normalize(up, up);
  35523. tmp = SIMD.float32x4.mul(up, up);
  35524. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  35525. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  35526. // cc.kmVec3Cross(s, f, up);
  35527. 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)));
  35528. // cc.kmVec3Normalize(s, s);
  35529. tmp = SIMD.float32x4.mul(s, s);
  35530. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  35531. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  35532. // cc.kmVec3Cross(u, s, f);
  35533. 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)));
  35534. // cc.kmVec3Normalize(s, s);
  35535. tmp = SIMD.float32x4.mul(s, s);
  35536. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  35537. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  35538. var zero = SIMD.float32x4.splat(0.0);
  35539. s = SIMD.float32x4.neg(s);
  35540. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  35541. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  35542. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  35543. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  35544. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  35545. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  35546. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  35547. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  35548. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  35549. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  35550. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  35551. var b3 = SIMD.float32x4.neg(eye);
  35552. b3 = SIMD.float32x4.withW(b3, 1.0);
  35553. 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)))));
  35554. 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)))));
  35555. 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)))));
  35556. 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)))));
  35557. };
  35558. return SIMDMatrix;
  35559. }());
  35560. BABYLON.SIMDMatrix = SIMDMatrix;
  35561. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  35562. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  35563. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  35564. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  35565. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  35566. var SIMDHelper = (function () {
  35567. function SIMDHelper() {
  35568. }
  35569. Object.defineProperty(SIMDHelper, "IsEnabled", {
  35570. get: function () {
  35571. return SIMDHelper._isEnabled;
  35572. },
  35573. enumerable: true,
  35574. configurable: true
  35575. });
  35576. SIMDHelper.DisableSIMD = function () {
  35577. // Replace functions
  35578. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  35579. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  35580. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  35581. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  35582. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  35583. SIMDHelper._isEnabled = false;
  35584. };
  35585. SIMDHelper.EnableSIMD = function () {
  35586. if (window.SIMD === undefined) {
  35587. return;
  35588. }
  35589. // Replace functions
  35590. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  35591. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  35592. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  35593. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  35594. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  35595. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  35596. get: function () { return this._data[0]; },
  35597. set: function (value) {
  35598. if (!this._data) {
  35599. this._data = new Float32Array(3);
  35600. }
  35601. this._data[0] = value;
  35602. }
  35603. });
  35604. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  35605. get: function () { return this._data[1]; },
  35606. set: function (value) {
  35607. this._data[1] = value;
  35608. }
  35609. });
  35610. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  35611. get: function () { return this._data[2]; },
  35612. set: function (value) {
  35613. this._data[2] = value;
  35614. }
  35615. });
  35616. SIMDHelper._isEnabled = true;
  35617. };
  35618. SIMDHelper._isEnabled = false;
  35619. return SIMDHelper;
  35620. }());
  35621. BABYLON.SIMDHelper = SIMDHelper;
  35622. })(BABYLON || (BABYLON = {}));
  35623. var BABYLON;
  35624. (function (BABYLON) {
  35625. /**
  35626. * This class describe a rectangle that were added to the map.
  35627. * You have access to its coordinates either in pixel or normalized (UV)
  35628. */
  35629. var PackedRect = (function () {
  35630. function PackedRect(root, parent, pos, size) {
  35631. this._pos = pos;
  35632. this._size = size;
  35633. this._root = root;
  35634. this._parent = parent;
  35635. }
  35636. Object.defineProperty(PackedRect.prototype, "pos", {
  35637. /**
  35638. * @returns the position of this node into the map
  35639. */
  35640. get: function () {
  35641. return this._pos;
  35642. },
  35643. enumerable: true,
  35644. configurable: true
  35645. });
  35646. Object.defineProperty(PackedRect.prototype, "contentSize", {
  35647. /**
  35648. * @returns the size of the rectangle this node handles
  35649. */
  35650. get: function () {
  35651. return this._contentSize;
  35652. },
  35653. enumerable: true,
  35654. configurable: true
  35655. });
  35656. Object.defineProperty(PackedRect.prototype, "UVs", {
  35657. /**
  35658. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  35659. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  35660. */
  35661. get: function () {
  35662. return this.getUVsForCustomSize(this._root._size);
  35663. },
  35664. enumerable: true,
  35665. configurable: true
  35666. });
  35667. /**
  35668. * 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.
  35669. * This method will return the UVs for this part by given the custom size of what you really use
  35670. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  35671. */
  35672. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  35673. var mainWidth = this._root._size.width;
  35674. var mainHeight = this._root._size.height;
  35675. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  35676. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  35677. var uvs = new Array();
  35678. uvs.push(topLeft);
  35679. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  35680. uvs.push(rightBottom);
  35681. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  35682. return uvs;
  35683. };
  35684. /**
  35685. * Free this rectangle from the map.
  35686. * Call this method when you no longer need the rectangle to be in the map.
  35687. */
  35688. PackedRect.prototype.freeContent = function () {
  35689. if (!this.contentSize) {
  35690. return;
  35691. }
  35692. this._contentSize = null;
  35693. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  35694. this.attemptDefrag();
  35695. };
  35696. Object.defineProperty(PackedRect.prototype, "isUsed", {
  35697. get: function () {
  35698. return this._contentSize != null || this._leftNode != null;
  35699. },
  35700. enumerable: true,
  35701. configurable: true
  35702. });
  35703. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  35704. var node = this.findNode(contentSize);
  35705. // Not enough space...
  35706. if (!node) {
  35707. return null;
  35708. }
  35709. node.splitNode(contentSize);
  35710. return node;
  35711. };
  35712. PackedRect.prototype.findNode = function (size) {
  35713. var resNode = null;
  35714. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  35715. if (this.isUsed) {
  35716. if (this._leftNode) {
  35717. resNode = this._leftNode.findNode(size);
  35718. }
  35719. if (!resNode && this._rightNode) {
  35720. resNode = this._rightNode.findNode(size);
  35721. }
  35722. if (!resNode && this._bottomNode) {
  35723. resNode = this._bottomNode.findNode(size);
  35724. }
  35725. }
  35726. else if (this._initialSize && (size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  35727. resNode = this;
  35728. }
  35729. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  35730. resNode = this;
  35731. }
  35732. return resNode;
  35733. };
  35734. PackedRect.prototype.splitNode = function (contentSize) {
  35735. // 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)
  35736. if (!this._contentSize && this._initialSize) {
  35737. 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));
  35738. return this._leftNode.splitNode(contentSize);
  35739. }
  35740. else {
  35741. this._contentSize = contentSize.clone();
  35742. this._initialSize = contentSize.clone();
  35743. if (contentSize.width !== this._size.width) {
  35744. 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));
  35745. }
  35746. if (contentSize.height !== this._size.height) {
  35747. 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));
  35748. }
  35749. return this;
  35750. }
  35751. };
  35752. PackedRect.prototype.attemptDefrag = function () {
  35753. if (!this.isUsed && this.isRecursiveFree) {
  35754. this.clearNode();
  35755. if (this._parent) {
  35756. this._parent.attemptDefrag();
  35757. }
  35758. }
  35759. };
  35760. PackedRect.prototype.clearNode = function () {
  35761. this._initialSize = null;
  35762. this._rightNode = null;
  35763. this._bottomNode = null;
  35764. };
  35765. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  35766. get: function () {
  35767. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  35768. },
  35769. enumerable: true,
  35770. configurable: true
  35771. });
  35772. PackedRect.prototype.evalFreeSize = function (size) {
  35773. var levelSize = 0;
  35774. if (!this.isUsed) {
  35775. if (this._initialSize) {
  35776. levelSize = this._initialSize.surface;
  35777. }
  35778. else {
  35779. levelSize = this._size.surface;
  35780. }
  35781. }
  35782. if (this._rightNode) {
  35783. levelSize += this._rightNode.evalFreeSize(0);
  35784. }
  35785. if (this._bottomNode) {
  35786. levelSize += this._bottomNode.evalFreeSize(0);
  35787. }
  35788. return levelSize + size;
  35789. };
  35790. return PackedRect;
  35791. }());
  35792. BABYLON.PackedRect = PackedRect;
  35793. /**
  35794. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  35795. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  35796. * 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.
  35797. */
  35798. var RectPackingMap = (function (_super) {
  35799. __extends(RectPackingMap, _super);
  35800. /**
  35801. * Create an instance of the object with a dimension using the given size
  35802. * @param size The dimension of the rectangle that will contain all the sub ones.
  35803. */
  35804. function RectPackingMap(size) {
  35805. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  35806. this._root = this;
  35807. }
  35808. /**
  35809. * Add a rectangle, finding the best location to store it into the map
  35810. * @param size the dimension of the rectangle to store
  35811. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  35812. */
  35813. RectPackingMap.prototype.addRect = function (size) {
  35814. var node = this.findAndSplitNode(size);
  35815. return node;
  35816. };
  35817. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  35818. /**
  35819. * Return the current space free normalized between [0;1]
  35820. * @returns {}
  35821. */
  35822. get: function () {
  35823. var freeSize = 0;
  35824. freeSize = this.evalFreeSize(freeSize);
  35825. return freeSize / (this._size.width * this._size.height);
  35826. },
  35827. enumerable: true,
  35828. configurable: true
  35829. });
  35830. return RectPackingMap;
  35831. }(PackedRect));
  35832. BABYLON.RectPackingMap = RectPackingMap;
  35833. })(BABYLON || (BABYLON = {}));
  35834. var BABYLON;
  35835. (function (BABYLON) {
  35836. var DynamicFloatArrayElementInfo = (function () {
  35837. function DynamicFloatArrayElementInfo() {
  35838. }
  35839. return DynamicFloatArrayElementInfo;
  35840. }());
  35841. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  35842. /**
  35843. * 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.
  35844. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  35845. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  35846. * 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.
  35847. * 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.
  35848. * 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".
  35849. */
  35850. var DynamicFloatArray = (function () {
  35851. /**
  35852. * Construct an instance of the dynamic float array
  35853. * @param stride size of one element in float (i.e. not bytes!)
  35854. * @param initialElementCount the number of available entries at construction
  35855. */
  35856. function DynamicFloatArray(stride, initialElementCount) {
  35857. this.compareValueOffset = null;
  35858. this.sortingAscending = true;
  35859. this._stride = stride;
  35860. this.buffer = new Float32Array(stride * initialElementCount);
  35861. this._lastUsed = 0;
  35862. this._firstFree = 0;
  35863. this._allEntries = new Array(initialElementCount);
  35864. this._freeEntries = new Array(initialElementCount);
  35865. for (var i = 0; i < initialElementCount; i++) {
  35866. var element = new DynamicFloatArrayElementInfo();
  35867. element.offset = i * stride;
  35868. this._allEntries[i] = element;
  35869. this._freeEntries[initialElementCount - i - 1] = element;
  35870. }
  35871. }
  35872. /**
  35873. * Allocate an element in the array.
  35874. * @return the element info instance that contains the offset into the main buffer of the element's location.
  35875. * Beware, this offset may change when you call pack()
  35876. */
  35877. DynamicFloatArray.prototype.allocElement = function () {
  35878. if (this._freeEntries.length === 0) {
  35879. this._growBuffer();
  35880. }
  35881. var el = this._freeEntries.pop();
  35882. this._lastUsed = Math.max(el.offset, this._lastUsed);
  35883. if (el.offset === this._firstFree) {
  35884. if (this._freeEntries.length > 0) {
  35885. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  35886. }
  35887. else {
  35888. this._firstFree += this._stride;
  35889. }
  35890. }
  35891. return el;
  35892. };
  35893. /**
  35894. * Free the element corresponding to the given element info
  35895. * @param elInfo the element that describe the allocated element
  35896. */
  35897. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  35898. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  35899. this._freeEntries.push(elInfo);
  35900. };
  35901. /**
  35902. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  35903. * 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().
  35904. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  35905. */
  35906. DynamicFloatArray.prototype.pack = function () {
  35907. // no free slot? no need to pack
  35908. if (this._freeEntries.length === 0) {
  35909. return this.buffer;
  35910. }
  35911. // If the buffer is already packed the last used will always be lower than the first free
  35912. // 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.
  35913. if (this._lastUsed < this._firstFree) {
  35914. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  35915. return elementsBuffer_1;
  35916. }
  35917. var s = this._stride;
  35918. // 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
  35919. var lastFree = new DynamicFloatArrayElementInfo();
  35920. lastFree.offset = this.totalElementCount * s;
  35921. this._freeEntries.push(lastFree);
  35922. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  35923. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  35924. var firstFreeSlotOffset = sortedFree[0].offset;
  35925. var freeZoneSize = 1;
  35926. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  35927. var prevOffset = sortedFree[0].offset;
  35928. for (var i = 1; i < sortedFree.length; i++) {
  35929. // 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
  35930. if (firstFreeSlotOffset >= occupiedZoneSize) {
  35931. break;
  35932. }
  35933. var curFree = sortedFree[i];
  35934. var curOffset = curFree.offset;
  35935. // Compute the distance between this offset and the previous
  35936. var distance = curOffset - prevOffset;
  35937. // If the distance is the stride size, they are adjacent, it good, move to the next
  35938. if (distance === s) {
  35939. // Free zone is one element bigger
  35940. ++freeZoneSize;
  35941. // as we're about to iterate to the next, the cur becomes the previous...
  35942. prevOffset = curOffset;
  35943. continue;
  35944. }
  35945. // Distance is bigger, which means there's x element between the previous free and this one
  35946. var usedRange = (distance / s) - 1;
  35947. // Two cases the free zone is smaller than the data to move or bigger
  35948. // Copy what can fit in the free zone
  35949. var curMoveOffset = curOffset - s;
  35950. var copyCount = Math.min(freeZoneSize, usedRange);
  35951. for (var j = 0; j < copyCount; j++) {
  35952. var freeI = firstFreeSlotOffset / s;
  35953. var curI = curMoveOffset / s;
  35954. var moveEl = sortedAll[curI];
  35955. this._moveElement(moveEl, firstFreeSlotOffset);
  35956. var replacedEl = sortedAll[freeI];
  35957. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  35958. replacedEl.offset = curMoveOffset;
  35959. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  35960. sortedAll[freeI] = moveEl;
  35961. sortedAll[curI] = replacedEl;
  35962. curMoveOffset -= s;
  35963. firstFreeSlotOffset += s;
  35964. }
  35965. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  35966. if (freeZoneSize <= usedRange) {
  35967. firstFreeSlotOffset = curMoveOffset + s;
  35968. freeZoneSize = 1 + copyCount;
  35969. }
  35970. else {
  35971. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  35972. }
  35973. // as we're about to iterate to the next, the cur becomes the previous...
  35974. prevOffset = curOffset;
  35975. }
  35976. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  35977. this._lastUsed = firstFreeSlotOffset - s;
  35978. this._firstFree = firstFreeSlotOffset;
  35979. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  35980. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  35981. this._allEntries = sortedAll;
  35982. return elementsBuffer;
  35983. };
  35984. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  35985. for (var i = 0; i < this._stride; i++) {
  35986. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  35987. }
  35988. element.offset = destOffset;
  35989. };
  35990. DynamicFloatArray.prototype._growBuffer = function () {
  35991. // Allocate the new buffer with 50% more entries, copy the content of the current one
  35992. var newElCount = Math.floor(this.totalElementCount * 1.5);
  35993. var newBuffer = new Float32Array(newElCount * this._stride);
  35994. newBuffer.set(this.buffer);
  35995. var curCount = this.totalElementCount;
  35996. var addedCount = newElCount - this.totalElementCount;
  35997. for (var i = 0; i < addedCount; i++) {
  35998. var element = new DynamicFloatArrayElementInfo();
  35999. element.offset = (curCount + i) * this.stride;
  36000. this._allEntries.push(element);
  36001. this._freeEntries[addedCount - i - 1] = element;
  36002. }
  36003. this._firstFree = curCount * this.stride;
  36004. this.buffer = newBuffer;
  36005. };
  36006. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  36007. /**
  36008. * Get the total count of entries that can fit in the current buffer
  36009. * @returns the elements count
  36010. */
  36011. get: function () {
  36012. return this._allEntries.length;
  36013. },
  36014. enumerable: true,
  36015. configurable: true
  36016. });
  36017. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  36018. /**
  36019. * Get the count of free entries that can still be allocated without resizing the buffer
  36020. * @returns the free elements count
  36021. */
  36022. get: function () {
  36023. return this._freeEntries.length;
  36024. },
  36025. enumerable: true,
  36026. configurable: true
  36027. });
  36028. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  36029. /**
  36030. * Get the count of allocated elements
  36031. * @returns the allocated elements count
  36032. */
  36033. get: function () {
  36034. return this._allEntries.length - this._freeEntries.length;
  36035. },
  36036. enumerable: true,
  36037. configurable: true
  36038. });
  36039. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  36040. /**
  36041. * Return the size of one element in float
  36042. * @returns the size in float
  36043. */
  36044. get: function () {
  36045. return this._stride;
  36046. },
  36047. enumerable: true,
  36048. configurable: true
  36049. });
  36050. DynamicFloatArray.prototype.sort = function () {
  36051. var _this = this;
  36052. if (!this.compareValueOffset) {
  36053. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  36054. }
  36055. var count = this.usedElementCount;
  36056. // Do we have to (re)create the sort table?
  36057. if (!this._sortTable || this._sortTable.length < count) {
  36058. // 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...
  36059. var newCount = Math.min(this.totalElementCount, count * 2);
  36060. this._sortTable = new Array(newCount);
  36061. }
  36062. if (!this._sortTable || this._sortTable.length !== count) {
  36063. this._sortedTable = new Array(count);
  36064. }
  36065. // Because, you know...
  36066. this.pack();
  36067. //let stride = this.stride;
  36068. //for (let i = 0; i < count; i++) {
  36069. // let si = this._sortTable[i];
  36070. // if (!si) {
  36071. // si = new SortInfo();
  36072. // this._sortTable[i] = si;
  36073. // }
  36074. // si.entry = this._allEntries[i];
  36075. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  36076. // si.swapedOffset = null;
  36077. // this._sortedTable[i] = si;
  36078. //}
  36079. var curOffset = 0;
  36080. var stride = this.stride;
  36081. for (var i = 0; i < count; i++, curOffset += stride) {
  36082. var si = this._sortTable[i];
  36083. if (!si) {
  36084. si = new SortInfo();
  36085. this._sortTable[i] = si;
  36086. }
  36087. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  36088. si.offset = curOffset;
  36089. si.swapedOffset = null;
  36090. this._sortedTable[i] = si;
  36091. }
  36092. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  36093. if (this.sortingAscending) {
  36094. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  36095. }
  36096. else {
  36097. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  36098. }
  36099. var swapElements = function (src, dst) {
  36100. for (var i = 0; i < stride; i++) {
  36101. var tps = _this.buffer[dst + i];
  36102. _this.buffer[dst + i] = _this.buffer[src + i];
  36103. _this.buffer[src + i] = tps;
  36104. }
  36105. };
  36106. // 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:
  36107. // 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),
  36108. // and I still want something with a good algorithm complexity.
  36109. // 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,
  36110. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  36111. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  36112. // 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
  36113. // until we find a SortInfo object without a swapedOffset which means we got the right location
  36114. // 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
  36115. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  36116. for (var i = 0; i < count; i++) {
  36117. // Get the element to move
  36118. var sourceSI = this._sortedTable[i];
  36119. var destSI = this._sortTable[i];
  36120. var sourceOff = sourceSI.offset;
  36121. // If the source changed location, find the new one
  36122. if (sourceSI.swapedOffset) {
  36123. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  36124. var curSI = sourceSI;
  36125. while (curSI.swapedOffset) {
  36126. curSI = this._sortTable[curSI.swapedOffset / stride];
  36127. }
  36128. // Finally get the right location
  36129. sourceOff = curSI.offset;
  36130. }
  36131. // Tag the element being replaced with its new location
  36132. destSI.swapedOffset = sourceOff;
  36133. // Swap elements (only if needed)
  36134. if (sourceOff !== destSI.offset) {
  36135. swapElements(sourceOff, destSI.offset);
  36136. }
  36137. // Update the offset in the corresponding DFAE
  36138. //sourceSI.entry.offset = destSI.entry.offset;
  36139. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  36140. }
  36141. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  36142. return true;
  36143. };
  36144. return DynamicFloatArray;
  36145. }());
  36146. BABYLON.DynamicFloatArray = DynamicFloatArray;
  36147. var SortInfo = (function () {
  36148. function SortInfo() {
  36149. this.compareData = this.offset = this.swapedOffset = null;
  36150. }
  36151. return SortInfo;
  36152. }());
  36153. })(BABYLON || (BABYLON = {}));
  36154. var BABYLON;
  36155. (function (BABYLON) {
  36156. /**
  36157. * This class given information about a given character.
  36158. */
  36159. var CharInfo = (function () {
  36160. function CharInfo() {
  36161. }
  36162. return CharInfo;
  36163. }());
  36164. BABYLON.CharInfo = CharInfo;
  36165. var FontTexture = (function (_super) {
  36166. __extends(FontTexture, _super);
  36167. /**
  36168. * Create a new instance of the FontTexture class
  36169. * @param name the name of the texture
  36170. * @param font the font to use, use the W3C CSS notation
  36171. * @param scene the scene that owns the texture
  36172. * @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
  36173. * @param samplingMode the texture sampling mode
  36174. * @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.
  36175. */
  36176. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample) {
  36177. if (maxCharCount === void 0) { maxCharCount = 200; }
  36178. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36179. if (superSample === void 0) { superSample = false; }
  36180. _super.call(this, null, scene, true, false, samplingMode);
  36181. this._charInfos = {};
  36182. this._curCharCount = 0;
  36183. this._lastUpdateCharCount = -1;
  36184. this._usedCounter = 1;
  36185. this.name = name;
  36186. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36187. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36188. this._superSample = false;
  36189. if (superSample) {
  36190. var sfont = this.getSuperSampleFont(font);
  36191. if (sfont) {
  36192. this._superSample = true;
  36193. font = sfont;
  36194. }
  36195. }
  36196. // First canvas creation to determine the size of the texture to create
  36197. this._canvas = document.createElement("canvas");
  36198. this._context = this._canvas.getContext("2d");
  36199. this._context.font = font;
  36200. this._context.fillStyle = "white";
  36201. var res = this.getFontHeight(font);
  36202. this._lineHeightSuper = res.height;
  36203. this._lineHeight = this._superSample ? (this._lineHeightSuper / 2) : this._lineHeightSuper;
  36204. this._offset = res.offset - 1;
  36205. var maxCharWidth = this._context.measureText("W").width;
  36206. this._spaceWidthSuper = this._context.measureText(" ").width;
  36207. this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
  36208. // This is an approximate size, but should always be able to fit at least the maxCharCount
  36209. var totalEstSurface = this._lineHeightSuper * maxCharWidth * maxCharCount;
  36210. var edge = Math.sqrt(totalEstSurface);
  36211. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  36212. // Create the texture that will store the font characters
  36213. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  36214. var textureSize = this.getSize();
  36215. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  36216. this._canvas = document.createElement("canvas");
  36217. this._canvas.width = textureSize.width;
  36218. this._canvas.height = textureSize.height;
  36219. this._context = this._canvas.getContext("2d");
  36220. this._context.textBaseline = "top";
  36221. this._context.font = font;
  36222. this._context.fillStyle = "white";
  36223. this._context.imageSmoothingEnabled = false;
  36224. this._currentFreePosition = BABYLON.Vector2.Zero();
  36225. // Add the basic ASCII based characters
  36226. for (var i = 0x20; i < 0x7F; i++) {
  36227. var c = String.fromCharCode(i);
  36228. this.getChar(c);
  36229. }
  36230. this.update();
  36231. }
  36232. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  36233. get: function () {
  36234. return this._superSample;
  36235. },
  36236. enumerable: true,
  36237. configurable: true
  36238. });
  36239. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  36240. get: function () {
  36241. return this._spaceWidth;
  36242. },
  36243. enumerable: true,
  36244. configurable: true
  36245. });
  36246. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  36247. get: function () {
  36248. return this._lineHeight;
  36249. },
  36250. enumerable: true,
  36251. configurable: true
  36252. });
  36253. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample) {
  36254. if (supersample === void 0) { supersample = false; }
  36255. var s = scene;
  36256. if (!s.__fontTextureCache__) {
  36257. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  36258. }
  36259. var dic = s.__fontTextureCache__;
  36260. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  36261. var ft = dic.get(lfn);
  36262. if (ft) {
  36263. ++ft._usedCounter;
  36264. return ft;
  36265. }
  36266. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample);
  36267. dic.add(lfn, ft);
  36268. return ft;
  36269. };
  36270. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample) {
  36271. if (supersample === void 0) { supersample = false; }
  36272. var s = scene;
  36273. var dic = s.__fontTextureCache__;
  36274. if (!dic) {
  36275. return;
  36276. }
  36277. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  36278. var font = dic.get(lfn);
  36279. if (--font._usedCounter === 0) {
  36280. dic.remove(lfn);
  36281. font.dispose();
  36282. }
  36283. };
  36284. /**
  36285. * Make sure the given char is present in the font map.
  36286. * @param char the character to get or add
  36287. * @return the CharInfo instance corresponding to the given character
  36288. */
  36289. FontTexture.prototype.getChar = function (char) {
  36290. if (char.length !== 1) {
  36291. return null;
  36292. }
  36293. var info = this._charInfos[char];
  36294. if (info) {
  36295. return info;
  36296. }
  36297. info = new CharInfo();
  36298. var measure = this._context.measureText(char);
  36299. var textureSize = this.getSize();
  36300. // we reached the end of the current line?
  36301. var width = Math.round(measure.width);
  36302. var xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  36303. var yMargin = xMargin;
  36304. if (this._currentFreePosition.x + width + xMargin > textureSize.width) {
  36305. this._currentFreePosition.x = 0;
  36306. this._currentFreePosition.y += this._lineHeightSuper + yMargin;
  36307. // No more room?
  36308. if (this._currentFreePosition.y > textureSize.height) {
  36309. return this.getChar("!");
  36310. }
  36311. }
  36312. // Draw the character in the texture
  36313. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  36314. // Fill the CharInfo object
  36315. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  36316. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  36317. info.charWidth = this._superSample ? (width / 2) : width;
  36318. // Add the info structure
  36319. this._charInfos[char] = info;
  36320. this._curCharCount++;
  36321. // Set the next position
  36322. this._currentFreePosition.x += width + xMargin;
  36323. return info;
  36324. };
  36325. FontTexture.prototype.measureText = function (text, tabulationSize) {
  36326. if (tabulationSize === void 0) { tabulationSize = 4; }
  36327. var maxWidth = 0;
  36328. var curWidth = 0;
  36329. var lineCount = 1;
  36330. var charxpos = 0;
  36331. // Parse each char of the string
  36332. for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
  36333. var char = text_1[_i];
  36334. // Next line feed?
  36335. if (char === "\n") {
  36336. maxWidth = Math.max(maxWidth, curWidth);
  36337. charxpos = 0;
  36338. curWidth = 0;
  36339. ++lineCount;
  36340. continue;
  36341. }
  36342. // Tabulation ?
  36343. if (char === "\t") {
  36344. var nextPos = charxpos + tabulationSize;
  36345. nextPos = nextPos - (nextPos % tabulationSize);
  36346. curWidth += (nextPos - charxpos) * this.spaceWidth;
  36347. charxpos = nextPos;
  36348. continue;
  36349. }
  36350. if (char < " ") {
  36351. continue;
  36352. }
  36353. curWidth += this.getChar(char).charWidth;
  36354. ++charxpos;
  36355. }
  36356. maxWidth = Math.max(maxWidth, curWidth);
  36357. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  36358. };
  36359. FontTexture.prototype.getSuperSampleFont = function (font) {
  36360. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  36361. 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*$/;
  36362. var res = font.toLocaleLowerCase().match(regex);
  36363. if (res == null) {
  36364. return null;
  36365. }
  36366. var size = parseInt(res[4]);
  36367. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  36368. var newFont = "";
  36369. for (var j = 1; j < res.length; j++) {
  36370. if (res[j] != null) {
  36371. newFont += res[j] + " ";
  36372. }
  36373. }
  36374. return newFont;
  36375. };
  36376. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  36377. FontTexture.prototype.getFontHeight = function (font) {
  36378. var fontDraw = document.createElement("canvas");
  36379. var ctx = fontDraw.getContext('2d');
  36380. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  36381. ctx.textBaseline = 'top';
  36382. ctx.fillStyle = 'white';
  36383. ctx.font = font;
  36384. ctx.fillText('jH|', 0, 0);
  36385. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  36386. var start = -1;
  36387. var end = -1;
  36388. for (var row = 0; row < fontDraw.height; row++) {
  36389. for (var column = 0; column < fontDraw.width; column++) {
  36390. var index = (row * fontDraw.width + column) * 4;
  36391. if (pixels[index] === 0) {
  36392. if (column === fontDraw.width - 1 && start !== -1) {
  36393. end = row;
  36394. row = fontDraw.height;
  36395. break;
  36396. }
  36397. continue;
  36398. }
  36399. else {
  36400. if (start === -1) {
  36401. start = row;
  36402. }
  36403. break;
  36404. }
  36405. }
  36406. }
  36407. return { height: (end - start) + 1, offset: start - 1 };
  36408. };
  36409. Object.defineProperty(FontTexture.prototype, "canRescale", {
  36410. get: function () {
  36411. return false;
  36412. },
  36413. enumerable: true,
  36414. configurable: true
  36415. });
  36416. FontTexture.prototype.getContext = function () {
  36417. return this._context;
  36418. };
  36419. /**
  36420. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  36421. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  36422. */
  36423. FontTexture.prototype.update = function () {
  36424. // Update only if there's new char added since the previous update
  36425. if (this._lastUpdateCharCount < this._curCharCount) {
  36426. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  36427. this._lastUpdateCharCount = this._curCharCount;
  36428. }
  36429. };
  36430. // cloning should be prohibited, there's no point to duplicate this texture at all
  36431. FontTexture.prototype.clone = function () {
  36432. return null;
  36433. };
  36434. return FontTexture;
  36435. }(BABYLON.Texture));
  36436. BABYLON.FontTexture = FontTexture;
  36437. })(BABYLON || (BABYLON = {}));
  36438. var BABYLON;
  36439. (function (BABYLON) {
  36440. var MapTexture = (function (_super) {
  36441. __extends(MapTexture, _super);
  36442. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  36443. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36444. if (useMipMap === void 0) { useMipMap = false; }
  36445. _super.call(this, null, scene, !useMipMap, false, samplingMode);
  36446. this.name = name;
  36447. this._size = size;
  36448. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36449. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36450. // Create the rectPackMap that will allocate portion of the texture
  36451. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  36452. // Create the texture that will store the content
  36453. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  36454. }
  36455. /**
  36456. * Allocate a rectangle of a given size in the texture map
  36457. * @param size the size of the rectangle to allocation
  36458. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  36459. */
  36460. MapTexture.prototype.allocateRect = function (size) {
  36461. return this._rectPackingMap.addRect(size);
  36462. };
  36463. /**
  36464. * Free a given rectangle from the texture map
  36465. * @param rectInfo the instance corresponding to the rect to free.
  36466. */
  36467. MapTexture.prototype.freeRect = function (rectInfo) {
  36468. if (rectInfo) {
  36469. rectInfo.freeContent();
  36470. }
  36471. };
  36472. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  36473. /**
  36474. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  36475. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  36476. * @returns {}
  36477. */
  36478. get: function () {
  36479. return this._rectPackingMap.freeSpace;
  36480. },
  36481. enumerable: true,
  36482. configurable: true
  36483. });
  36484. /**
  36485. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  36486. * 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.
  36487. * Don't forget to call unbindTexture when you're done rendering
  36488. * @param rect the zone to render to
  36489. * @param clear true to clear the portion's color/depth data
  36490. */
  36491. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  36492. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  36493. };
  36494. /**
  36495. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  36496. * 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.
  36497. * Don't forget to call unbindTexture when you're done rendering
  36498. * @param pos the position into the texture
  36499. * @param size the portion to fit the clip space to
  36500. * @param clear true to clear the portion's color/depth data
  36501. */
  36502. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  36503. var engine = this.getScene().getEngine();
  36504. engine.bindFramebuffer(this._texture);
  36505. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  36506. if (clear) {
  36507. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  36508. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  36509. }
  36510. };
  36511. /**
  36512. * Unbind the texture map from the rendering engine.
  36513. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  36514. * @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.
  36515. */
  36516. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  36517. // Dump ?
  36518. if (dumpForDebug) {
  36519. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  36520. }
  36521. var engine = this.getScene().getEngine();
  36522. if (this._replacedViewport) {
  36523. engine.setViewport(this._replacedViewport);
  36524. this._replacedViewport = null;
  36525. }
  36526. engine.unBindFramebuffer(this._texture);
  36527. };
  36528. Object.defineProperty(MapTexture.prototype, "canRescale", {
  36529. get: function () {
  36530. return false;
  36531. },
  36532. enumerable: true,
  36533. configurable: true
  36534. });
  36535. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  36536. // Anyway, there's not much point to use this method for this kind of texture I guess
  36537. MapTexture.prototype.clone = function () {
  36538. return null;
  36539. };
  36540. return MapTexture;
  36541. }(BABYLON.Texture));
  36542. BABYLON.MapTexture = MapTexture;
  36543. })(BABYLON || (BABYLON = {}));
  36544. var BABYLON;
  36545. (function (BABYLON) {
  36546. /**
  36547. * Stores 2D Bounding Information.
  36548. * This class handles a circle area and a bounding rectangle one.
  36549. */
  36550. var BoundingInfo2D = (function () {
  36551. function BoundingInfo2D() {
  36552. this.radius = 0;
  36553. this.center = BABYLON.Vector2.Zero();
  36554. this.extent = BABYLON.Vector2.Zero();
  36555. }
  36556. /**
  36557. * Create a BoundingInfo2D object from a given size
  36558. * @param size the size that will be used to set the extend, radius will be computed from it.
  36559. */
  36560. BoundingInfo2D.CreateFromSize = function (size) {
  36561. var r = new BoundingInfo2D();
  36562. BoundingInfo2D.CreateFromSizeToRef(size, r);
  36563. return r;
  36564. };
  36565. /**
  36566. * Create a BoundingInfo2D object from a given radius
  36567. * @param radius the radius to use, the extent will be computed from it.
  36568. */
  36569. BoundingInfo2D.CreateFromRadius = function (radius) {
  36570. var r = new BoundingInfo2D();
  36571. BoundingInfo2D.CreateFromRadiusToRef(radius, r);
  36572. return r;
  36573. };
  36574. /**
  36575. * Create a BoundingInfo2D object from a list of points.
  36576. * The resulted object will be the smallest bounding area that includes all the given points.
  36577. * @param points an array of points to compute the bounding object from.
  36578. */
  36579. BoundingInfo2D.CreateFromPoints = function (points) {
  36580. var r = new BoundingInfo2D();
  36581. BoundingInfo2D.CreateFromPointsToRef(points, r);
  36582. return r;
  36583. };
  36584. /**
  36585. * Update a BoundingInfo2D object using the given Size as input
  36586. * @param size the bounding data will be computed from this size.
  36587. * @param b must be a valid/allocated object, it will contain the result of the operation
  36588. */
  36589. BoundingInfo2D.CreateFromSizeToRef = function (size, b) {
  36590. if (!size) {
  36591. size = BABYLON.Size.Zero();
  36592. }
  36593. b.center.x = +size.width / 2;
  36594. b.center.y = +size.height / 2;
  36595. b.extent.x = b.center.x;
  36596. b.extent.y = b.center.y;
  36597. b.radius = b.extent.length();
  36598. };
  36599. /**
  36600. * Update a BoundingInfo2D object using the given radius as input
  36601. * @param radius the bounding data will be computed from this radius
  36602. * @param b must be a valid/allocated object, it will contain the result of the operation
  36603. */
  36604. BoundingInfo2D.CreateFromRadiusToRef = function (radius, b) {
  36605. b.center.x = b.center.y = 0;
  36606. var r = +radius;
  36607. b.extent.x = r;
  36608. b.extent.y = r;
  36609. b.radius = r;
  36610. };
  36611. /**
  36612. * Update a BoundingInfo2D object using the given points array as input
  36613. * @param points the point array to use to update the bounding data
  36614. * @param b must be a valid/allocated object, it will contain the result of the operation
  36615. */
  36616. BoundingInfo2D.CreateFromPointsToRef = function (points, b) {
  36617. var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
  36618. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  36619. var p = points_1[_i];
  36620. xmin = Math.min(p.x, xmin);
  36621. xmax = Math.max(p.x, xmax);
  36622. ymin = Math.min(p.y, ymin);
  36623. ymax = Math.max(p.y, ymax);
  36624. }
  36625. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b);
  36626. };
  36627. /**
  36628. * Update a BoundingInfo2D object using the given min/max values as input
  36629. * @param xmin the smallest x coordinate
  36630. * @param xmax the biggest x coordinate
  36631. * @param ymin the smallest y coordinate
  36632. * @param ymax the buggest y coordinate
  36633. * @param b must be a valid/allocated object, it will contain the result of the operation
  36634. */
  36635. BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b) {
  36636. var w = xmax - xmin;
  36637. var h = ymax - ymin;
  36638. b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
  36639. b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
  36640. b.radius = b.extent.length();
  36641. };
  36642. /**
  36643. * Duplicate this instance and return a new one
  36644. * @return the duplicated instance
  36645. */
  36646. BoundingInfo2D.prototype.clone = function () {
  36647. var r = new BoundingInfo2D();
  36648. r.center = this.center.clone();
  36649. r.radius = this.radius;
  36650. r.extent = this.extent.clone();
  36651. return r;
  36652. };
  36653. BoundingInfo2D.prototype.clear = function () {
  36654. this.center.copyFromFloats(0, 0);
  36655. this.radius = 0;
  36656. this.extent.copyFromFloats(0, 0);
  36657. };
  36658. BoundingInfo2D.prototype.copyFrom = function (src) {
  36659. this.center.copyFrom(src.center);
  36660. this.radius = src.radius;
  36661. this.extent.copyFrom(src.extent);
  36662. };
  36663. /**
  36664. * return the max extend of the bounding info
  36665. */
  36666. BoundingInfo2D.prototype.max = function () {
  36667. var r = BABYLON.Vector2.Zero();
  36668. this.maxToRef(r);
  36669. return r;
  36670. };
  36671. /**
  36672. * Update a vector2 with the max extend of the bounding info
  36673. * @param result must be a valid/allocated vector2 that will contain the result of the operation
  36674. */
  36675. BoundingInfo2D.prototype.maxToRef = function (result) {
  36676. result.x = this.center.x + this.extent.x;
  36677. result.y = this.center.y + this.extent.y;
  36678. };
  36679. /**
  36680. * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
  36681. * @param matrix the transformation matrix to apply
  36682. * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
  36683. */
  36684. BoundingInfo2D.prototype.transform = function (matrix) {
  36685. var r = new BoundingInfo2D();
  36686. this.transformToRef(matrix, r);
  36687. return r;
  36688. };
  36689. /**
  36690. * Compute the union of this BoundingInfo2D with a given one, returns a new BoundingInfo2D as a result
  36691. * @param other the second BoundingInfo2D to compute the union with this one
  36692. * @return a new instance containing the result of the union
  36693. */
  36694. BoundingInfo2D.prototype.union = function (other) {
  36695. var r = new BoundingInfo2D();
  36696. this.unionToRef(other, r);
  36697. return r;
  36698. };
  36699. /**
  36700. * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
  36701. * 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.
  36702. * @param matrix The matrix to use to compute the transformation
  36703. * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
  36704. */
  36705. BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
  36706. // Construct a bounding box based on the extent values
  36707. var p = BoundingInfo2D._transform;
  36708. p[0].x = this.center.x + this.extent.x;
  36709. p[0].y = this.center.y + this.extent.y;
  36710. p[1].x = this.center.x + this.extent.x;
  36711. p[1].y = this.center.y - this.extent.y;
  36712. p[2].x = this.center.x - this.extent.x;
  36713. p[2].y = this.center.y - this.extent.y;
  36714. p[3].x = this.center.x - this.extent.x;
  36715. p[3].y = this.center.y + this.extent.y;
  36716. // Transform the four points of the bounding box with the matrix
  36717. for (var i = 0; i < 4; i++) {
  36718. BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
  36719. }
  36720. BoundingInfo2D.CreateFromPointsToRef(p, result);
  36721. };
  36722. /**
  36723. * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
  36724. * 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.
  36725. * @param other the second object used to compute the union
  36726. * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
  36727. */
  36728. BoundingInfo2D.prototype.unionToRef = function (other, result) {
  36729. var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
  36730. var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
  36731. var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
  36732. var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
  36733. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
  36734. };
  36735. /**
  36736. * Check if the given point is inside the BoundingInfo.
  36737. * The test is first made on the radius, then inside the rectangle described by the extent
  36738. * @param pickPosition the position to test
  36739. * @return true if the point is inside, false otherwise
  36740. */
  36741. BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
  36742. // is it inside the radius?
  36743. var pickLocal = pickPosition.subtract(this.center);
  36744. if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
  36745. // is it inside the rectangle?
  36746. return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
  36747. }
  36748. return false;
  36749. };
  36750. BoundingInfo2D._transform = new Array(BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero());
  36751. return BoundingInfo2D;
  36752. }());
  36753. BABYLON.BoundingInfo2D = BoundingInfo2D;
  36754. })(BABYLON || (BABYLON = {}));
  36755. var BABYLON;
  36756. (function (BABYLON) {
  36757. /**
  36758. * Base class implementing the ILocable interface.
  36759. * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
  36760. */
  36761. var LockableBase = (function () {
  36762. function LockableBase() {
  36763. }
  36764. LockableBase.prototype.isLocked = function () {
  36765. return this._isLocked;
  36766. };
  36767. LockableBase.prototype.lock = function () {
  36768. if (this._isLocked) {
  36769. return true;
  36770. }
  36771. this.onLock();
  36772. this._isLocked = true;
  36773. return false;
  36774. };
  36775. /**
  36776. * Protected handler that will be called when the instance is about to be locked.
  36777. */
  36778. LockableBase.prototype.onLock = function () {
  36779. };
  36780. return LockableBase;
  36781. }());
  36782. BABYLON.LockableBase = LockableBase;
  36783. var SolidColorBrush2D = (function (_super) {
  36784. __extends(SolidColorBrush2D, _super);
  36785. function SolidColorBrush2D(color, lock) {
  36786. if (lock === void 0) { lock = false; }
  36787. _super.call(this);
  36788. this._color = color;
  36789. if (lock) {
  36790. {
  36791. this.lock();
  36792. }
  36793. }
  36794. }
  36795. /**
  36796. * Return true if the brush is transparent, false if it's totally opaque
  36797. */
  36798. SolidColorBrush2D.prototype.isTransparent = function () {
  36799. return this._color && this._color.a < 1.0;
  36800. };
  36801. Object.defineProperty(SolidColorBrush2D.prototype, "color", {
  36802. /**
  36803. * The color used by this instance to render
  36804. * @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.
  36805. */
  36806. get: function () {
  36807. return this._color;
  36808. },
  36809. set: function (value) {
  36810. if (this.isLocked()) {
  36811. return;
  36812. }
  36813. this._color = value;
  36814. },
  36815. enumerable: true,
  36816. configurable: true
  36817. });
  36818. /**
  36819. * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
  36820. */
  36821. SolidColorBrush2D.prototype.toString = function () {
  36822. return this._color.toHexString();
  36823. };
  36824. SolidColorBrush2D = __decorate([
  36825. BABYLON.className("SolidColorBrush2D")
  36826. ], SolidColorBrush2D);
  36827. return SolidColorBrush2D;
  36828. }(LockableBase));
  36829. BABYLON.SolidColorBrush2D = SolidColorBrush2D;
  36830. var GradientColorBrush2D = (function (_super) {
  36831. __extends(GradientColorBrush2D, _super);
  36832. function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
  36833. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  36834. if (rotation === void 0) { rotation = 0; }
  36835. if (scale === void 0) { scale = 1; }
  36836. if (lock === void 0) { lock = false; }
  36837. _super.call(this);
  36838. this._color1 = color1;
  36839. this._color2 = color2;
  36840. this._translation = translation;
  36841. this._rotation = rotation;
  36842. this._scale = scale;
  36843. if (lock) {
  36844. this.lock();
  36845. }
  36846. }
  36847. /**
  36848. * Return true if the brush is transparent, false if it's totally opaque
  36849. */
  36850. GradientColorBrush2D.prototype.isTransparent = function () {
  36851. return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
  36852. };
  36853. Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
  36854. /**
  36855. * First color, the blend will start from this color
  36856. */
  36857. get: function () {
  36858. return this._color1;
  36859. },
  36860. set: function (value) {
  36861. if (this.isLocked()) {
  36862. return;
  36863. }
  36864. this._color1 = value;
  36865. },
  36866. enumerable: true,
  36867. configurable: true
  36868. });
  36869. Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
  36870. /**
  36871. * Second color, the blend will end to this color
  36872. */
  36873. get: function () {
  36874. return this._color2;
  36875. },
  36876. set: function (value) {
  36877. if (this.isLocked()) {
  36878. return;
  36879. }
  36880. this._color2 = value;
  36881. },
  36882. enumerable: true,
  36883. configurable: true
  36884. });
  36885. Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
  36886. /**
  36887. * Translation vector to apply on the blend
  36888. * Default is [0;0]
  36889. */
  36890. get: function () {
  36891. return this._translation;
  36892. },
  36893. set: function (value) {
  36894. if (this.isLocked()) {
  36895. return;
  36896. }
  36897. this._translation = value;
  36898. },
  36899. enumerable: true,
  36900. configurable: true
  36901. });
  36902. Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
  36903. /**
  36904. * Rotation in radian to apply to the brush
  36905. * Default direction of the brush is vertical, you can change this using this property.
  36906. * Default is 0.
  36907. */
  36908. get: function () {
  36909. return this._rotation;
  36910. },
  36911. set: function (value) {
  36912. if (this.isLocked()) {
  36913. return;
  36914. }
  36915. this._rotation = value;
  36916. },
  36917. enumerable: true,
  36918. configurable: true
  36919. });
  36920. Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
  36921. /**
  36922. * Scale factor to apply to the gradient.
  36923. * Default is 1: no scale.
  36924. */
  36925. get: function () {
  36926. return this._scale;
  36927. },
  36928. set: function (value) {
  36929. if (this.isLocked()) {
  36930. return;
  36931. }
  36932. this._scale = value;
  36933. },
  36934. enumerable: true,
  36935. configurable: true
  36936. });
  36937. /**
  36938. * Return a string describing the brush
  36939. */
  36940. GradientColorBrush2D.prototype.toString = function () {
  36941. return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
  36942. };
  36943. /**
  36944. * Build a unique key string for the given parameters
  36945. */
  36946. GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
  36947. return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
  36948. };
  36949. GradientColorBrush2D = __decorate([
  36950. BABYLON.className("GradientColorBrush2D")
  36951. ], GradientColorBrush2D);
  36952. return GradientColorBrush2D;
  36953. }(LockableBase));
  36954. BABYLON.GradientColorBrush2D = GradientColorBrush2D;
  36955. })(BABYLON || (BABYLON = {}));
  36956. var BABYLON;
  36957. (function (BABYLON) {
  36958. var Prim2DClassInfo = (function () {
  36959. function Prim2DClassInfo() {
  36960. }
  36961. return Prim2DClassInfo;
  36962. }());
  36963. BABYLON.Prim2DClassInfo = Prim2DClassInfo;
  36964. var Prim2DPropInfo = (function () {
  36965. function Prim2DPropInfo() {
  36966. }
  36967. Prim2DPropInfo.PROPKIND_MODEL = 1;
  36968. Prim2DPropInfo.PROPKIND_INSTANCE = 2;
  36969. Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
  36970. return Prim2DPropInfo;
  36971. }());
  36972. BABYLON.Prim2DPropInfo = Prim2DPropInfo;
  36973. /**
  36974. * Custom type of the propertyChanged observable
  36975. */
  36976. var PropertyChangedInfo = (function () {
  36977. function PropertyChangedInfo() {
  36978. }
  36979. return PropertyChangedInfo;
  36980. }());
  36981. BABYLON.PropertyChangedInfo = PropertyChangedInfo;
  36982. var ClassTreeInfo = (function () {
  36983. function ClassTreeInfo(baseClass, type, classContentFactory) {
  36984. this._baseClass = baseClass;
  36985. this._type = type;
  36986. this._subClasses = new Array();
  36987. this._levelContent = new BABYLON.StringDictionary();
  36988. this._classContentFactory = classContentFactory;
  36989. }
  36990. Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
  36991. get: function () {
  36992. if (!this._classContent) {
  36993. this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
  36994. }
  36995. return this._classContent;
  36996. },
  36997. enumerable: true,
  36998. configurable: true
  36999. });
  37000. Object.defineProperty(ClassTreeInfo.prototype, "type", {
  37001. get: function () {
  37002. return this._type;
  37003. },
  37004. enumerable: true,
  37005. configurable: true
  37006. });
  37007. Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
  37008. get: function () {
  37009. return this._levelContent;
  37010. },
  37011. enumerable: true,
  37012. configurable: true
  37013. });
  37014. Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
  37015. get: function () {
  37016. if (!this._fullContent) {
  37017. var dic_1 = new BABYLON.StringDictionary();
  37018. var curLevel = this;
  37019. while (curLevel) {
  37020. curLevel.levelContent.forEach(function (k, v) { return dic_1.add(k, v); });
  37021. curLevel = curLevel._baseClass;
  37022. }
  37023. this._fullContent = dic_1;
  37024. }
  37025. return this._fullContent;
  37026. },
  37027. enumerable: true,
  37028. configurable: true
  37029. });
  37030. ClassTreeInfo.prototype.getLevelOf = function (type) {
  37031. // Are we already there?
  37032. if (type === this._type) {
  37033. return this;
  37034. }
  37035. var baseProto = Object.getPrototypeOf(type);
  37036. var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
  37037. if (!curProtoContent) {
  37038. this.getLevelOf(baseProto);
  37039. }
  37040. return this.getOrAddType(baseProto, type);
  37041. };
  37042. ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
  37043. // Are we at the level corresponding to the baseType?
  37044. // If so, get or add the level we're looking for
  37045. if (baseType === this._type) {
  37046. for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
  37047. var subType = _a[_i];
  37048. if (subType.type === type) {
  37049. return subType.node;
  37050. }
  37051. }
  37052. var node = new ClassTreeInfo(this, type, this._classContentFactory);
  37053. var info = { type: type, node: node };
  37054. this._subClasses.push(info);
  37055. return info.node;
  37056. }
  37057. // Recurse down to keep looking for the node corresponding to the baseTypeName
  37058. for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
  37059. var subType = _c[_b];
  37060. var info = subType.node.getOrAddType(baseType, type);
  37061. if (info) {
  37062. return info;
  37063. }
  37064. }
  37065. return null;
  37066. };
  37067. ClassTreeInfo.get = function (type) {
  37068. var dic = type["__classTreeInfo"];
  37069. if (!dic) {
  37070. return null;
  37071. }
  37072. return dic.getLevelOf(type);
  37073. };
  37074. ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
  37075. var dic = type["__classTreeInfo"];
  37076. if (!dic) {
  37077. dic = new ClassTreeInfo(null, type, classContentFactory);
  37078. type["__classTreeInfo"] = dic;
  37079. }
  37080. return dic;
  37081. };
  37082. return ClassTreeInfo;
  37083. }());
  37084. BABYLON.ClassTreeInfo = ClassTreeInfo;
  37085. var SmartPropertyPrim = (function () {
  37086. function SmartPropertyPrim() {
  37087. this._flags = 0;
  37088. this._modelKey = null;
  37089. this._instanceDirtyFlags = 0;
  37090. this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
  37091. this.animations = new Array();
  37092. }
  37093. Object.defineProperty(SmartPropertyPrim.prototype, "isDisposed", {
  37094. /**
  37095. * Check if the object is disposed or not.
  37096. * @returns true if the object is dispose, false otherwise.
  37097. */
  37098. get: function () {
  37099. return this._isFlagSet(SmartPropertyPrim.flagIsDisposed);
  37100. },
  37101. enumerable: true,
  37102. configurable: true
  37103. });
  37104. /**
  37105. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  37106. * @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.
  37107. */
  37108. SmartPropertyPrim.prototype.dispose = function () {
  37109. if (this.isDisposed) {
  37110. return false;
  37111. }
  37112. // Don't set to null, it may upset somebody...
  37113. this.animations.splice(0);
  37114. this._setFlags(SmartPropertyPrim.flagIsDisposed);
  37115. return true;
  37116. };
  37117. /**
  37118. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  37119. * Look at Sprite2D for more information
  37120. */
  37121. SmartPropertyPrim.prototype.getAnimatables = function () {
  37122. return new Array();
  37123. };
  37124. Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
  37125. /**
  37126. * Property giving the Model Key associated to the property.
  37127. * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
  37128. * @returns the model key string.
  37129. */
  37130. get: function () {
  37131. var _this = this;
  37132. // No need to compute it?
  37133. if (!this._isFlagSet(SmartPropertyPrim.flagModelDirty) && this._modelKey) {
  37134. return this._modelKey;
  37135. }
  37136. var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
  37137. var propDic = this.propDic;
  37138. propDic.forEach(function (k, v) {
  37139. if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  37140. var propVal = _this[v.name];
  37141. // 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
  37142. if (propVal && propVal.constructor === Array) {
  37143. var firstVal = propVal[0];
  37144. if (!firstVal) {
  37145. propVal = 0;
  37146. }
  37147. else {
  37148. propVal = BABYLON.Tools.hashCodeFromStream(BABYLON.Tools.arrayOrStringFeeder(propVal));
  37149. }
  37150. }
  37151. modelKey += v.name + ":" + ((propVal != null) ? ((v.typeLevelCompare) ? BABYLON.Tools.getClassName(propVal) : propVal.toString()) : "[null]") + ";";
  37152. }
  37153. });
  37154. this._clearFlags(SmartPropertyPrim.flagModelDirty);
  37155. this._modelKey = modelKey;
  37156. return modelKey;
  37157. },
  37158. enumerable: true,
  37159. configurable: true
  37160. });
  37161. Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
  37162. /**
  37163. * States if the Primitive is dirty and should be rendered again next time.
  37164. * @returns true is dirty, false otherwise
  37165. */
  37166. get: function () {
  37167. return (this._instanceDirtyFlags !== 0) || this._areSomeFlagsSet(SmartPropertyPrim.flagModelDirty | SmartPropertyPrim.flagPositioningDirty | SmartPropertyPrim.flagLayoutDirty);
  37168. },
  37169. enumerable: true,
  37170. configurable: true
  37171. });
  37172. Object.defineProperty(SmartPropertyPrim.prototype, "propDic", {
  37173. /**
  37174. * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
  37175. * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
  37176. */
  37177. get: function () {
  37178. if (!this._propInfo) {
  37179. var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
  37180. if (!cti) {
  37181. throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
  37182. }
  37183. this._propInfo = cti.fullContent;
  37184. }
  37185. return this._propInfo;
  37186. },
  37187. enumerable: true,
  37188. configurable: true
  37189. });
  37190. SmartPropertyPrim._createPropInfo = function (target, propName, propId, dirtyBoundingInfo, dirtyParentBoundingBox, typeLevelCompare, kind) {
  37191. var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
  37192. var node = dic.getLevelOf(target);
  37193. var propInfo = node.levelContent.get(propId.toString());
  37194. if (propInfo) {
  37195. throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
  37196. }
  37197. // Create, setup and add the PropInfo object to our prop dictionary
  37198. propInfo = new Prim2DPropInfo();
  37199. propInfo.id = propId;
  37200. propInfo.flagId = Math.pow(2, propId);
  37201. propInfo.kind = kind;
  37202. propInfo.name = propName;
  37203. propInfo.dirtyBoundingInfo = dirtyBoundingInfo;
  37204. propInfo.dirtyParentBoundingInfo = dirtyParentBoundingBox;
  37205. propInfo.typeLevelCompare = typeLevelCompare;
  37206. node.levelContent.add(propName, propInfo);
  37207. return propInfo;
  37208. };
  37209. SmartPropertyPrim._checkUnchanged = function (curValue, newValue) {
  37210. // Nothing to nothing: nothing to do!
  37211. if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
  37212. return true;
  37213. }
  37214. // Check value unchanged
  37215. if ((curValue != null) && (newValue != null)) {
  37216. if (typeof (curValue.equals) == "function") {
  37217. if (curValue.equals(newValue)) {
  37218. return true;
  37219. }
  37220. }
  37221. else {
  37222. if (curValue === newValue) {
  37223. return true;
  37224. }
  37225. }
  37226. }
  37227. return false;
  37228. };
  37229. SmartPropertyPrim.prototype.markAsDirty = function (propertyName) {
  37230. if (this.isDisposed) {
  37231. return;
  37232. }
  37233. var i = propertyName.indexOf(".");
  37234. if (i !== -1) {
  37235. propertyName = propertyName.substr(0, i);
  37236. }
  37237. var propInfo = this.propDic.get(propertyName);
  37238. if (!propInfo) {
  37239. return;
  37240. }
  37241. var newValue = this[propertyName];
  37242. this._handlePropChanged(undefined, newValue, propertyName, propInfo, propInfo.typeLevelCompare);
  37243. };
  37244. SmartPropertyPrim.prototype._boundingBoxDirty = function () {
  37245. this._setFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  37246. // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
  37247. if (this instanceof BABYLON.Prim2DBase) {
  37248. var curprim = this;
  37249. while (curprim) {
  37250. curprim._setFlags(SmartPropertyPrim.flagBoundingInfoDirty);
  37251. if (curprim.isSizeAuto) {
  37252. curprim.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  37253. curprim._setFlags(SmartPropertyPrim.flagPositioningDirty);
  37254. }
  37255. if (curprim instanceof BABYLON.Group2D) {
  37256. if (curprim.isRenderableGroup) {
  37257. break;
  37258. }
  37259. }
  37260. curprim = curprim.parent;
  37261. }
  37262. }
  37263. };
  37264. SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  37265. // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
  37266. if (propInfo.dirtyBoundingInfo) {
  37267. this._boundingBoxDirty();
  37268. }
  37269. else if (propInfo.dirtyParentBoundingInfo) {
  37270. var p = this._parent;
  37271. if (p != null) {
  37272. p._boundingBoxDirty();
  37273. }
  37274. }
  37275. // Trigger property changed
  37276. var info = SmartPropertyPrim.propChangedInfo;
  37277. info.oldValue = curValue;
  37278. info.newValue = newValue;
  37279. info.propertyName = propName;
  37280. var propMask = propInfo.flagId;
  37281. this.propertyChanged.notifyObservers(info, propMask);
  37282. // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
  37283. if (this instanceof BABYLON.Group2D) {
  37284. this.handleGroupChanged(propInfo);
  37285. }
  37286. // Check for parent layout dirty
  37287. if (this instanceof BABYLON.Prim2DBase) {
  37288. var p = this._parent;
  37289. if (p != null && p.layoutEngine && (p.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
  37290. p._setLayoutDirty();
  37291. }
  37292. }
  37293. // For type level compare, if there's a change of type it's a change of model, otherwise we issue an instance change
  37294. var instanceDirty = false;
  37295. if (typeLevelCompare && curValue != null && newValue != null) {
  37296. var cvProto = curValue.__proto__;
  37297. var nvProto = newValue.__proto__;
  37298. instanceDirty = (cvProto === nvProto);
  37299. }
  37300. // Set the dirty flags
  37301. if (!instanceDirty && (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL)) {
  37302. this.onPrimitivePropertyDirty(SmartPropertyPrim.flagModelDirty);
  37303. }
  37304. else if (instanceDirty || (propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
  37305. this.onPrimitivePropertyDirty(propMask);
  37306. }
  37307. };
  37308. SmartPropertyPrim.prototype.onPrimitivePropertyDirty = function (propFlagId) {
  37309. if (!this.isDirty) {
  37310. this.onPrimBecomesDirty();
  37311. }
  37312. this._instanceDirtyFlags |= propFlagId;
  37313. };
  37314. SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
  37315. };
  37316. /**
  37317. * Check if a given set of properties are dirty or not.
  37318. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  37319. * @return true if at least one property is dirty, false if none of them are.
  37320. */
  37321. SmartPropertyPrim.prototype.checkPropertiesDirty = function (flags) {
  37322. return (this._instanceDirtyFlags & flags) !== 0;
  37323. };
  37324. /**
  37325. * Clear a given set of properties.
  37326. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  37327. * @return the new set of property still marked as dirty
  37328. */
  37329. SmartPropertyPrim.prototype.clearPropertiesDirty = function (flags) {
  37330. this._instanceDirtyFlags &= ~flags;
  37331. return this._instanceDirtyFlags;
  37332. };
  37333. SmartPropertyPrim.prototype._resetPropertiesDirty = function () {
  37334. this._instanceDirtyFlags = 0;
  37335. };
  37336. Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
  37337. /**
  37338. * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
  37339. */
  37340. get: function () {
  37341. if (this._isFlagSet(SmartPropertyPrim.flagLevelBoundingInfoDirty)) {
  37342. this.updateLevelBoundingInfo();
  37343. this._clearFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  37344. }
  37345. return this._levelBoundingInfo;
  37346. },
  37347. enumerable: true,
  37348. configurable: true
  37349. });
  37350. /**
  37351. * This method must be overridden by a given Primitive implementation to compute its boundingInfo
  37352. */
  37353. SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
  37354. };
  37355. /**
  37356. * Property method called when the Primitive becomes dirty
  37357. */
  37358. SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
  37359. };
  37360. SmartPropertyPrim._hookProperty = function (propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, kind) {
  37361. return function (target, propName, descriptor) {
  37362. var propInfo = SmartPropertyPrim._createPropInfo(target, propName, propId, dirtyBoundingInfo, dirtyParentBoundingBox, typeLevelCompare, kind);
  37363. if (piStore) {
  37364. piStore(propInfo);
  37365. }
  37366. var getter = descriptor.get, setter = descriptor.set;
  37367. // Overload the property setter implementation to add our own logic
  37368. descriptor.set = function (val) {
  37369. // check for disposed first, do nothing
  37370. if (this.isDisposed) {
  37371. return;
  37372. }
  37373. var curVal = getter.call(this);
  37374. if (SmartPropertyPrim._checkUnchanged(curVal, val)) {
  37375. return;
  37376. }
  37377. // Cast the object we're working one
  37378. var prim = this;
  37379. // Change the value
  37380. setter.call(this, val);
  37381. // Notify change, dirty flags update
  37382. prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
  37383. };
  37384. };
  37385. };
  37386. /**
  37387. * Add an externally attached data from its key.
  37388. * This method call will fail and return false, if such key already exists.
  37389. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  37390. * @param key the unique key that identifies the data
  37391. * @param data the data object to associate to the key for this Engine instance
  37392. * @return true if no such key were already present and the data was added successfully, false otherwise
  37393. */
  37394. SmartPropertyPrim.prototype.addExternalData = function (key, data) {
  37395. if (!this._externalData) {
  37396. this._externalData = new BABYLON.StringDictionary();
  37397. }
  37398. return this._externalData.add(key, data);
  37399. };
  37400. /**
  37401. * Get an externally attached data from its key
  37402. * @param key the unique key that identifies the data
  37403. * @return the associated data, if present (can be null), or undefined if not present
  37404. */
  37405. SmartPropertyPrim.prototype.getExternalData = function (key) {
  37406. if (!this._externalData) {
  37407. return null;
  37408. }
  37409. return this._externalData.get(key);
  37410. };
  37411. /**
  37412. * Get an externally attached data from its key, create it using a factory if it's not already present
  37413. * @param key the unique key that identifies the data
  37414. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  37415. * @return the associated data, can be null if the factory returned null.
  37416. */
  37417. SmartPropertyPrim.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  37418. if (!this._externalData) {
  37419. this._externalData = new BABYLON.StringDictionary();
  37420. }
  37421. return this._externalData.getOrAddWithFactory(key, factory);
  37422. };
  37423. /**
  37424. * Remove an externally attached data from the Engine instance
  37425. * @param key the unique key that identifies the data
  37426. * @return true if the data was successfully removed, false if it doesn't exist
  37427. */
  37428. SmartPropertyPrim.prototype.removeExternalData = function (key) {
  37429. if (!this._externalData) {
  37430. return false;
  37431. }
  37432. return this._externalData.remove(key);
  37433. };
  37434. /**
  37435. * Check if a given flag is set
  37436. * @param flag the flag value
  37437. * @return true if set, false otherwise
  37438. */
  37439. SmartPropertyPrim.prototype._isFlagSet = function (flag) {
  37440. return (this._flags & flag) !== 0;
  37441. };
  37442. /**
  37443. * Check if all given flags are set
  37444. * @param flags the flags ORed
  37445. * @return true if all the flags are set, false otherwise
  37446. */
  37447. SmartPropertyPrim.prototype._areAllFlagsSet = function (flags) {
  37448. return (this._flags & flags) === flags;
  37449. };
  37450. /**
  37451. * Check if at least one flag of the given flags is set
  37452. * @param flags the flags ORed
  37453. * @return true if at least one flag is set, false otherwise
  37454. */
  37455. SmartPropertyPrim.prototype._areSomeFlagsSet = function (flags) {
  37456. return (this._flags & flags) !== 0;
  37457. };
  37458. /**
  37459. * Clear the given flags
  37460. * @param flags the flags to clear
  37461. */
  37462. SmartPropertyPrim.prototype._clearFlags = function (flags) {
  37463. this._flags &= ~flags;
  37464. };
  37465. /**
  37466. * Set the given flags to true state
  37467. * @param flags the flags ORed to set
  37468. * @return the flags state before this call
  37469. */
  37470. SmartPropertyPrim.prototype._setFlags = function (flags) {
  37471. var cur = this._flags;
  37472. this._flags |= flags;
  37473. return cur;
  37474. };
  37475. /**
  37476. * Change the state of the given flags
  37477. * @param flags the flags ORed to change
  37478. * @param state true to set them, false to clear them
  37479. */
  37480. SmartPropertyPrim.prototype._changeFlags = function (flags, state) {
  37481. if (state) {
  37482. this._flags |= flags;
  37483. }
  37484. else {
  37485. this._flags &= ~flags;
  37486. }
  37487. };
  37488. SmartPropertyPrim.propChangedInfo = new PropertyChangedInfo();
  37489. SmartPropertyPrim.flagIsDisposed = 0x0000001; // set if the object is already disposed
  37490. SmartPropertyPrim.flagLevelBoundingInfoDirty = 0x0000002; // set if the primitive's level bounding box (not including children) is dirty
  37491. SmartPropertyPrim.flagModelDirty = 0x0000004; // set if the model must be changed
  37492. SmartPropertyPrim.flagLayoutDirty = 0x0000008; // set if the layout must be computed
  37493. SmartPropertyPrim.flagLevelVisible = 0x0000010; // set if the primitive is set as visible for its level only
  37494. SmartPropertyPrim.flagBoundingInfoDirty = 0x0000020; // set if the primitive's overall bounding box (including children) is dirty
  37495. SmartPropertyPrim.flagIsPickable = 0x0000040; // set if the primitive can be picked during interaction
  37496. SmartPropertyPrim.flagIsVisible = 0x0000080; // set if the primitive is concretely visible (use the levelVisible of parents)
  37497. SmartPropertyPrim.flagVisibilityChanged = 0x0000100; // set if there was a transition between visible/hidden status
  37498. SmartPropertyPrim.flagPositioningDirty = 0x0000200; // set if the primitive positioning must be computed
  37499. SmartPropertyPrim.flagTrackedGroup = 0x0000400; // set if the group2D is tracking a scene node
  37500. SmartPropertyPrim.flagWorldCacheChanged = 0x0000800; // set if the cached bitmap of a world space canvas changed
  37501. SmartPropertyPrim.flagChildrenFlatZOrder = 0x0001000; // set if all the children (direct and indirect) will share the same Z-Order
  37502. SmartPropertyPrim.flagZOrderDirty = 0x0002000; // set if the Z-Order for this prim and its children must be recomputed
  37503. SmartPropertyPrim.flagActualOpacityDirty = 0x0004000; // set if the actualOpactity should be recomputed
  37504. SmartPropertyPrim = __decorate([
  37505. BABYLON.className("SmartPropertyPrim")
  37506. ], SmartPropertyPrim);
  37507. return SmartPropertyPrim;
  37508. }());
  37509. BABYLON.SmartPropertyPrim = SmartPropertyPrim;
  37510. function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  37511. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  37512. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  37513. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  37514. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_MODEL);
  37515. }
  37516. BABYLON.modelLevelProperty = modelLevelProperty;
  37517. function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  37518. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  37519. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  37520. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  37521. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_INSTANCE);
  37522. }
  37523. BABYLON.instanceLevelProperty = instanceLevelProperty;
  37524. function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  37525. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  37526. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  37527. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  37528. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_DYNAMIC);
  37529. }
  37530. BABYLON.dynamicLevelProperty = dynamicLevelProperty;
  37531. })(BABYLON || (BABYLON = {}));
  37532. var BABYLON;
  37533. (function (BABYLON) {
  37534. var PrepareRender2DContext = (function () {
  37535. function PrepareRender2DContext() {
  37536. this.forceRefreshPrimitive = false;
  37537. }
  37538. return PrepareRender2DContext;
  37539. }());
  37540. BABYLON.PrepareRender2DContext = PrepareRender2DContext;
  37541. var Render2DContext = (function () {
  37542. function Render2DContext(renderMode) {
  37543. this._renderMode = renderMode;
  37544. this.useInstancing = false;
  37545. this.groupInfoPartData = null;
  37546. this.partDataStartIndex = this.partDataEndIndex = null;
  37547. this.instancedBuffers = null;
  37548. }
  37549. Object.defineProperty(Render2DContext.prototype, "renderMode", {
  37550. /**
  37551. * Define which render Mode should be used to render the primitive: one of Render2DContext.RenderModeXxxx property
  37552. */
  37553. get: function () {
  37554. return this._renderMode;
  37555. },
  37556. enumerable: true,
  37557. configurable: true
  37558. });
  37559. Object.defineProperty(Render2DContext, "RenderModeOpaque", {
  37560. /**
  37561. * The set of primitives to render is opaque.
  37562. * This is the first rendering pass. All Opaque primitives are rendered. Depth Compare and Write are both enabled.
  37563. */
  37564. get: function () {
  37565. return Render2DContext._renderModeOpaque;
  37566. },
  37567. enumerable: true,
  37568. configurable: true
  37569. });
  37570. Object.defineProperty(Render2DContext, "RenderModeAlphaTest", {
  37571. /**
  37572. * The set of primitives to render is using Alpha Test (aka masking).
  37573. * 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.
  37574. */
  37575. get: function () {
  37576. return Render2DContext._renderModeAlphaTest;
  37577. },
  37578. enumerable: true,
  37579. configurable: true
  37580. });
  37581. Object.defineProperty(Render2DContext, "RenderModeTransparent", {
  37582. /**
  37583. * The set of primitives to render is transparent.
  37584. * 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.
  37585. */
  37586. get: function () {
  37587. return Render2DContext._renderModeTransparent;
  37588. },
  37589. enumerable: true,
  37590. configurable: true
  37591. });
  37592. Render2DContext._renderModeOpaque = 1;
  37593. Render2DContext._renderModeAlphaTest = 2;
  37594. Render2DContext._renderModeTransparent = 3;
  37595. return Render2DContext;
  37596. }());
  37597. BABYLON.Render2DContext = Render2DContext;
  37598. /**
  37599. * This class store information for the pointerEventObservable Observable.
  37600. * 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.
  37601. */
  37602. var PrimitivePointerInfo = (function () {
  37603. function PrimitivePointerInfo() {
  37604. this.primitivePointerPos = BABYLON.Vector2.Zero();
  37605. this.tilt = BABYLON.Vector2.Zero();
  37606. this.cancelBubble = false;
  37607. }
  37608. Object.defineProperty(PrimitivePointerInfo, "PointerOver", {
  37609. // 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.
  37610. /**
  37611. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  37612. * Bubbles: yes
  37613. */
  37614. get: function () {
  37615. return PrimitivePointerInfo._pointerOver;
  37616. },
  37617. enumerable: true,
  37618. configurable: true
  37619. });
  37620. Object.defineProperty(PrimitivePointerInfo, "PointerEnter", {
  37621. /**
  37622. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  37623. * Bubbles: no
  37624. */
  37625. get: function () {
  37626. return PrimitivePointerInfo._pointerEnter;
  37627. },
  37628. enumerable: true,
  37629. configurable: true
  37630. });
  37631. Object.defineProperty(PrimitivePointerInfo, "PointerDown", {
  37632. /**
  37633. * 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.
  37634. * Bubbles: yes
  37635. */
  37636. get: function () {
  37637. return PrimitivePointerInfo._pointerDown;
  37638. },
  37639. enumerable: true,
  37640. configurable: true
  37641. });
  37642. Object.defineProperty(PrimitivePointerInfo, "PointerMouseWheel", {
  37643. /**
  37644. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  37645. * Bubbles: yes
  37646. */
  37647. get: function () {
  37648. return PrimitivePointerInfo._pointerMouseWheel;
  37649. },
  37650. enumerable: true,
  37651. configurable: true
  37652. });
  37653. Object.defineProperty(PrimitivePointerInfo, "PointerMove", {
  37654. /**
  37655. * 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.
  37656. * Bubbles: yes
  37657. */
  37658. get: function () {
  37659. return PrimitivePointerInfo._pointerMove;
  37660. },
  37661. enumerable: true,
  37662. configurable: true
  37663. });
  37664. Object.defineProperty(PrimitivePointerInfo, "PointerUp", {
  37665. /**
  37666. * 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.
  37667. * Bubbles: yes
  37668. */
  37669. get: function () {
  37670. return PrimitivePointerInfo._pointerUp;
  37671. },
  37672. enumerable: true,
  37673. configurable: true
  37674. });
  37675. Object.defineProperty(PrimitivePointerInfo, "PointerOut", {
  37676. /**
  37677. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  37678. * Bubbles: yes
  37679. */
  37680. get: function () {
  37681. return PrimitivePointerInfo._pointerOut;
  37682. },
  37683. enumerable: true,
  37684. configurable: true
  37685. });
  37686. Object.defineProperty(PrimitivePointerInfo, "PointerLeave", {
  37687. /**
  37688. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  37689. * Bubbles: no
  37690. */
  37691. get: function () {
  37692. return PrimitivePointerInfo._pointerLeave;
  37693. },
  37694. enumerable: true,
  37695. configurable: true
  37696. });
  37697. Object.defineProperty(PrimitivePointerInfo, "PointerGotCapture", {
  37698. /**
  37699. * 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.
  37700. * Bubbles: yes
  37701. */
  37702. get: function () {
  37703. return PrimitivePointerInfo._pointerGotCapture;
  37704. },
  37705. enumerable: true,
  37706. configurable: true
  37707. });
  37708. Object.defineProperty(PrimitivePointerInfo, "PointerLostCapture", {
  37709. /**
  37710. * This event type is raised after pointer capture is released for a pointer.
  37711. * Bubbles: yes
  37712. */
  37713. get: function () {
  37714. return PrimitivePointerInfo._pointerLostCapture;
  37715. },
  37716. enumerable: true,
  37717. configurable: true
  37718. });
  37719. Object.defineProperty(PrimitivePointerInfo, "MouseWheelPrecision", {
  37720. get: function () {
  37721. return PrimitivePointerInfo._mouseWheelPrecision;
  37722. },
  37723. enumerable: true,
  37724. configurable: true
  37725. });
  37726. PrimitivePointerInfo.prototype.updateRelatedTarget = function (prim, primPointerPos) {
  37727. this.relatedTarget = prim;
  37728. this.relatedTargetPointerPos = primPointerPos;
  37729. };
  37730. PrimitivePointerInfo.getEventTypeName = function (mask) {
  37731. switch (mask) {
  37732. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  37733. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  37734. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  37735. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  37736. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  37737. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  37738. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  37739. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  37740. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  37741. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  37742. }
  37743. };
  37744. PrimitivePointerInfo._pointerOver = 0x0001;
  37745. PrimitivePointerInfo._pointerEnter = 0x0002;
  37746. PrimitivePointerInfo._pointerDown = 0x0004;
  37747. PrimitivePointerInfo._pointerMouseWheel = 0x0008;
  37748. PrimitivePointerInfo._pointerMove = 0x0010;
  37749. PrimitivePointerInfo._pointerUp = 0x0020;
  37750. PrimitivePointerInfo._pointerOut = 0x0040;
  37751. PrimitivePointerInfo._pointerLeave = 0x0080;
  37752. PrimitivePointerInfo._pointerGotCapture = 0x0100;
  37753. PrimitivePointerInfo._pointerLostCapture = 0x0200;
  37754. PrimitivePointerInfo._mouseWheelPrecision = 3.0;
  37755. return PrimitivePointerInfo;
  37756. }());
  37757. BABYLON.PrimitivePointerInfo = PrimitivePointerInfo;
  37758. /**
  37759. * Defines the horizontal and vertical alignment information for a Primitive.
  37760. */
  37761. var PrimitiveAlignment = (function () {
  37762. function PrimitiveAlignment(changeCallback) {
  37763. this._changedCallback = changeCallback;
  37764. this._horizontal = PrimitiveAlignment.AlignLeft;
  37765. this._vertical = PrimitiveAlignment.AlignBottom;
  37766. }
  37767. Object.defineProperty(PrimitiveAlignment, "AlignLeft", {
  37768. /**
  37769. * Alignment is made relative to the left edge of the Primitive. Valid for horizontal alignment only.
  37770. */
  37771. get: function () { return PrimitiveAlignment._AlignLeft; },
  37772. enumerable: true,
  37773. configurable: true
  37774. });
  37775. Object.defineProperty(PrimitiveAlignment, "AlignTop", {
  37776. /**
  37777. * Alignment is made relative to the top edge of the Primitive. Valid for vertical alignment only.
  37778. */
  37779. get: function () { return PrimitiveAlignment._AlignTop; },
  37780. enumerable: true,
  37781. configurable: true
  37782. });
  37783. Object.defineProperty(PrimitiveAlignment, "AlignRight", {
  37784. /**
  37785. * Alignment is made relative to the right edge of the Primitive. Valid for horizontal alignment only.
  37786. */
  37787. get: function () { return PrimitiveAlignment._AlignRight; },
  37788. enumerable: true,
  37789. configurable: true
  37790. });
  37791. Object.defineProperty(PrimitiveAlignment, "AlignBottom", {
  37792. /**
  37793. * Alignment is made relative to the bottom edge of the Primitive. Valid for vertical alignment only.
  37794. */
  37795. get: function () { return PrimitiveAlignment._AlignBottom; },
  37796. enumerable: true,
  37797. configurable: true
  37798. });
  37799. Object.defineProperty(PrimitiveAlignment, "AlignCenter", {
  37800. /**
  37801. * Alignment is made to center the content from equal distance to the opposite edges of the Primitive
  37802. */
  37803. get: function () { return PrimitiveAlignment._AlignCenter; },
  37804. enumerable: true,
  37805. configurable: true
  37806. });
  37807. Object.defineProperty(PrimitiveAlignment, "AlignStretch", {
  37808. /**
  37809. * The content is stretched toward the opposite edges of the Primitive
  37810. */
  37811. get: function () { return PrimitiveAlignment._AlignStretch; },
  37812. enumerable: true,
  37813. configurable: true
  37814. });
  37815. Object.defineProperty(PrimitiveAlignment.prototype, "horizontal", {
  37816. /**
  37817. * Get/set the horizontal alignment. Use one of the AlignXXX static properties of this class
  37818. */
  37819. get: function () {
  37820. return this._horizontal;
  37821. },
  37822. set: function (value) {
  37823. if (this._horizontal === value) {
  37824. return;
  37825. }
  37826. this._horizontal = value;
  37827. this._changedCallback();
  37828. },
  37829. enumerable: true,
  37830. configurable: true
  37831. });
  37832. Object.defineProperty(PrimitiveAlignment.prototype, "vertical", {
  37833. /**
  37834. * Get/set the vertical alignment. Use one of the AlignXXX static properties of this class
  37835. */
  37836. get: function () {
  37837. return this._vertical;
  37838. },
  37839. set: function (value) {
  37840. if (this._vertical === value) {
  37841. return;
  37842. }
  37843. this._vertical = value;
  37844. this._changedCallback();
  37845. },
  37846. enumerable: true,
  37847. configurable: true
  37848. });
  37849. /**
  37850. * Set the horizontal alignment from a string value.
  37851. * @param text can be either: 'left','right','center','stretch'
  37852. */
  37853. PrimitiveAlignment.prototype.setHorizontal = function (text) {
  37854. var v = text.trim().toLocaleLowerCase();
  37855. switch (v) {
  37856. case "left":
  37857. this.horizontal = PrimitiveAlignment.AlignLeft;
  37858. return;
  37859. case "right":
  37860. this.horizontal = PrimitiveAlignment.AlignRight;
  37861. return;
  37862. case "center":
  37863. this.horizontal = PrimitiveAlignment.AlignCenter;
  37864. return;
  37865. case "stretch":
  37866. this.horizontal = PrimitiveAlignment.AlignStretch;
  37867. return;
  37868. }
  37869. };
  37870. /**
  37871. * Set the vertical alignment from a string value.
  37872. * @param text can be either: 'top','bottom','center','stretch'
  37873. */
  37874. PrimitiveAlignment.prototype.setVertical = function (text) {
  37875. var v = text.trim().toLocaleLowerCase();
  37876. switch (v) {
  37877. case "top":
  37878. this.vertical = PrimitiveAlignment.AlignTop;
  37879. return;
  37880. case "bottom":
  37881. this.vertical = PrimitiveAlignment.AlignBottom;
  37882. return;
  37883. case "center":
  37884. this.vertical = PrimitiveAlignment.AlignCenter;
  37885. return;
  37886. case "stretch":
  37887. this.vertical = PrimitiveAlignment.AlignStretch;
  37888. return;
  37889. }
  37890. };
  37891. /**
  37892. * Set the horizontal and or vertical alignments from a string value.
  37893. * @param text can be: [<h:|horizontal:><left|right|center|stretch>], [<v:|vertical:><top|bottom|center|stretch>]
  37894. */
  37895. PrimitiveAlignment.prototype.fromString = function (value) {
  37896. var m = value.trim().split(",");
  37897. for (var _i = 0, m_1 = m; _i < m_1.length; _i++) {
  37898. var v = m_1[_i];
  37899. v = v.toLocaleLowerCase().trim();
  37900. // Horizontal
  37901. var i = v.indexOf("h:");
  37902. if (i === -1) {
  37903. i = v.indexOf("horizontal:");
  37904. }
  37905. if (i !== -1) {
  37906. v = v.substr(v.indexOf(":") + 1);
  37907. this.setHorizontal(v);
  37908. continue;
  37909. }
  37910. // Vertical
  37911. i = v.indexOf("v:");
  37912. if (i === -1) {
  37913. i = v.indexOf("vertical:");
  37914. }
  37915. if (i !== -1) {
  37916. v = v.substr(v.indexOf(":") + 1);
  37917. this.setVertical(v);
  37918. continue;
  37919. }
  37920. }
  37921. };
  37922. PrimitiveAlignment._AlignLeft = 1;
  37923. PrimitiveAlignment._AlignTop = 1; // Same as left
  37924. PrimitiveAlignment._AlignRight = 2;
  37925. PrimitiveAlignment._AlignBottom = 2; // Same as right
  37926. PrimitiveAlignment._AlignCenter = 3;
  37927. PrimitiveAlignment._AlignStretch = 4;
  37928. return PrimitiveAlignment;
  37929. }());
  37930. BABYLON.PrimitiveAlignment = PrimitiveAlignment;
  37931. /**
  37932. * Stores information about a Primitive that was intersected
  37933. */
  37934. var PrimitiveIntersectedInfo = (function () {
  37935. function PrimitiveIntersectedInfo(prim, intersectionLocation) {
  37936. this.prim = prim;
  37937. this.intersectionLocation = intersectionLocation;
  37938. }
  37939. return PrimitiveIntersectedInfo;
  37940. }());
  37941. BABYLON.PrimitiveIntersectedInfo = PrimitiveIntersectedInfo;
  37942. /**
  37943. * Define a thickness toward every edges of a Primitive to allow margin and padding.
  37944. * The thickness can be expressed as pixels, percentages, inherit the value of the parent primitive or be auto.
  37945. */
  37946. var PrimitiveThickness = (function () {
  37947. function PrimitiveThickness(parentAccess, changedCallback) {
  37948. this._parentAccess = parentAccess;
  37949. this._changedCallback = changedCallback;
  37950. this._pixels = new Array(4);
  37951. this._percentages = new Array(4);
  37952. this._setType(0, PrimitiveThickness.Auto);
  37953. this._setType(1, PrimitiveThickness.Auto);
  37954. this._setType(2, PrimitiveThickness.Auto);
  37955. this._setType(3, PrimitiveThickness.Auto);
  37956. this._pixels[0] = 0;
  37957. this._pixels[1] = 0;
  37958. this._pixels[2] = 0;
  37959. this._pixels[3] = 0;
  37960. }
  37961. /**
  37962. * Set the thickness from a string value
  37963. * @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.
  37964. * Values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  37965. */
  37966. PrimitiveThickness.prototype.fromString = function (thickness) {
  37967. this._clear();
  37968. var m = thickness.trim().split(",");
  37969. // Special case, one value to apply to all edges
  37970. if (m.length === 1 && thickness.indexOf(":") === -1) {
  37971. this._setStringValue(m[0], 0, false);
  37972. this._setStringValue(m[0], 1, false);
  37973. this._setStringValue(m[0], 2, false);
  37974. this._setStringValue(m[0], 3, false);
  37975. this._changedCallback();
  37976. return;
  37977. }
  37978. var res = false;
  37979. for (var _i = 0, m_2 = m; _i < m_2.length; _i++) {
  37980. var cm = m_2[_i];
  37981. res = this._extractString(cm, false) || res;
  37982. }
  37983. if (!res) {
  37984. throw new Error("Can't parse the string to create a PrimitiveMargin object, format must be: 'top: <value>, left:<value>, right:<value>, bottom:<value>");
  37985. }
  37986. // Check the margin that weren't set and set them in auto
  37987. if ((this._flags & 0x000F) === 0)
  37988. this._flags |= PrimitiveThickness.Pixel << 0;
  37989. if ((this._flags & 0x00F0) === 0)
  37990. this._flags |= PrimitiveThickness.Pixel << 4;
  37991. if ((this._flags & 0x0F00) === 0)
  37992. this._flags |= PrimitiveThickness.Pixel << 8;
  37993. if ((this._flags & 0xF000) === 0)
  37994. this._flags |= PrimitiveThickness.Pixel << 12;
  37995. this._changedCallback();
  37996. };
  37997. /**
  37998. * Set the thickness from multiple string
  37999. * Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  38000. * @param top the top thickness to set
  38001. * @param left the left thickness to set
  38002. * @param right the right thickness to set
  38003. * @param bottom the bottom thickness to set
  38004. */
  38005. PrimitiveThickness.prototype.fromStrings = function (top, left, right, bottom) {
  38006. this._clear();
  38007. this._setStringValue(top, 0, false);
  38008. this._setStringValue(left, 1, false);
  38009. this._setStringValue(right, 2, false);
  38010. this._setStringValue(bottom, 3, false);
  38011. this._changedCallback();
  38012. return this;
  38013. };
  38014. /**
  38015. * Set the thickness from pixel values
  38016. * @param top the top thickness in pixels to set
  38017. * @param left the left thickness in pixels to set
  38018. * @param right the right thickness in pixels to set
  38019. * @param bottom the bottom thickness in pixels to set
  38020. */
  38021. PrimitiveThickness.prototype.fromPixels = function (top, left, right, bottom) {
  38022. this._clear();
  38023. this._pixels[0] = top;
  38024. this._pixels[1] = left;
  38025. this._pixels[2] = right;
  38026. this._pixels[3] = bottom;
  38027. this._changedCallback();
  38028. return this;
  38029. };
  38030. /**
  38031. * Apply the same pixel value to all edges
  38032. * @param margin the value to set, in pixels.
  38033. */
  38034. PrimitiveThickness.prototype.fromUniformPixels = function (margin) {
  38035. this._clear();
  38036. this._pixels[0] = margin;
  38037. this._pixels[1] = margin;
  38038. this._pixels[2] = margin;
  38039. this._pixels[3] = margin;
  38040. this._changedCallback();
  38041. return this;
  38042. };
  38043. /**
  38044. * Set all edges in auto
  38045. */
  38046. PrimitiveThickness.prototype.auto = function () {
  38047. this._clear();
  38048. this._flags = (PrimitiveThickness.Auto << 0) | (PrimitiveThickness.Auto << 4) | (PrimitiveThickness.Auto << 8) | (PrimitiveThickness.Auto << 12);
  38049. this._pixels[0] = 0;
  38050. this._pixels[1] = 0;
  38051. this._pixels[2] = 0;
  38052. this._pixels[3] = 0;
  38053. this._changedCallback();
  38054. return this;
  38055. };
  38056. PrimitiveThickness.prototype._clear = function () {
  38057. this._flags = 0;
  38058. this._pixels[0] = 0;
  38059. this._pixels[1] = 0;
  38060. this._pixels[2] = 0;
  38061. this._pixels[3] = 0;
  38062. this._percentages[0] = null;
  38063. this._percentages[1] = null;
  38064. this._percentages[2] = null;
  38065. this._percentages[3] = null;
  38066. };
  38067. PrimitiveThickness.prototype._extractString = function (value, emitChanged) {
  38068. var v = value.trim().toLocaleLowerCase();
  38069. if (v.indexOf("top:") === 0) {
  38070. v = v.substr(4).trim();
  38071. return this._setStringValue(v, 0, emitChanged);
  38072. }
  38073. if (v.indexOf("left:") === 0) {
  38074. v = v.substr(5).trim();
  38075. return this._setStringValue(v, 1, emitChanged);
  38076. }
  38077. if (v.indexOf("right:") === 0) {
  38078. v = v.substr(6).trim();
  38079. return this._setStringValue(v, 2, emitChanged);
  38080. }
  38081. if (v.indexOf("bottom:") === 0) {
  38082. v = v.substr(7).trim();
  38083. return this._setStringValue(v, 3, emitChanged);
  38084. }
  38085. return false;
  38086. };
  38087. PrimitiveThickness.prototype._setStringValue = function (value, index, emitChanged) {
  38088. // Check for auto
  38089. var v = value.trim().toLocaleLowerCase();
  38090. if (v === "auto") {
  38091. if (this._isType(index, PrimitiveThickness.Auto)) {
  38092. return true;
  38093. }
  38094. this._setType(index, PrimitiveThickness.Auto);
  38095. this._pixels[index] = 0;
  38096. if (emitChanged) {
  38097. this._changedCallback();
  38098. }
  38099. }
  38100. else if (v === "inherit") {
  38101. if (this._isType(index, PrimitiveThickness.Inherit)) {
  38102. return true;
  38103. }
  38104. this._setType(index, PrimitiveThickness.Inherit);
  38105. this._pixels[index] = null;
  38106. if (emitChanged) {
  38107. this._changedCallback();
  38108. }
  38109. }
  38110. else {
  38111. var pI = v.indexOf("%");
  38112. // Check for percentage
  38113. if (pI !== -1) {
  38114. var n_1 = v.substr(0, pI);
  38115. var number_1 = Math.round(Number(n_1)) / 100; // Normalize the percentage to [0;1] with a 0.01 precision
  38116. if (this._isType(index, PrimitiveThickness.Percentage) && (this._percentages[index] === number_1)) {
  38117. return true;
  38118. }
  38119. this._setType(index, PrimitiveThickness.Percentage);
  38120. if (isNaN(number_1)) {
  38121. return false;
  38122. }
  38123. this._percentages[index] = number_1;
  38124. if (emitChanged) {
  38125. this._changedCallback();
  38126. }
  38127. return true;
  38128. }
  38129. // Check for pixel
  38130. var n = void 0;
  38131. pI = v.indexOf("px");
  38132. if (pI !== -1) {
  38133. n = v.substr(0, pI).trim();
  38134. }
  38135. else {
  38136. n = v;
  38137. }
  38138. var number = Number(n);
  38139. if (this._isType(index, PrimitiveThickness.Pixel) && (this._pixels[index] === number)) {
  38140. return true;
  38141. }
  38142. if (isNaN(number)) {
  38143. return false;
  38144. }
  38145. this._pixels[index] = number;
  38146. this._setType(index, PrimitiveThickness.Pixel);
  38147. if (emitChanged) {
  38148. this._changedCallback();
  38149. }
  38150. return true;
  38151. }
  38152. };
  38153. PrimitiveThickness.prototype._setPixels = function (value, index, emitChanged) {
  38154. // 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
  38155. value = Math.round(value);
  38156. if (this._isType(index, PrimitiveThickness.Pixel) && this._pixels[index] === value) {
  38157. return;
  38158. }
  38159. this._setType(index, PrimitiveThickness.Pixel);
  38160. this._pixels[index] = value;
  38161. if (emitChanged) {
  38162. this._changedCallback();
  38163. }
  38164. };
  38165. PrimitiveThickness.prototype._setPercentage = function (value, index, emitChanged) {
  38166. // Clip Value to bounds
  38167. value = Math.min(1, value);
  38168. value = Math.max(0, value);
  38169. value = Math.round(value * 100) / 100; // 0.01 precision
  38170. if (this._isType(index, PrimitiveThickness.Percentage) && this._percentages[index] === value) {
  38171. return;
  38172. }
  38173. this._setType(index, PrimitiveThickness.Percentage);
  38174. this._percentages[index] = value;
  38175. if (emitChanged) {
  38176. this._changedCallback();
  38177. }
  38178. };
  38179. PrimitiveThickness.prototype._getStringValue = function (index) {
  38180. var f = (this._flags >> (index * 4)) & 0xF;
  38181. switch (f) {
  38182. case PrimitiveThickness.Auto:
  38183. return "auto";
  38184. case PrimitiveThickness.Pixel:
  38185. return this._pixels[index] + "px";
  38186. case PrimitiveThickness.Percentage:
  38187. return this._percentages[index] * 100 + "%";
  38188. case PrimitiveThickness.Inherit:
  38189. return "inherit";
  38190. }
  38191. return "";
  38192. };
  38193. PrimitiveThickness.prototype._isType = function (index, type) {
  38194. var f = (this._flags >> (index * 4)) & 0xF;
  38195. return f === type;
  38196. };
  38197. PrimitiveThickness.prototype._getType = function (index, processInherit) {
  38198. var t = (this._flags >> (index * 4)) & 0xF;
  38199. if (processInherit && (t === PrimitiveThickness.Inherit)) {
  38200. var p = this._parentAccess();
  38201. if (p) {
  38202. return p._getType(index, true);
  38203. }
  38204. return PrimitiveThickness.Auto;
  38205. }
  38206. return t;
  38207. };
  38208. PrimitiveThickness.prototype._setType = function (index, type) {
  38209. this._flags &= ~(0xF << (index * 4));
  38210. this._flags |= type << (index * 4);
  38211. };
  38212. PrimitiveThickness.prototype.setTop = function (value) {
  38213. if (typeof value === "string") {
  38214. this._setStringValue(value, 0, true);
  38215. }
  38216. else {
  38217. this.topPixels = value;
  38218. }
  38219. };
  38220. PrimitiveThickness.prototype.setLeft = function (value) {
  38221. if (typeof value === "string") {
  38222. this._setStringValue(value, 1, true);
  38223. }
  38224. else {
  38225. this.leftPixels = value;
  38226. }
  38227. };
  38228. PrimitiveThickness.prototype.setRight = function (value) {
  38229. if (typeof value === "string") {
  38230. this._setStringValue(value, 2, true);
  38231. }
  38232. else {
  38233. this.rightPixels = value;
  38234. }
  38235. };
  38236. PrimitiveThickness.prototype.setBottom = function (value) {
  38237. if (typeof value === "string") {
  38238. this._setStringValue(value, 3, true);
  38239. }
  38240. else {
  38241. this.bottomPixels = value;
  38242. }
  38243. };
  38244. Object.defineProperty(PrimitiveThickness.prototype, "top", {
  38245. /**
  38246. * Get/set the top thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  38247. */
  38248. get: function () {
  38249. return this._getStringValue(0);
  38250. },
  38251. set: function (value) {
  38252. this._setStringValue(value, 0, true);
  38253. },
  38254. enumerable: true,
  38255. configurable: true
  38256. });
  38257. Object.defineProperty(PrimitiveThickness.prototype, "left", {
  38258. /**
  38259. * Get/set the left thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  38260. */
  38261. get: function () {
  38262. return this._getStringValue(1);
  38263. },
  38264. set: function (value) {
  38265. this._setStringValue(value, 1, true);
  38266. },
  38267. enumerable: true,
  38268. configurable: true
  38269. });
  38270. Object.defineProperty(PrimitiveThickness.prototype, "right", {
  38271. /**
  38272. * Get/set the right thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  38273. */
  38274. get: function () {
  38275. return this._getStringValue(2);
  38276. },
  38277. set: function (value) {
  38278. this._setStringValue(value, 2, true);
  38279. },
  38280. enumerable: true,
  38281. configurable: true
  38282. });
  38283. Object.defineProperty(PrimitiveThickness.prototype, "bottom", {
  38284. /**
  38285. * Get/set the bottom thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  38286. */
  38287. get: function () {
  38288. return this._getStringValue(3);
  38289. },
  38290. set: function (value) {
  38291. this._setStringValue(value, 3, true);
  38292. },
  38293. enumerable: true,
  38294. configurable: true
  38295. });
  38296. Object.defineProperty(PrimitiveThickness.prototype, "topPixels", {
  38297. /**
  38298. * Get/set the top thickness in pixel.
  38299. */
  38300. get: function () {
  38301. return this._pixels[0];
  38302. },
  38303. set: function (value) {
  38304. this._setPixels(value, 0, true);
  38305. },
  38306. enumerable: true,
  38307. configurable: true
  38308. });
  38309. Object.defineProperty(PrimitiveThickness.prototype, "leftPixels", {
  38310. /**
  38311. * Get/set the left thickness in pixel.
  38312. */
  38313. get: function () {
  38314. return this._pixels[1];
  38315. },
  38316. set: function (value) {
  38317. this._setPixels(value, 1, true);
  38318. },
  38319. enumerable: true,
  38320. configurable: true
  38321. });
  38322. Object.defineProperty(PrimitiveThickness.prototype, "rightPixels", {
  38323. /**
  38324. * Get/set the right thickness in pixel.
  38325. */
  38326. get: function () {
  38327. return this._pixels[2];
  38328. },
  38329. set: function (value) {
  38330. this._setPixels(value, 2, true);
  38331. },
  38332. enumerable: true,
  38333. configurable: true
  38334. });
  38335. Object.defineProperty(PrimitiveThickness.prototype, "bottomPixels", {
  38336. /**
  38337. * Get/set the bottom thickness in pixel.
  38338. */
  38339. get: function () {
  38340. return this._pixels[3];
  38341. },
  38342. set: function (value) {
  38343. this._setPixels(value, 3, true);
  38344. },
  38345. enumerable: true,
  38346. configurable: true
  38347. });
  38348. Object.defineProperty(PrimitiveThickness.prototype, "topPercentage", {
  38349. /**
  38350. * Get/set the top thickness in percentage.
  38351. * The get will return a valid value only if the edge type is percentage.
  38352. * The Set will change the edge mode if needed
  38353. */
  38354. get: function () {
  38355. return this._percentages[0];
  38356. },
  38357. set: function (value) {
  38358. this._setPercentage(value, 0, true);
  38359. },
  38360. enumerable: true,
  38361. configurable: true
  38362. });
  38363. Object.defineProperty(PrimitiveThickness.prototype, "leftPercentage", {
  38364. /**
  38365. * Get/set the left thickness in percentage.
  38366. * The get will return a valid value only if the edge mode is percentage.
  38367. * The Set will change the edge mode if needed
  38368. */
  38369. get: function () {
  38370. return this._percentages[1];
  38371. },
  38372. set: function (value) {
  38373. this._setPercentage(value, 1, true);
  38374. },
  38375. enumerable: true,
  38376. configurable: true
  38377. });
  38378. Object.defineProperty(PrimitiveThickness.prototype, "rightPercentage", {
  38379. /**
  38380. * Get/set the right thickness in percentage.
  38381. * The get will return a valid value only if the edge mode is percentage.
  38382. * The Set will change the edge mode if needed
  38383. */
  38384. get: function () {
  38385. return this._percentages[2];
  38386. },
  38387. set: function (value) {
  38388. this._setPercentage(value, 2, true);
  38389. },
  38390. enumerable: true,
  38391. configurable: true
  38392. });
  38393. Object.defineProperty(PrimitiveThickness.prototype, "bottomPercentage", {
  38394. /**
  38395. * Get/set the bottom thickness in percentage.
  38396. * The get will return a valid value only if the edge mode is percentage.
  38397. * The Set will change the edge mode if needed
  38398. */
  38399. get: function () {
  38400. return this._percentages[3];
  38401. },
  38402. set: function (value) {
  38403. this._setPercentage(value, 3, true);
  38404. },
  38405. enumerable: true,
  38406. configurable: true
  38407. });
  38408. Object.defineProperty(PrimitiveThickness.prototype, "topMode", {
  38409. /**
  38410. * Get/set the top mode. The setter shouldn't be used, other setters with value should be preferred
  38411. */
  38412. get: function () {
  38413. return this._getType(0, false);
  38414. },
  38415. set: function (mode) {
  38416. this._setType(0, mode);
  38417. },
  38418. enumerable: true,
  38419. configurable: true
  38420. });
  38421. Object.defineProperty(PrimitiveThickness.prototype, "leftMode", {
  38422. /**
  38423. * Get/set the left mode. The setter shouldn't be used, other setters with value should be preferred
  38424. */
  38425. get: function () {
  38426. return this._getType(1, false);
  38427. },
  38428. set: function (mode) {
  38429. this._setType(1, mode);
  38430. },
  38431. enumerable: true,
  38432. configurable: true
  38433. });
  38434. Object.defineProperty(PrimitiveThickness.prototype, "rightMode", {
  38435. /**
  38436. * Get/set the right mode. The setter shouldn't be used, other setters with value should be preferred
  38437. */
  38438. get: function () {
  38439. return this._getType(2, false);
  38440. },
  38441. set: function (mode) {
  38442. this._setType(2, mode);
  38443. },
  38444. enumerable: true,
  38445. configurable: true
  38446. });
  38447. Object.defineProperty(PrimitiveThickness.prototype, "bottomMode", {
  38448. /**
  38449. * Get/set the bottom mode. The setter shouldn't be used, other setters with value should be preferred
  38450. */
  38451. get: function () {
  38452. return this._getType(3, false);
  38453. },
  38454. set: function (mode) {
  38455. this._setType(3, mode);
  38456. },
  38457. enumerable: true,
  38458. configurable: true
  38459. });
  38460. PrimitiveThickness.prototype._computePixels = function (index, sourceArea, emitChanged) {
  38461. var type = this._getType(index, false);
  38462. if (type === PrimitiveThickness.Inherit) {
  38463. this._parentAccess()._computePixels(index, sourceArea, emitChanged);
  38464. return;
  38465. }
  38466. if (type !== PrimitiveThickness.Percentage) {
  38467. return;
  38468. }
  38469. var pixels = ((index === 0 || index === 3) ? sourceArea.height : sourceArea.width) * this._percentages[index];
  38470. this._pixels[index] = pixels;
  38471. if (emitChanged) {
  38472. this._changedCallback();
  38473. }
  38474. };
  38475. /**
  38476. * Compute the positioning/size of an area considering the thickness of this object and a given alignment
  38477. * @param sourceArea the source area
  38478. * @param contentSize the content size to position/resize
  38479. * @param alignment the alignment setting
  38480. * @param dstOffset the position of the content
  38481. * @param dstArea the new size of the content
  38482. */
  38483. PrimitiveThickness.prototype.computeWithAlignment = function (sourceArea, contentSize, alignment, dstOffset, dstArea) {
  38484. // Fetch some data
  38485. var topType = this._getType(0, true);
  38486. var leftType = this._getType(1, true);
  38487. var rightType = this._getType(2, true);
  38488. var bottomType = this._getType(3, true);
  38489. var hasWidth = contentSize && (contentSize.width != null);
  38490. var hasHeight = contentSize && (contentSize.height != null);
  38491. var width = hasWidth ? contentSize.width : 0;
  38492. var height = hasHeight ? contentSize.height : 0;
  38493. var isTopAuto = topType === PrimitiveThickness.Auto;
  38494. var isLeftAuto = leftType === PrimitiveThickness.Auto;
  38495. var isRightAuto = rightType === PrimitiveThickness.Auto;
  38496. var isBottomAuto = bottomType === PrimitiveThickness.Auto;
  38497. switch (alignment.horizontal) {
  38498. case PrimitiveAlignment.AlignLeft:
  38499. {
  38500. if (isLeftAuto) {
  38501. dstOffset.x = 0;
  38502. }
  38503. else {
  38504. this._computePixels(1, sourceArea, true);
  38505. dstOffset.x = this.leftPixels;
  38506. }
  38507. dstArea.width = width;
  38508. break;
  38509. }
  38510. case PrimitiveAlignment.AlignRight:
  38511. {
  38512. if (isRightAuto) {
  38513. dstOffset.x = Math.round(sourceArea.width - width);
  38514. }
  38515. else {
  38516. this._computePixels(2, sourceArea, true);
  38517. dstOffset.x = Math.round(sourceArea.width - (width + this.rightPixels));
  38518. }
  38519. dstArea.width = width;
  38520. break;
  38521. }
  38522. case PrimitiveAlignment.AlignStretch:
  38523. {
  38524. if (isLeftAuto) {
  38525. dstOffset.x = 0;
  38526. }
  38527. else {
  38528. this._computePixels(1, sourceArea, true);
  38529. dstOffset.x = this.leftPixels;
  38530. }
  38531. var right = 0;
  38532. if (!isRightAuto) {
  38533. this._computePixels(2, sourceArea, true);
  38534. right = this.rightPixels;
  38535. }
  38536. dstArea.width = sourceArea.width - (dstOffset.x + right);
  38537. break;
  38538. }
  38539. case PrimitiveAlignment.AlignCenter:
  38540. {
  38541. if (!isLeftAuto) {
  38542. this._computePixels(1, sourceArea, true);
  38543. }
  38544. if (!isRightAuto) {
  38545. this._computePixels(2, sourceArea, true);
  38546. }
  38547. var offset = (isLeftAuto ? 0 : this.leftPixels) - (isRightAuto ? 0 : this.rightPixels);
  38548. dstOffset.x = Math.round(((sourceArea.width - width) / 2) + offset);
  38549. dstArea.width = width;
  38550. break;
  38551. }
  38552. }
  38553. switch (alignment.vertical) {
  38554. case PrimitiveAlignment.AlignTop:
  38555. {
  38556. if (isTopAuto) {
  38557. dstOffset.y = sourceArea.height - height;
  38558. }
  38559. else {
  38560. this._computePixels(0, sourceArea, true);
  38561. dstOffset.y = Math.round(sourceArea.height - (height + this.topPixels));
  38562. }
  38563. dstArea.height = height;
  38564. break;
  38565. }
  38566. case PrimitiveAlignment.AlignBottom:
  38567. {
  38568. if (isBottomAuto) {
  38569. dstOffset.y = 0;
  38570. }
  38571. else {
  38572. this._computePixels(3, sourceArea, true);
  38573. dstOffset.y = this.bottomPixels;
  38574. }
  38575. dstArea.height = height;
  38576. break;
  38577. }
  38578. case PrimitiveAlignment.AlignStretch:
  38579. {
  38580. if (isBottomAuto) {
  38581. dstOffset.y = 0;
  38582. }
  38583. else {
  38584. this._computePixels(3, sourceArea, true);
  38585. dstOffset.y = this.bottomPixels;
  38586. }
  38587. var top_1 = 0;
  38588. if (!isTopAuto) {
  38589. this._computePixels(0, sourceArea, true);
  38590. top_1 = this.topPixels;
  38591. }
  38592. dstArea.height = sourceArea.height - (dstOffset.y + top_1);
  38593. break;
  38594. }
  38595. case PrimitiveAlignment.AlignCenter:
  38596. {
  38597. if (!isTopAuto) {
  38598. this._computePixels(0, sourceArea, true);
  38599. }
  38600. if (!isBottomAuto) {
  38601. this._computePixels(3, sourceArea, true);
  38602. }
  38603. var offset = (isBottomAuto ? 0 : this.bottomPixels) - (isTopAuto ? 0 : this.topPixels);
  38604. dstOffset.y = Math.round(((sourceArea.height - height) / 2) + offset);
  38605. dstArea.height = height;
  38606. break;
  38607. }
  38608. }
  38609. };
  38610. /**
  38611. * Compute an area and its position considering this thickness properties based on a given source area
  38612. * @param sourceArea the source area
  38613. * @param dstOffset the position of the resulting area
  38614. * @param dstArea the size of the resulting area
  38615. */
  38616. PrimitiveThickness.prototype.compute = function (sourceArea, dstOffset, dstArea) {
  38617. this._computePixels(0, sourceArea, true);
  38618. this._computePixels(1, sourceArea, true);
  38619. this._computePixels(2, sourceArea, true);
  38620. this._computePixels(3, sourceArea, true);
  38621. dstOffset.x = this.leftPixels;
  38622. dstArea.width = sourceArea.width - (dstOffset.x + this.rightPixels);
  38623. dstOffset.y = this.bottomPixels;
  38624. dstArea.height = sourceArea.height - (dstOffset.y + this.topPixels);
  38625. };
  38626. /**
  38627. * Compute an area considering this thickness properties based on a given source area
  38628. * @param sourceArea the source area
  38629. * @param result the resulting area
  38630. */
  38631. PrimitiveThickness.prototype.computeArea = function (sourceArea, result) {
  38632. this._computePixels(0, sourceArea, true);
  38633. this._computePixels(1, sourceArea, true);
  38634. this._computePixels(2, sourceArea, true);
  38635. this._computePixels(3, sourceArea, true);
  38636. result.width = this.leftPixels + sourceArea.width + this.rightPixels;
  38637. result.height = this.bottomPixels + sourceArea.height + this.topPixels;
  38638. };
  38639. PrimitiveThickness.prototype.enlarge = function (sourceArea, dstOffset, enlargedArea) {
  38640. this._computePixels(0, sourceArea, true);
  38641. this._computePixels(1, sourceArea, true);
  38642. this._computePixels(2, sourceArea, true);
  38643. this._computePixels(3, sourceArea, true);
  38644. dstOffset.x = this.leftPixels;
  38645. enlargedArea.width = sourceArea.width + (dstOffset.x + this.rightPixels);
  38646. dstOffset.y = this.bottomPixels;
  38647. enlargedArea.height = sourceArea.height + (dstOffset.y + this.topPixels);
  38648. };
  38649. PrimitiveThickness.Auto = 0x1;
  38650. PrimitiveThickness.Inherit = 0x2;
  38651. PrimitiveThickness.Percentage = 0x4;
  38652. PrimitiveThickness.Pixel = 0x8;
  38653. return PrimitiveThickness;
  38654. }());
  38655. BABYLON.PrimitiveThickness = PrimitiveThickness;
  38656. /**
  38657. * Main class used for the Primitive Intersection API
  38658. */
  38659. var IntersectInfo2D = (function () {
  38660. function IntersectInfo2D() {
  38661. this.findFirstOnly = false;
  38662. this.intersectHidden = false;
  38663. this.pickPosition = BABYLON.Vector2.Zero();
  38664. }
  38665. Object.defineProperty(IntersectInfo2D.prototype, "isIntersected", {
  38666. /**
  38667. * true if at least one primitive intersected during the test
  38668. */
  38669. get: function () {
  38670. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  38671. },
  38672. enumerable: true,
  38673. configurable: true
  38674. });
  38675. IntersectInfo2D.prototype.isPrimIntersected = function (prim) {
  38676. for (var _i = 0, _a = this.intersectedPrimitives; _i < _a.length; _i++) {
  38677. var cur = _a[_i];
  38678. if (cur.prim === prim) {
  38679. return cur.intersectionLocation;
  38680. }
  38681. }
  38682. return null;
  38683. };
  38684. // Internals, don't use
  38685. IntersectInfo2D.prototype._exit = function (firstLevel) {
  38686. if (firstLevel) {
  38687. this._globalPickPosition = null;
  38688. }
  38689. };
  38690. return IntersectInfo2D;
  38691. }());
  38692. BABYLON.IntersectInfo2D = IntersectInfo2D;
  38693. var Prim2DBase = (function (_super) {
  38694. __extends(Prim2DBase, _super);
  38695. function Prim2DBase(settings) {
  38696. // Avoid checking every time if the object exists
  38697. if (settings == null) {
  38698. settings = {};
  38699. }
  38700. // BASE CLASS CALL
  38701. _super.call(this);
  38702. // Fetch the owner, parent. There're many ways to do it and we can end up with nothing for both
  38703. var owner;
  38704. var parent;
  38705. if (Prim2DBase._isCanvasInit) {
  38706. owner = this;
  38707. parent = null;
  38708. this._canvasPreInit(settings);
  38709. }
  38710. else {
  38711. if (settings.parent != null) {
  38712. parent = settings.parent;
  38713. owner = settings.parent.owner;
  38714. if (!owner) {
  38715. throw new Error("Parent " + parent.id + " of " + settings.id + " doesn't have a valid owner!");
  38716. }
  38717. 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)) {
  38718. 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");
  38719. }
  38720. }
  38721. }
  38722. // Fields initialization
  38723. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  38724. this._size = null; //Size.Zero();
  38725. this._actualSize = null;
  38726. this._boundingSize = BABYLON.Size.Zero();
  38727. this._layoutArea = BABYLON.Size.Zero();
  38728. this._layoutAreaPos = BABYLON.Vector2.Zero();
  38729. this._marginOffset = BABYLON.Vector2.Zero();
  38730. this._paddingOffset = BABYLON.Vector2.Zero();
  38731. this._parentPaddingOffset = BABYLON.Vector2.Zero();
  38732. this._parentContentArea = BABYLON.Size.Zero();
  38733. this._lastAutoSizeArea = BABYLON.Size.Zero();
  38734. this._contentArea = new BABYLON.Size(null, null);
  38735. this._pointerEventObservable = new BABYLON.Observable();
  38736. this._boundingInfo = new BABYLON.BoundingInfo2D();
  38737. this._owner = owner;
  38738. this._parent = null;
  38739. this._margin = null;
  38740. this._padding = null;
  38741. this._marginAlignment = null;
  38742. this._id = settings.id;
  38743. this.propertyChanged = new BABYLON.Observable();
  38744. this._children = new Array();
  38745. this._localTransform = new BABYLON.Matrix();
  38746. this._globalTransform = null;
  38747. this._invGlobalTransform = null;
  38748. this._globalTransformProcessStep = 0;
  38749. this._globalTransformStep = 0;
  38750. this._renderGroup = null;
  38751. this._primLinearPosition = 0;
  38752. this._manualZOrder = null;
  38753. this._zOrder = 0;
  38754. this._zMax = 0;
  38755. this._firstZDirtyIndex = Prim2DBase._bigInt;
  38756. this._setFlags(BABYLON.SmartPropertyPrim.flagIsPickable | BABYLON.SmartPropertyPrim.flagBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  38757. if (settings.opacity != null) {
  38758. this._opacity = settings.opacity;
  38759. }
  38760. else {
  38761. this._opacity = 1;
  38762. }
  38763. if (settings.childrenFlatZOrder) {
  38764. this._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  38765. }
  38766. // If the parent is given, initialize the hierarchy/owner related data
  38767. if (parent != null) {
  38768. parent.addChild(this);
  38769. this._patchHierarchy(parent.owner);
  38770. }
  38771. // If it's a group, detect its own states
  38772. if (this.owner && this instanceof BABYLON.Group2D) {
  38773. var group = this;
  38774. group.detectGroupStates();
  38775. }
  38776. // Time to insert children if some are specified
  38777. if (settings.children != null) {
  38778. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  38779. var child = _a[_i];
  38780. this.addChild(child);
  38781. // Good time to patch the hierarchy, it won't go very far if there's no need to
  38782. child._patchHierarchy(this.owner);
  38783. }
  38784. }
  38785. // Set the model related properties
  38786. if (settings.position != null) {
  38787. this.position = settings.position;
  38788. }
  38789. else if (settings.x != null || settings.y != null) {
  38790. this.position = new BABYLON.Vector2(settings.x || 0, settings.y || 0);
  38791. }
  38792. else {
  38793. this._position = null;
  38794. }
  38795. this.rotation = (settings.rotation == null) ? 0 : settings.rotation;
  38796. this.scale = (settings.scale == null) ? 1 : settings.scale;
  38797. this.levelVisible = (settings.isVisible == null) ? true : settings.isVisible;
  38798. this.origin = settings.origin || new BABYLON.Vector2(0.5, 0.5);
  38799. // Layout Engine
  38800. if (settings.layoutEngine != null) {
  38801. if (typeof settings.layoutEngine === "string") {
  38802. var name_1 = settings.layoutEngine.toLocaleLowerCase().trim();
  38803. if (name_1 === "canvas" || name_1 === "canvaslayoutengine") {
  38804. this.layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  38805. }
  38806. else if (name_1.indexOf("stackpanel") === 0 || name_1.indexOf("horizontalstackpanel") === 0) {
  38807. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Horizontal;
  38808. }
  38809. else if (name_1.indexOf("verticalstackpanel") === 0) {
  38810. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Vertical;
  38811. }
  38812. }
  38813. else if (settings.layoutEngine instanceof BABYLON.LayoutEngineBase) {
  38814. this.layoutEngine = settings.layoutEngine;
  38815. }
  38816. }
  38817. // Set the layout/margin stuffs
  38818. if (settings.marginTop) {
  38819. this.margin.setTop(settings.marginTop);
  38820. }
  38821. if (settings.marginLeft) {
  38822. this.margin.setLeft(settings.marginLeft);
  38823. }
  38824. if (settings.marginRight) {
  38825. this.margin.setRight(settings.marginRight);
  38826. }
  38827. if (settings.marginBottom) {
  38828. this.margin.setBottom(settings.marginBottom);
  38829. }
  38830. if (settings.margin) {
  38831. if (typeof settings.margin === "string") {
  38832. this.margin.fromString(settings.margin);
  38833. }
  38834. else {
  38835. this.margin.fromUniformPixels(settings.margin);
  38836. }
  38837. }
  38838. if (settings.marginHAlignment) {
  38839. this.marginAlignment.horizontal = settings.marginHAlignment;
  38840. }
  38841. if (settings.marginVAlignment) {
  38842. this.marginAlignment.vertical = settings.marginVAlignment;
  38843. }
  38844. if (settings.marginAlignment) {
  38845. this.marginAlignment.fromString(settings.marginAlignment);
  38846. }
  38847. if (settings.paddingTop) {
  38848. this.padding.setTop(settings.paddingTop);
  38849. }
  38850. if (settings.paddingLeft) {
  38851. this.padding.setLeft(settings.paddingLeft);
  38852. }
  38853. if (settings.paddingRight) {
  38854. this.padding.setRight(settings.paddingRight);
  38855. }
  38856. if (settings.paddingBottom) {
  38857. this.padding.setBottom(settings.paddingBottom);
  38858. }
  38859. if (settings.padding) {
  38860. this.padding.fromString(settings.padding);
  38861. }
  38862. // Dirty layout and positioning
  38863. this._parentLayoutDirty();
  38864. this._positioningDirty();
  38865. }
  38866. Object.defineProperty(Prim2DBase.prototype, "actionManager", {
  38867. get: function () {
  38868. if (!this._actionManager) {
  38869. this._actionManager = new BABYLON.ActionManager(this.owner.scene);
  38870. }
  38871. return this._actionManager;
  38872. },
  38873. enumerable: true,
  38874. configurable: true
  38875. });
  38876. /**
  38877. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  38878. * @param predicate the predicate to test on each parent
  38879. * @return the first primitive where the predicate was successful
  38880. */
  38881. Prim2DBase.prototype.traverseUp = function (predicate) {
  38882. var p = this;
  38883. while (p != null) {
  38884. if (predicate(p)) {
  38885. return p;
  38886. }
  38887. p = p._parent;
  38888. }
  38889. return null;
  38890. };
  38891. Object.defineProperty(Prim2DBase.prototype, "owner", {
  38892. /**
  38893. * Retrieve the owner Canvas2D
  38894. */
  38895. get: function () {
  38896. return this._owner;
  38897. },
  38898. enumerable: true,
  38899. configurable: true
  38900. });
  38901. Object.defineProperty(Prim2DBase.prototype, "parent", {
  38902. /**
  38903. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  38904. */
  38905. get: function () {
  38906. return this._parent;
  38907. },
  38908. enumerable: true,
  38909. configurable: true
  38910. });
  38911. Object.defineProperty(Prim2DBase.prototype, "children", {
  38912. /**
  38913. * The array of direct children primitives
  38914. */
  38915. get: function () {
  38916. return this._children;
  38917. },
  38918. enumerable: true,
  38919. configurable: true
  38920. });
  38921. Object.defineProperty(Prim2DBase.prototype, "id", {
  38922. /**
  38923. * The identifier of this primitive, may not be unique, it's for information purpose only
  38924. */
  38925. get: function () {
  38926. return this._id;
  38927. },
  38928. enumerable: true,
  38929. configurable: true
  38930. });
  38931. Object.defineProperty(Prim2DBase.prototype, "actualPosition", {
  38932. get: function () {
  38933. if (this._actualPosition != null) {
  38934. return this._actualPosition;
  38935. }
  38936. if (this._position != null) {
  38937. return this._position;
  38938. }
  38939. // At least return 0,0, we can't return null on actualPosition
  38940. return Prim2DBase._nullPosition;
  38941. },
  38942. /**
  38943. * DO NOT INVOKE for internal purpose only
  38944. */
  38945. set: function (val) {
  38946. this._actualPosition = val;
  38947. },
  38948. enumerable: true,
  38949. configurable: true
  38950. });
  38951. Object.defineProperty(Prim2DBase.prototype, "actualX", {
  38952. /**
  38953. * Shortcut to actualPosition.x
  38954. */
  38955. get: function () {
  38956. return this.actualPosition.x;
  38957. },
  38958. enumerable: true,
  38959. configurable: true
  38960. });
  38961. Object.defineProperty(Prim2DBase.prototype, "actualY", {
  38962. /**
  38963. * Shortcut to actualPosition.y
  38964. */
  38965. get: function () {
  38966. return this.actualPosition.y;
  38967. },
  38968. enumerable: true,
  38969. configurable: true
  38970. });
  38971. Object.defineProperty(Prim2DBase.prototype, "position", {
  38972. /**
  38973. * Position of the primitive, relative to its parent.
  38974. * BEWARE: if you change only position.x or y it won't trigger a property change and you won't have the expected behavior.
  38975. * Use this property to set a new Vector2 object, otherwise to change only the x/y use Prim2DBase.x or y properties.
  38976. * Setting this property may have no effect is specific alignment are in effect.
  38977. */
  38978. get: function () {
  38979. return this._position || Prim2DBase._nullPosition;
  38980. },
  38981. set: function (value) {
  38982. if (!this._checkPositionChange()) {
  38983. return;
  38984. }
  38985. this._position = value;
  38986. this.markAsDirty("actualPosition");
  38987. },
  38988. enumerable: true,
  38989. configurable: true
  38990. });
  38991. Object.defineProperty(Prim2DBase.prototype, "x", {
  38992. /**
  38993. * Direct access to the position.x value of the primitive
  38994. * Use this property when you only want to change one component of the position property
  38995. */
  38996. get: function () {
  38997. if (!this._position) {
  38998. return null;
  38999. }
  39000. return this._position.x;
  39001. },
  39002. set: function (value) {
  39003. if (!this._checkPositionChange()) {
  39004. return;
  39005. }
  39006. if (!this._position) {
  39007. this._position = BABYLON.Vector2.Zero();
  39008. }
  39009. if (this._position.x === value) {
  39010. return;
  39011. }
  39012. this._position.x = value;
  39013. this.markAsDirty("position");
  39014. this.markAsDirty("actualPosition");
  39015. },
  39016. enumerable: true,
  39017. configurable: true
  39018. });
  39019. Object.defineProperty(Prim2DBase.prototype, "y", {
  39020. /**
  39021. * Direct access to the position.y value of the primitive
  39022. * Use this property when you only want to change one component of the position property
  39023. */
  39024. get: function () {
  39025. if (!this._position) {
  39026. return null;
  39027. }
  39028. return this._position.y;
  39029. },
  39030. set: function (value) {
  39031. if (!this._checkPositionChange()) {
  39032. return;
  39033. }
  39034. if (!this._position) {
  39035. this._position = BABYLON.Vector2.Zero();
  39036. }
  39037. if (this._position.y === value) {
  39038. return;
  39039. }
  39040. this._position.y = value;
  39041. this.markAsDirty("position");
  39042. this.markAsDirty("actualPosition");
  39043. },
  39044. enumerable: true,
  39045. configurable: true
  39046. });
  39047. Object.defineProperty(Prim2DBase.prototype, "size", {
  39048. /**
  39049. * Size of the primitive or its bounding area
  39050. * BEWARE: if you change only size.width or height it won't trigger a property change and you won't have the expected behavior.
  39051. * Use this property to set a new Size object, otherwise to change only the width/height use Prim2DBase.width or height properties.
  39052. */
  39053. get: function () {
  39054. if (!this._size || this._size.width == null || this._size.height == null) {
  39055. if (Prim2DBase.boundinbBoxReentrency) {
  39056. return Prim2DBase.nullSize;
  39057. }
  39058. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  39059. return this._boundingSize;
  39060. }
  39061. Prim2DBase.boundinbBoxReentrency = true;
  39062. var b = this.boundingInfo;
  39063. Prim2DBase.boundinbBoxReentrency = false;
  39064. return this._boundingSize;
  39065. }
  39066. return this._size;
  39067. },
  39068. set: function (value) {
  39069. this._size = value;
  39070. },
  39071. enumerable: true,
  39072. configurable: true
  39073. });
  39074. Object.defineProperty(Prim2DBase.prototype, "width", {
  39075. /**
  39076. * Direct access to the size.width value of the primitive
  39077. * Use this property when you only want to change one component of the size property
  39078. */
  39079. get: function () {
  39080. if (!this.size) {
  39081. return null;
  39082. }
  39083. return this.size.width;
  39084. },
  39085. set: function (value) {
  39086. if (!this.size) {
  39087. this.size = new BABYLON.Size(value, 0);
  39088. return;
  39089. }
  39090. if (this.size.width === value) {
  39091. return;
  39092. }
  39093. this.size.width = value;
  39094. this.markAsDirty("size");
  39095. this._positioningDirty();
  39096. },
  39097. enumerable: true,
  39098. configurable: true
  39099. });
  39100. Object.defineProperty(Prim2DBase.prototype, "height", {
  39101. /**
  39102. * Direct access to the size.height value of the primitive
  39103. * Use this property when you only want to change one component of the size property
  39104. */
  39105. get: function () {
  39106. if (!this.size) {
  39107. return null;
  39108. }
  39109. return this.size.height;
  39110. },
  39111. set: function (value) {
  39112. if (!this.size) {
  39113. this.size = new BABYLON.Size(0, value);
  39114. return;
  39115. }
  39116. if (this.size.height === value) {
  39117. return;
  39118. }
  39119. this.size.height = value;
  39120. this.markAsDirty("size");
  39121. this._positioningDirty();
  39122. },
  39123. enumerable: true,
  39124. configurable: true
  39125. });
  39126. Object.defineProperty(Prim2DBase.prototype, "rotation", {
  39127. get: function () {
  39128. return this._rotation;
  39129. },
  39130. set: function (value) {
  39131. this._rotation = value;
  39132. },
  39133. enumerable: true,
  39134. configurable: true
  39135. });
  39136. Object.defineProperty(Prim2DBase.prototype, "scale", {
  39137. get: function () {
  39138. return this._scale;
  39139. },
  39140. set: function (value) {
  39141. this._scale = value;
  39142. },
  39143. enumerable: true,
  39144. configurable: true
  39145. });
  39146. Object.defineProperty(Prim2DBase.prototype, "actualSize", {
  39147. /**
  39148. * Return the size of the primitive as it's being rendered into the target.
  39149. * 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.
  39150. * BEWARE: don't use the setter, it's for internal purpose only
  39151. * Note to implementers: you have to override this property and declare if necessary a @xxxxInstanceLevel decorator
  39152. */
  39153. get: function () {
  39154. if (this._actualSize) {
  39155. return this._actualSize;
  39156. }
  39157. return this._size;
  39158. },
  39159. set: function (value) {
  39160. if (this._actualSize.equals(value)) {
  39161. return;
  39162. }
  39163. this._actualSize = value;
  39164. },
  39165. enumerable: true,
  39166. configurable: true
  39167. });
  39168. Object.defineProperty(Prim2DBase.prototype, "actualZOffset", {
  39169. get: function () {
  39170. if (this._manualZOrder != null) {
  39171. return this._manualZOrder;
  39172. }
  39173. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  39174. this._updateZOrder();
  39175. }
  39176. return (1 - this._zOrder);
  39177. },
  39178. enumerable: true,
  39179. configurable: true
  39180. });
  39181. Object.defineProperty(Prim2DBase.prototype, "minSize", {
  39182. /**
  39183. * Get or set the minimal size the Layout Engine should respect when computing the primitive's actualSize.
  39184. * The Primitive's size won't be less than specified.
  39185. * The default value depends of the Primitive type
  39186. */
  39187. get: function () {
  39188. return this._minSize;
  39189. },
  39190. set: function (value) {
  39191. if (this._minSize && value && this._minSize.equals(value)) {
  39192. return;
  39193. }
  39194. this._minSize = value;
  39195. this._parentLayoutDirty();
  39196. },
  39197. enumerable: true,
  39198. configurable: true
  39199. });
  39200. Object.defineProperty(Prim2DBase.prototype, "maxSize", {
  39201. /**
  39202. * Get or set the maximal size the Layout Engine should respect when computing the primitive's actualSize.
  39203. * The Primitive's size won't be more than specified.
  39204. * The default value depends of the Primitive type
  39205. */
  39206. get: function () {
  39207. return this._maxSize;
  39208. },
  39209. set: function (value) {
  39210. if (this._maxSize && value && this._maxSize.equals(value)) {
  39211. return;
  39212. }
  39213. this._maxSize = value;
  39214. this._parentLayoutDirty();
  39215. },
  39216. enumerable: true,
  39217. configurable: true
  39218. });
  39219. Object.defineProperty(Prim2DBase.prototype, "origin", {
  39220. /**
  39221. * The origin defines the normalized coordinate of the center of the primitive, from the bottom/left corner.
  39222. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  39223. * For instance:
  39224. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  39225. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  39226. * 0,1 means the center is top/left
  39227. * @returns The normalized center.
  39228. */
  39229. get: function () {
  39230. return this._origin;
  39231. },
  39232. set: function (value) {
  39233. this._origin = value;
  39234. },
  39235. enumerable: true,
  39236. configurable: true
  39237. });
  39238. Object.defineProperty(Prim2DBase.prototype, "levelVisible", {
  39239. get: function () {
  39240. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelVisible);
  39241. },
  39242. set: function (value) {
  39243. this._changeFlags(BABYLON.SmartPropertyPrim.flagLevelVisible, value);
  39244. },
  39245. enumerable: true,
  39246. configurable: true
  39247. });
  39248. Object.defineProperty(Prim2DBase.prototype, "isVisible", {
  39249. get: function () {
  39250. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsVisible);
  39251. },
  39252. set: function (value) {
  39253. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsVisible, value);
  39254. },
  39255. enumerable: true,
  39256. configurable: true
  39257. });
  39258. Object.defineProperty(Prim2DBase.prototype, "zOrder", {
  39259. get: function () {
  39260. return this._manualZOrder;
  39261. },
  39262. set: function (value) {
  39263. if (this._manualZOrder === value) {
  39264. return;
  39265. }
  39266. this._manualZOrder = value;
  39267. this.onZOrderChanged();
  39268. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  39269. this._actualZOrderChangedObservable.notifyObservers(value);
  39270. }
  39271. },
  39272. enumerable: true,
  39273. configurable: true
  39274. });
  39275. Object.defineProperty(Prim2DBase.prototype, "isManualZOrder", {
  39276. get: function () {
  39277. return this._manualZOrder != null;
  39278. },
  39279. enumerable: true,
  39280. configurable: true
  39281. });
  39282. Object.defineProperty(Prim2DBase.prototype, "margin", {
  39283. get: function () {
  39284. var _this = this;
  39285. if (!this._margin) {
  39286. this._margin = new PrimitiveThickness(function () {
  39287. if (!_this.parent) {
  39288. return null;
  39289. }
  39290. return _this.parent.margin;
  39291. }, function () { return _this._positioningDirty(); });
  39292. }
  39293. return this._margin;
  39294. },
  39295. enumerable: true,
  39296. configurable: true
  39297. });
  39298. Object.defineProperty(Prim2DBase.prototype, "_hasMargin", {
  39299. get: function () {
  39300. return (this._margin !== null) || (this._marginAlignment !== null);
  39301. },
  39302. enumerable: true,
  39303. configurable: true
  39304. });
  39305. Object.defineProperty(Prim2DBase.prototype, "padding", {
  39306. get: function () {
  39307. var _this = this;
  39308. if (!this._padding) {
  39309. this._padding = new PrimitiveThickness(function () {
  39310. if (!_this.parent) {
  39311. return null;
  39312. }
  39313. return _this.parent.padding;
  39314. }, function () { return _this._positioningDirty(); });
  39315. }
  39316. return this._padding;
  39317. },
  39318. enumerable: true,
  39319. configurable: true
  39320. });
  39321. Object.defineProperty(Prim2DBase.prototype, "_hasPadding", {
  39322. get: function () {
  39323. return this._padding !== null;
  39324. },
  39325. enumerable: true,
  39326. configurable: true
  39327. });
  39328. Object.defineProperty(Prim2DBase.prototype, "marginAlignment", {
  39329. get: function () {
  39330. var _this = this;
  39331. if (!this._marginAlignment) {
  39332. this._marginAlignment = new PrimitiveAlignment(function () { return _this._positioningDirty(); });
  39333. }
  39334. return this._marginAlignment;
  39335. },
  39336. enumerable: true,
  39337. configurable: true
  39338. });
  39339. Object.defineProperty(Prim2DBase.prototype, "opacity", {
  39340. get: function () {
  39341. return this._opacity;
  39342. },
  39343. set: function (value) {
  39344. if (value < 0) {
  39345. value = 0;
  39346. }
  39347. else if (value > 1) {
  39348. value = 1;
  39349. }
  39350. if (this._opacity === value) {
  39351. return;
  39352. }
  39353. this._opacity = value;
  39354. this._updateRenderMode();
  39355. this._spreadActualOpacityChanged();
  39356. },
  39357. enumerable: true,
  39358. configurable: true
  39359. });
  39360. Object.defineProperty(Prim2DBase.prototype, "actualOpacity", {
  39361. get: function () {
  39362. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualOpacityDirty)) {
  39363. var cur = this.parent;
  39364. var op = this.opacity;
  39365. while (cur) {
  39366. op *= cur.opacity;
  39367. cur = cur.parent;
  39368. }
  39369. this._actualOpacity = op;
  39370. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  39371. }
  39372. return this._actualOpacity;
  39373. },
  39374. enumerable: true,
  39375. configurable: true
  39376. });
  39377. Object.defineProperty(Prim2DBase.prototype, "layoutEngine", {
  39378. /**
  39379. * Get/set the layout engine to use for this primitive.
  39380. * The default layout engine is the CanvasLayoutEngine.
  39381. */
  39382. get: function () {
  39383. if (!this._layoutEngine) {
  39384. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  39385. }
  39386. return this._layoutEngine;
  39387. },
  39388. set: function (value) {
  39389. if (this._layoutEngine === value) {
  39390. return;
  39391. }
  39392. this._changeLayoutEngine(value);
  39393. },
  39394. enumerable: true,
  39395. configurable: true
  39396. });
  39397. Object.defineProperty(Prim2DBase.prototype, "layoutArea", {
  39398. /**
  39399. * Get/set the layout are of this primitive.
  39400. * The Layout area is the zone allocated by the Layout Engine for this particular primitive. Margins/Alignment will be computed based on this area.
  39401. * The setter should only be called by a Layout Engine class.
  39402. */
  39403. get: function () {
  39404. return this._layoutArea;
  39405. },
  39406. set: function (val) {
  39407. if (this._layoutArea.equals(val)) {
  39408. return;
  39409. }
  39410. this._positioningDirty();
  39411. this._layoutArea = val;
  39412. },
  39413. enumerable: true,
  39414. configurable: true
  39415. });
  39416. Object.defineProperty(Prim2DBase.prototype, "layoutAreaPos", {
  39417. /**
  39418. * Get/set the layout area position (relative to the parent primitive).
  39419. * The setter should only be called by a Layout Engine class.
  39420. */
  39421. get: function () {
  39422. return this._layoutAreaPos;
  39423. },
  39424. set: function (val) {
  39425. if (this._layoutAreaPos.equals(val)) {
  39426. return;
  39427. }
  39428. this._positioningDirty();
  39429. this._layoutAreaPos = val;
  39430. },
  39431. enumerable: true,
  39432. configurable: true
  39433. });
  39434. Object.defineProperty(Prim2DBase.prototype, "isPickable", {
  39435. /**
  39436. * Define if the Primitive can be subject to intersection test or not (default is true)
  39437. */
  39438. get: function () {
  39439. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsPickable);
  39440. },
  39441. set: function (value) {
  39442. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsPickable, value);
  39443. },
  39444. enumerable: true,
  39445. configurable: true
  39446. });
  39447. Object.defineProperty(Prim2DBase.prototype, "hierarchyDepth", {
  39448. /**
  39449. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  39450. */
  39451. get: function () {
  39452. return this._hierarchyDepth;
  39453. },
  39454. enumerable: true,
  39455. configurable: true
  39456. });
  39457. Object.defineProperty(Prim2DBase.prototype, "renderGroup", {
  39458. /**
  39459. * Retrieve the Group that is responsible to render this primitive
  39460. */
  39461. get: function () {
  39462. return this._renderGroup;
  39463. },
  39464. enumerable: true,
  39465. configurable: true
  39466. });
  39467. Object.defineProperty(Prim2DBase.prototype, "globalTransform", {
  39468. /**
  39469. * Get the global transformation matrix of the primitive
  39470. */
  39471. get: function () {
  39472. return this._globalTransform;
  39473. },
  39474. enumerable: true,
  39475. configurable: true
  39476. });
  39477. /**
  39478. * return the global position of the primitive, relative to its canvas
  39479. */
  39480. Prim2DBase.prototype.getGlobalPosition = function () {
  39481. var v = new BABYLON.Vector2(0, 0);
  39482. this.getGlobalPositionByRef(v);
  39483. return v;
  39484. };
  39485. /**
  39486. * return the global position of the primitive, relative to its canvas
  39487. * @param v the valid Vector2 object where the global position will be stored
  39488. */
  39489. Prim2DBase.prototype.getGlobalPositionByRef = function (v) {
  39490. v.x = this.globalTransform.m[12];
  39491. v.y = this.globalTransform.m[13];
  39492. };
  39493. Object.defineProperty(Prim2DBase.prototype, "invGlobalTransform", {
  39494. /**
  39495. * Get invert of the global transformation matrix of the primitive
  39496. */
  39497. get: function () {
  39498. return this._invGlobalTransform;
  39499. },
  39500. enumerable: true,
  39501. configurable: true
  39502. });
  39503. Object.defineProperty(Prim2DBase.prototype, "localTransform", {
  39504. /**
  39505. * Get the local transformation of the primitive
  39506. */
  39507. get: function () {
  39508. this._updateLocalTransform();
  39509. return this._localTransform;
  39510. },
  39511. enumerable: true,
  39512. configurable: true
  39513. });
  39514. Object.defineProperty(Prim2DBase.prototype, "boundingInfo", {
  39515. /**
  39516. * Get the boundingInfo associated to the primitive and its children.
  39517. * The value is supposed to be always up to date
  39518. */
  39519. get: function () {
  39520. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  39521. if (this.owner) {
  39522. this.owner.boundingInfoRecomputeCounter.addCount(1, false);
  39523. }
  39524. if (this.isSizedByContent) {
  39525. this._boundingInfo.clear();
  39526. }
  39527. else {
  39528. this._boundingInfo.copyFrom(this.levelBoundingInfo);
  39529. }
  39530. var bi = this._boundingInfo;
  39531. var tps = new BABYLON.BoundingInfo2D();
  39532. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39533. var curChild = _a[_i];
  39534. curChild.boundingInfo.transformToRef(curChild.localTransform, tps);
  39535. bi.unionToRef(tps, bi);
  39536. }
  39537. this._boundingInfo.maxToRef(Prim2DBase._bMax);
  39538. 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);
  39539. this._clearFlags(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty);
  39540. }
  39541. return this._boundingInfo;
  39542. },
  39543. enumerable: true,
  39544. configurable: true
  39545. });
  39546. Object.defineProperty(Prim2DBase.prototype, "isSizeAuto", {
  39547. /**
  39548. * Determine if the size is automatically computed or fixed because manually specified.
  39549. * Use the actualSize property to get the final/real size of the primitive
  39550. * @returns true if the size is automatically computed, false if it were manually specified.
  39551. */
  39552. get: function () {
  39553. return this._size == null;
  39554. },
  39555. enumerable: true,
  39556. configurable: true
  39557. });
  39558. Object.defineProperty(Prim2DBase.prototype, "isSizedByContent", {
  39559. /**
  39560. * Return true if this prim has an auto size which is set by the children's global bounding box
  39561. */
  39562. get: function () {
  39563. return (this._size == null) && (this._children.length > 0);
  39564. },
  39565. enumerable: true,
  39566. configurable: true
  39567. });
  39568. Object.defineProperty(Prim2DBase.prototype, "isPositionAuto", {
  39569. /**
  39570. * Determine if the position is automatically computed or fixed because manually specified.
  39571. * Use the actualPosition property to get the final/real position of the primitive
  39572. * @returns true if the position is automatically computed, false if it were manually specified.
  39573. */
  39574. get: function () {
  39575. return this._position == null;
  39576. },
  39577. enumerable: true,
  39578. configurable: true
  39579. });
  39580. Object.defineProperty(Prim2DBase.prototype, "pointerEventObservable", {
  39581. /**
  39582. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  39583. */
  39584. get: function () {
  39585. return this._pointerEventObservable;
  39586. },
  39587. enumerable: true,
  39588. configurable: true
  39589. });
  39590. Object.defineProperty(Prim2DBase.prototype, "zActualOrderChangedObservable", {
  39591. get: function () {
  39592. if (!this._actualZOrderChangedObservable) {
  39593. this._actualZOrderChangedObservable = new BABYLON.Observable();
  39594. }
  39595. return this._actualZOrderChangedObservable;
  39596. },
  39597. enumerable: true,
  39598. configurable: true
  39599. });
  39600. Prim2DBase.prototype.findById = function (id) {
  39601. if (this._id === id) {
  39602. return this;
  39603. }
  39604. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39605. var child = _a[_i];
  39606. var r = child.findById(id);
  39607. if (r != null) {
  39608. return r;
  39609. }
  39610. }
  39611. };
  39612. Prim2DBase.prototype.onZOrderChanged = function () {
  39613. };
  39614. Prim2DBase.prototype.levelIntersect = function (intersectInfo) {
  39615. return false;
  39616. };
  39617. /**
  39618. * Capture all the Events of the given PointerId for this primitive.
  39619. * Don't forget to call releasePointerEventsCapture when done.
  39620. * @param pointerId the Id of the pointer to capture the events from.
  39621. */
  39622. Prim2DBase.prototype.setPointerEventCapture = function (pointerId) {
  39623. return this.owner._setPointerCapture(pointerId, this);
  39624. };
  39625. /**
  39626. * Release a captured pointer made with setPointerEventCapture.
  39627. * @param pointerId the Id of the pointer to release the capture from.
  39628. */
  39629. Prim2DBase.prototype.releasePointerEventsCapture = function (pointerId) {
  39630. return this.owner._releasePointerCapture(pointerId, this);
  39631. };
  39632. /**
  39633. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  39634. * @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.
  39635. */
  39636. Prim2DBase.prototype.intersect = function (intersectInfo) {
  39637. if (!intersectInfo) {
  39638. return false;
  39639. }
  39640. // If this is null it means this method is call for the first level, initialize stuffs
  39641. var firstLevel = !intersectInfo._globalPickPosition;
  39642. if (firstLevel) {
  39643. // 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).
  39644. intersectInfo._globalPickPosition = BABYLON.Vector2.Zero();
  39645. BABYLON.Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  39646. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  39647. intersectInfo.intersectedPrimitives = new Array();
  39648. intersectInfo.topMostIntersectedPrimitive = null;
  39649. }
  39650. if (!intersectInfo.intersectHidden && !this.isVisible) {
  39651. return false;
  39652. }
  39653. // Fast rejection test with boundingInfo
  39654. if (this.isPickable && !this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  39655. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  39656. intersectInfo._exit(firstLevel);
  39657. return false;
  39658. }
  39659. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  39660. var levelIntersectRes = false;
  39661. if (this.isPickable) {
  39662. levelIntersectRes = this.levelIntersect(intersectInfo);
  39663. if (levelIntersectRes) {
  39664. var pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  39665. intersectInfo.intersectedPrimitives.push(pii);
  39666. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.actualZOffset > pii.prim.actualZOffset)) {
  39667. intersectInfo.topMostIntersectedPrimitive = pii;
  39668. }
  39669. // If we must stop at the first intersection, we're done, quit!
  39670. if (intersectInfo.findFirstOnly) {
  39671. intersectInfo._exit(firstLevel);
  39672. return true;
  39673. }
  39674. }
  39675. }
  39676. // Recurse to children if needed
  39677. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  39678. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39679. var curChild = _a[_i];
  39680. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  39681. if (!curChild.isPickable || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  39682. continue;
  39683. }
  39684. // Must compute the localPickLocation for the children level
  39685. BABYLON.Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  39686. // If we got an intersection with the child and we only need to find the first one, quit!
  39687. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  39688. intersectInfo._exit(firstLevel);
  39689. return true;
  39690. }
  39691. }
  39692. }
  39693. intersectInfo._exit(firstLevel);
  39694. return intersectInfo.isIntersected;
  39695. };
  39696. Prim2DBase.prototype.moveChild = function (child, previous) {
  39697. if (child.parent !== this) {
  39698. return false;
  39699. }
  39700. var childIndex = this._children.indexOf(child);
  39701. var prevIndex = previous ? this._children.indexOf(previous) : -1;
  39702. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  39703. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  39704. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, prevIndex + 1);
  39705. }
  39706. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  39707. };
  39708. Prim2DBase.prototype.addChild = function (child) {
  39709. child._parent = this;
  39710. this._boundingBoxDirty();
  39711. var flat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  39712. if (flat) {
  39713. child._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  39714. child._setZOrder(this._zOrder, true);
  39715. child._zMax = this._zOrder;
  39716. }
  39717. else {
  39718. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  39719. }
  39720. var length = this._children.push(child);
  39721. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, length - 1);
  39722. };
  39723. /**
  39724. * Dispose the primitive, remove it from its parent.
  39725. */
  39726. Prim2DBase.prototype.dispose = function () {
  39727. if (!_super.prototype.dispose.call(this)) {
  39728. return false;
  39729. }
  39730. if (this._actionManager) {
  39731. this._actionManager.dispose();
  39732. this._actionManager = null;
  39733. }
  39734. // If there's a parent, remove this object from its parent list
  39735. if (this._parent) {
  39736. var i = this._parent._children.indexOf(this);
  39737. if (i !== undefined) {
  39738. this._parent._children.splice(i, 1);
  39739. }
  39740. this._parent = null;
  39741. }
  39742. // Recurse dispose to children
  39743. if (this._children) {
  39744. while (this._children.length > 0) {
  39745. this._children[this._children.length - 1].dispose();
  39746. }
  39747. }
  39748. return true;
  39749. };
  39750. Prim2DBase.prototype.onPrimBecomesDirty = function () {
  39751. if (this._renderGroup) {
  39752. this._renderGroup._addPrimToDirtyList(this);
  39753. }
  39754. };
  39755. Prim2DBase.prototype._needPrepare = function () {
  39756. return this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagModelDirty) || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
  39757. };
  39758. Prim2DBase.prototype._prepareRender = function (context) {
  39759. this._prepareRenderPre(context);
  39760. this._prepareRenderPost(context);
  39761. };
  39762. Prim2DBase.prototype._prepareRenderPre = function (context) {
  39763. };
  39764. Prim2DBase.prototype._prepareRenderPost = function (context) {
  39765. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  39766. if (this instanceof BABYLON.Group2D) {
  39767. var self = this;
  39768. if (self.isRenderableGroup) {
  39769. return;
  39770. }
  39771. }
  39772. // Check if we need to recurse the prepare to children primitives
  39773. // - must have children
  39774. // - the global transform of this level have changed, or
  39775. // - the visible state of primitive has changed
  39776. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  39777. this.checkPropertiesDirty(Prim2DBase.isVisibleProperty.flagId))) {
  39778. this._children.forEach(function (c) {
  39779. // As usual stop the recursion if we meet a renderable group
  39780. if (!(c instanceof BABYLON.Group2D && c.isRenderableGroup)) {
  39781. c._prepareRender(context);
  39782. }
  39783. });
  39784. }
  39785. // Finally reset the dirty flags as we've processed everything
  39786. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  39787. this._instanceDirtyFlags = 0;
  39788. };
  39789. Prim2DBase.prototype._canvasPreInit = function (settings) {
  39790. };
  39791. Prim2DBase.CheckParent = function (parent) {
  39792. //if (!Prim2DBase._isCanvasInit && !parent) {
  39793. // 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)");
  39794. //}
  39795. };
  39796. Prim2DBase.prototype.updateCachedStatesOf = function (list, recurse) {
  39797. for (var _i = 0, list_1 = list; _i < list_1.length; _i++) {
  39798. var cur = list_1[_i];
  39799. cur.updateCachedStates(recurse);
  39800. }
  39801. };
  39802. Prim2DBase.prototype._parentLayoutDirty = function () {
  39803. if (!this._parent || this._parent.isDisposed) {
  39804. return;
  39805. }
  39806. this._parent._setLayoutDirty();
  39807. };
  39808. Prim2DBase.prototype._setLayoutDirty = function () {
  39809. if (!this.isDirty) {
  39810. this.onPrimBecomesDirty();
  39811. }
  39812. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  39813. };
  39814. Prim2DBase.prototype._checkPositionChange = function () {
  39815. if (this.parent && this.parent.layoutEngine.isChildPositionAllowed === false) {
  39816. console.log("Can't manually set the position of " + this.id + ", the Layout Engine of its parent doesn't allow it");
  39817. return false;
  39818. }
  39819. return true;
  39820. };
  39821. Prim2DBase.prototype._positioningDirty = function () {
  39822. if (!this.isDirty) {
  39823. this.onPrimBecomesDirty();
  39824. }
  39825. this._setFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  39826. };
  39827. Prim2DBase.prototype._spreadActualOpacityChanged = function () {
  39828. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39829. var child = _a[_i];
  39830. child._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  39831. child._spreadActualOpacityChanged();
  39832. }
  39833. };
  39834. Prim2DBase.prototype._changeLayoutEngine = function (engine) {
  39835. this._layoutEngine = engine;
  39836. };
  39837. Prim2DBase.prototype._updateLocalTransform = function () {
  39838. var tflags = Prim2DBase.actualPositionProperty.flagId | Prim2DBase.rotationProperty.flagId | Prim2DBase.scaleProperty.flagId | Prim2DBase.originProperty.flagId;
  39839. if (this.checkPropertiesDirty(tflags)) {
  39840. if (this.owner) {
  39841. this.owner.addupdateLocalTransformCounter(1);
  39842. }
  39843. var rot = BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), this._rotation);
  39844. var local;
  39845. var pos = this.position;
  39846. if (this._origin.x === 0 && this._origin.y === 0) {
  39847. local = BABYLON.Matrix.Compose(new BABYLON.Vector3(this._scale, this._scale, 1), rot, new BABYLON.Vector3(pos.x, pos.y, 0));
  39848. this._localTransform = local;
  39849. }
  39850. else {
  39851. // -Origin offset
  39852. var as = this.actualSize;
  39853. BABYLON.Matrix.TranslationToRef((-as.width * this._origin.x), (-as.height * this._origin.y), 0, Prim2DBase._t0);
  39854. // -Origin * rotation
  39855. rot.toRotationMatrix(Prim2DBase._t1);
  39856. Prim2DBase._t0.multiplyToRef(Prim2DBase._t1, Prim2DBase._t2);
  39857. // -Origin * rotation * scale
  39858. BABYLON.Matrix.ScalingToRef(this._scale, this._scale, 1, Prim2DBase._t0);
  39859. Prim2DBase._t2.multiplyToRef(Prim2DBase._t0, Prim2DBase._t1);
  39860. // -Origin * rotation * scale * (Origin + Position)
  39861. BABYLON.Matrix.TranslationToRef((as.width * this._origin.x) + pos.x, (as.height * this._origin.y) + pos.y, 0, Prim2DBase._t2);
  39862. Prim2DBase._t1.multiplyToRef(Prim2DBase._t2, this._localTransform);
  39863. }
  39864. this.clearPropertiesDirty(tflags);
  39865. return true;
  39866. }
  39867. return false;
  39868. };
  39869. Prim2DBase.prototype.updateCachedStates = function (recurse) {
  39870. if (this.isDisposed) {
  39871. return;
  39872. }
  39873. this.owner.addCachedGroupRenderCounter(1);
  39874. // Check if the parent is synced
  39875. if (this._parent && ((this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || this._parent._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagLayoutDirty | BABYLON.SmartPropertyPrim.flagPositioningDirty | BABYLON.SmartPropertyPrim.flagZOrderDirty))) {
  39876. this._parent.updateCachedStates(false);
  39877. }
  39878. // Update Z-Order if needed
  39879. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  39880. this._updateZOrder();
  39881. }
  39882. // Update actualSize only if there' not positioning to recompute and the size changed
  39883. // Otherwise positioning will take care of it.
  39884. var sizeDirty = this.checkPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  39885. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty) && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) && sizeDirty) {
  39886. var size = this.size;
  39887. if (size) {
  39888. if (this.size.width != null) {
  39889. this.actualSize.width = this.size.width;
  39890. }
  39891. if (this.size.height != null) {
  39892. this.actualSize.height = this.size.height;
  39893. }
  39894. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  39895. }
  39896. }
  39897. // Check for layout update
  39898. var positioningDirty = this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  39899. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  39900. this.owner.addUpdateLayoutCounter(1);
  39901. this._layoutEngine.updateLayout(this);
  39902. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  39903. }
  39904. var positioningComputed = positioningDirty && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  39905. var autoContentChanged = false;
  39906. if (this.isSizeAuto) {
  39907. if (!this._lastAutoSizeArea) {
  39908. autoContentChanged = this.size !== null;
  39909. }
  39910. else {
  39911. autoContentChanged = (!this._lastAutoSizeArea.equals(this.size));
  39912. }
  39913. }
  39914. // Check for positioning update
  39915. if (!positioningComputed && (autoContentChanged || sizeDirty || this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) || (this._parent && !this._parent.contentArea.equals(this._parentContentArea)))) {
  39916. this._updatePositioning();
  39917. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  39918. if (sizeDirty) {
  39919. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  39920. }
  39921. positioningComputed = true;
  39922. }
  39923. if (positioningComputed && this._parent) {
  39924. this._parentContentArea.copyFrom(this._parent.contentArea);
  39925. }
  39926. // Check if we must update this prim
  39927. if (this === this.owner || this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  39928. this.owner.addUpdateGlobalTransformCounter(1);
  39929. var curVisibleState = this.isVisible;
  39930. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  39931. // Detect a change of visibility
  39932. this._changeFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged, curVisibleState !== this.isVisible);
  39933. // Get/compute the localTransform
  39934. var localDirty = this._updateLocalTransform();
  39935. var parentPaddingChanged = false;
  39936. var parentPaddingOffset = Prim2DBase._v0;
  39937. if (this._parent) {
  39938. parentPaddingOffset = this._parent._paddingOffset;
  39939. parentPaddingChanged = !parentPaddingOffset.equals(this._parentPaddingOffset);
  39940. }
  39941. // Check if there are changes in the parent that will force us to update the global matrix
  39942. var parentDirty = (this._parent != null) ? (this._parent._globalTransformStep !== this._parentTransformStep) : false;
  39943. // Check if we have to update the globalTransform
  39944. if (!this._globalTransform || localDirty || parentDirty || parentPaddingChanged) {
  39945. var globalTransform = this._parent ? this._parent._globalTransform : null;
  39946. var localTransform = void 0;
  39947. Prim2DBase._transMtx.copyFrom(this._localTransform);
  39948. Prim2DBase._transMtx.m[12] += this._layoutAreaPos.x + this._marginOffset.x + parentPaddingOffset.x;
  39949. Prim2DBase._transMtx.m[13] += this._layoutAreaPos.y + this._marginOffset.y + parentPaddingOffset.y;
  39950. localTransform = Prim2DBase._transMtx;
  39951. this._globalTransform = this._parent ? localTransform.multiply(globalTransform) : localTransform.clone();
  39952. this._invGlobalTransform = BABYLON.Matrix.Invert(this._globalTransform);
  39953. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  39954. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  39955. }
  39956. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  39957. }
  39958. if (recurse) {
  39959. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39960. var child = _a[_i];
  39961. // Stop the recursion if we meet a renderable group
  39962. child.updateCachedStates(!(child instanceof BABYLON.Group2D && child.isRenderableGroup));
  39963. }
  39964. }
  39965. };
  39966. Prim2DBase.prototype._updatePositioning = function () {
  39967. if (this.owner) {
  39968. this.owner.addUpdatePositioningCounter(1);
  39969. }
  39970. // From this point we assume that the primitive layoutArea is computed and up to date.
  39971. // We know have to :
  39972. // 1. Determine the PaddingArea and the ActualPosition based on the margin/marginAlignment properties, which will also set the size property of the primitive
  39973. // 2. Determine the contentArea based on the padding property.
  39974. // 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
  39975. if (!this._hasMargin && (this.actualSize.width == null || this.actualSize.height == null)) {
  39976. if (this.actualSize.width == null) {
  39977. this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  39978. }
  39979. if (this.actualSize.height == null) {
  39980. this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  39981. }
  39982. }
  39983. // Apply margin
  39984. if (this._hasMargin) {
  39985. this.margin.computeWithAlignment(this.layoutArea, this.size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  39986. this.actualSize = Prim2DBase._size.clone();
  39987. }
  39988. var isSizeAuto = this.isSizeAuto;
  39989. if (this._hasPadding) {
  39990. // Two cases from here: the size of the Primitive is Auto, its content can't be shrink, so me resize the primitive itself
  39991. if (isSizeAuto) {
  39992. var content = this.size.clone();
  39993. this._getActualSizeFromContentToRef(content, Prim2DBase._icArea);
  39994. this.padding.enlarge(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  39995. this._contentArea.copyFrom(content);
  39996. this.actualSize = Prim2DBase._size.clone();
  39997. // Changing the padding has resize the prim, which forces us to recompute margin again
  39998. if (this._hasMargin) {
  39999. this.margin.computeWithAlignment(this.layoutArea, Prim2DBase._size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  40000. }
  40001. }
  40002. else {
  40003. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  40004. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  40005. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  40006. this.padding.compute(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  40007. this._paddingOffset.x += Prim2DBase._icPos.x;
  40008. this._paddingOffset.y += Prim2DBase._icPos.y;
  40009. this._contentArea.copyFrom(Prim2DBase._size);
  40010. }
  40011. }
  40012. else {
  40013. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  40014. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  40015. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  40016. this._paddingOffset.copyFrom(Prim2DBase._icPos);
  40017. this._contentArea.copyFrom(Prim2DBase._icArea);
  40018. }
  40019. var aPos = new BABYLON.Vector2(this._layoutAreaPos.x + this._marginOffset.x, this._layoutAreaPos.y + this._marginOffset.y);
  40020. this.actualPosition = aPos;
  40021. if (isSizeAuto) {
  40022. this._lastAutoSizeArea = this.size;
  40023. }
  40024. };
  40025. Object.defineProperty(Prim2DBase.prototype, "contentArea", {
  40026. /**
  40027. * Get the content are of this primitive, this area is computed using the padding property and also possibly the primitive type itself.
  40028. * Children of this primitive will be positioned relative to the bottom/left corner of this area.
  40029. */
  40030. get: function () {
  40031. // Check for positioning update
  40032. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  40033. this._updatePositioning();
  40034. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  40035. }
  40036. return this._contentArea;
  40037. },
  40038. enumerable: true,
  40039. configurable: true
  40040. });
  40041. Prim2DBase.prototype._patchHierarchy = function (owner) {
  40042. this._owner = owner;
  40043. // The only place we initialize the _renderGroup is this method, if it's set, we already been there, no need to execute more
  40044. if (this._renderGroup != null) {
  40045. return;
  40046. }
  40047. if (this instanceof BABYLON.Group2D) {
  40048. var group = this;
  40049. group.detectGroupStates();
  40050. if (group._trackedNode && !group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  40051. group.owner._registerTrackedNode(this);
  40052. }
  40053. }
  40054. if (this._parent) {
  40055. this._renderGroup = this.parent.traverseUp(function (p) { return p instanceof BABYLON.Group2D && p.isRenderableGroup; });
  40056. this._parentLayoutDirty();
  40057. }
  40058. // Make sure the prim is in the dirtyList if it should be
  40059. if (this._renderGroup && this.isDirty) {
  40060. var list = this._renderGroup._renderableData._primDirtyList;
  40061. var i = list.indexOf(this);
  40062. if (i === -1) {
  40063. list.push(this);
  40064. }
  40065. }
  40066. // Recurse
  40067. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40068. var child = _a[_i];
  40069. child._hierarchyDepth = this._hierarchyDepth + 1;
  40070. child._patchHierarchy(owner);
  40071. }
  40072. };
  40073. Prim2DBase.prototype._updateZOrder = function () {
  40074. var prevLinPos = this._primLinearPosition;
  40075. var startI = 0;
  40076. var startZ = this._zOrder;
  40077. // 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
  40078. var childrenCount = this._children.length;
  40079. if (this._firstZDirtyIndex > 0) {
  40080. if ((this._firstZDirtyIndex - 1) < childrenCount) {
  40081. var prevPrim = this._children[this._firstZDirtyIndex - 1];
  40082. prevLinPos = prevPrim._primLinearPosition;
  40083. startI = this._firstZDirtyIndex - 1;
  40084. startZ = prevPrim._zOrder;
  40085. }
  40086. }
  40087. var startPos = prevLinPos;
  40088. // Update the linear position of the primitive from the first one to the last inside this primitive, compute the total number of prim traversed
  40089. Prim2DBase._totalCount = 0;
  40090. for (var i = startI; i < childrenCount; i++) {
  40091. var child = this._children[i];
  40092. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  40093. }
  40094. // Compute the new Z-Order for all the primitives
  40095. // Add 20% to the current total count to reserve space for future insertions, except if we're rebuilding due to a zMinDelta reached
  40096. var zDelta = (this._zMax - startZ) / (Prim2DBase._totalCount * (Prim2DBase._zRebuildReentrency ? 1 : 1.2));
  40097. // 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.
  40098. if (zDelta < BABYLON.Canvas2D._zMinDelta) {
  40099. // 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...
  40100. if (Prim2DBase._zRebuildReentrency) {
  40101. var p = this._parent;
  40102. if (p == null) {
  40103. // 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...)
  40104. console.log("Can't compute Z-Order for " + this.id + "'s children, zDelta is too small, Z-Order is now in an unstable state");
  40105. Prim2DBase._zRebuildReentrency = false;
  40106. return;
  40107. }
  40108. p._firstZDirtyIndex = 0;
  40109. return p._updateZOrder();
  40110. }
  40111. Prim2DBase._zRebuildReentrency = true;
  40112. this._firstZDirtyIndex = 0;
  40113. this._updateZOrder();
  40114. Prim2DBase._zRebuildReentrency = false;
  40115. }
  40116. for (var i = startI; i < childrenCount; i++) {
  40117. var child = this._children[i];
  40118. child._updatePrimitiveZOrder(startPos, startZ, zDelta);
  40119. }
  40120. // Notify the Observers that we found during the Z change (we do it after to avoid any kind of re-entrance)
  40121. for (var _i = 0, _a = Prim2DBase._zOrderChangedNotifList; _i < _a.length; _i++) {
  40122. var p = _a[_i];
  40123. p._actualZOrderChangedObservable.notifyObservers(p.actualZOffset);
  40124. }
  40125. Prim2DBase._zOrderChangedNotifList.splice(0);
  40126. this._firstZDirtyIndex = Prim2DBase._bigInt;
  40127. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  40128. };
  40129. Prim2DBase.prototype._updatePrimitiveLinearPosition = function (prevLinPos) {
  40130. if (this.isManualZOrder) {
  40131. return prevLinPos;
  40132. }
  40133. this._primLinearPosition = ++prevLinPos;
  40134. Prim2DBase._totalCount++;
  40135. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  40136. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  40137. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40138. var child = _a[_i];
  40139. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  40140. }
  40141. }
  40142. return prevLinPos;
  40143. };
  40144. Prim2DBase.prototype._updatePrimitiveZOrder = function (startPos, startZ, deltaZ) {
  40145. if (this.isManualZOrder) {
  40146. return null;
  40147. }
  40148. var newZ = startZ + ((this._primLinearPosition - startPos) * deltaZ);
  40149. var isFlat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  40150. this._setZOrder(newZ, false);
  40151. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  40152. this._firstZDirtyIndex = Prim2DBase._bigInt;
  40153. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  40154. }
  40155. var curZ = newZ;
  40156. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  40157. if (isFlat) {
  40158. if (this._children.length > 0) {
  40159. //let childrenZOrder = startZ + ((this._children[0]._primLinearPosition - startPos) * deltaZ);
  40160. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40161. var child = _a[_i];
  40162. child._updatePrimitiveFlatZOrder(this._zOrder);
  40163. }
  40164. }
  40165. }
  40166. else {
  40167. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  40168. var child = _c[_b];
  40169. var r = child._updatePrimitiveZOrder(startPos, startZ, deltaZ);
  40170. if (r != null) {
  40171. curZ = r;
  40172. }
  40173. }
  40174. }
  40175. this._zMax = isFlat ? newZ : (curZ + deltaZ);
  40176. return curZ;
  40177. };
  40178. Prim2DBase.prototype._updatePrimitiveFlatZOrder = function (newZ) {
  40179. if (this.isManualZOrder) {
  40180. return;
  40181. }
  40182. this._setZOrder(newZ, false);
  40183. this._zMax = newZ;
  40184. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  40185. this._firstZDirtyIndex = Prim2DBase._bigInt;
  40186. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  40187. }
  40188. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40189. var child = _a[_i];
  40190. child._updatePrimitiveFlatZOrder(newZ);
  40191. }
  40192. };
  40193. Prim2DBase.prototype._setZOrder = function (newZ, directEmit) {
  40194. if (newZ !== this._zOrder) {
  40195. this._zOrder = newZ;
  40196. if (!this.isDirty) {
  40197. this.onPrimBecomesDirty();
  40198. }
  40199. this.onZOrderChanged();
  40200. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  40201. if (directEmit) {
  40202. this._actualZOrderChangedObservable.notifyObservers(newZ);
  40203. }
  40204. else {
  40205. Prim2DBase._zOrderChangedNotifList.push(this);
  40206. }
  40207. }
  40208. }
  40209. };
  40210. Prim2DBase.prototype._updateRenderMode = function () {
  40211. };
  40212. /**
  40213. * This method is used to alter the contentArea of the Primitive before margin is applied.
  40214. * 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.
  40215. * @param primSize the current size of the primitive
  40216. * @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!
  40217. * @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!
  40218. */
  40219. Prim2DBase.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  40220. initialContentArea.copyFrom(primSize);
  40221. initialContentPosition.x = initialContentPosition.y = 0;
  40222. };
  40223. /**
  40224. * This method is used to calculate the new size of the primitive based on the content which must stay the same
  40225. * Check the Rectangle2D implementation for a concrete application.
  40226. * @param primSize the current size of the primitive
  40227. * @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!
  40228. */
  40229. Prim2DBase.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  40230. newPrimSize.copyFrom(primSize);
  40231. };
  40232. Prim2DBase.PRIM2DBASE_PROPCOUNT = 15;
  40233. Prim2DBase._bigInt = Math.pow(2, 30);
  40234. Prim2DBase._nullPosition = BABYLON.Vector2.Zero();
  40235. Prim2DBase.boundinbBoxReentrency = false;
  40236. Prim2DBase.nullSize = BABYLON.Size.Zero();
  40237. Prim2DBase._bMax = BABYLON.Vector2.Zero();
  40238. Prim2DBase._isCanvasInit = false;
  40239. Prim2DBase._t0 = new BABYLON.Matrix();
  40240. Prim2DBase._t1 = new BABYLON.Matrix();
  40241. Prim2DBase._t2 = new BABYLON.Matrix();
  40242. Prim2DBase._v0 = BABYLON.Vector2.Zero(); // Must stay with the value 0,0
  40243. Prim2DBase._transMtx = BABYLON.Matrix.Zero();
  40244. Prim2DBase._icPos = BABYLON.Vector2.Zero();
  40245. Prim2DBase._icArea = BABYLON.Size.Zero();
  40246. Prim2DBase._size = BABYLON.Size.Zero();
  40247. Prim2DBase._zOrderChangedNotifList = new Array();
  40248. Prim2DBase._zRebuildReentrency = false;
  40249. Prim2DBase._totalCount = 0;
  40250. __decorate([
  40251. BABYLON.instanceLevelProperty(1, function (pi) { return Prim2DBase.actualPositionProperty = pi; }, false, false, true)
  40252. ], Prim2DBase.prototype, "actualPosition", null);
  40253. __decorate([
  40254. BABYLON.dynamicLevelProperty(2, function (pi) { return Prim2DBase.positionProperty = pi; }, false, false, true)
  40255. ], Prim2DBase.prototype, "position", null);
  40256. __decorate([
  40257. BABYLON.dynamicLevelProperty(3, function (pi) { return Prim2DBase.sizeProperty = pi; }, false, true)
  40258. ], Prim2DBase.prototype, "size", null);
  40259. __decorate([
  40260. BABYLON.instanceLevelProperty(4, function (pi) { return Prim2DBase.rotationProperty = pi; }, false, true)
  40261. ], Prim2DBase.prototype, "rotation", null);
  40262. __decorate([
  40263. BABYLON.instanceLevelProperty(5, function (pi) { return Prim2DBase.scaleProperty = pi; }, false, true)
  40264. ], Prim2DBase.prototype, "scale", null);
  40265. __decorate([
  40266. BABYLON.dynamicLevelProperty(6, function (pi) { return Prim2DBase.originProperty = pi; }, false, true)
  40267. ], Prim2DBase.prototype, "origin", null);
  40268. __decorate([
  40269. BABYLON.dynamicLevelProperty(7, function (pi) { return Prim2DBase.levelVisibleProperty = pi; })
  40270. ], Prim2DBase.prototype, "levelVisible", null);
  40271. __decorate([
  40272. BABYLON.instanceLevelProperty(8, function (pi) { return Prim2DBase.isVisibleProperty = pi; })
  40273. ], Prim2DBase.prototype, "isVisible", null);
  40274. __decorate([
  40275. BABYLON.instanceLevelProperty(9, function (pi) { return Prim2DBase.zOrderProperty = pi; })
  40276. ], Prim2DBase.prototype, "zOrder", null);
  40277. __decorate([
  40278. BABYLON.dynamicLevelProperty(10, function (pi) { return Prim2DBase.marginProperty = pi; })
  40279. ], Prim2DBase.prototype, "margin", null);
  40280. __decorate([
  40281. BABYLON.dynamicLevelProperty(11, function (pi) { return Prim2DBase.paddingProperty = pi; })
  40282. ], Prim2DBase.prototype, "padding", null);
  40283. __decorate([
  40284. BABYLON.dynamicLevelProperty(12, function (pi) { return Prim2DBase.marginAlignmentProperty = pi; })
  40285. ], Prim2DBase.prototype, "marginAlignment", null);
  40286. __decorate([
  40287. BABYLON.instanceLevelProperty(13, function (pi) { return Prim2DBase.opacityProperty = pi; })
  40288. ], Prim2DBase.prototype, "opacity", null);
  40289. Prim2DBase = __decorate([
  40290. BABYLON.className("Prim2DBase")
  40291. ], Prim2DBase);
  40292. return Prim2DBase;
  40293. }(BABYLON.SmartPropertyPrim));
  40294. BABYLON.Prim2DBase = Prim2DBase;
  40295. })(BABYLON || (BABYLON = {}));
  40296. var BABYLON;
  40297. (function (BABYLON) {
  40298. var GroupInstanceInfo = (function () {
  40299. function GroupInstanceInfo(owner, mrc, partCount) {
  40300. this._partCount = partCount;
  40301. this.owner = owner;
  40302. this.modelRenderCache = mrc;
  40303. this.modelRenderCache.addRef();
  40304. this.partIndexFromId = new BABYLON.StringDictionary();
  40305. this._usedShaderCategories = new Array(partCount);
  40306. this._strides = new Array(partCount);
  40307. this._opaqueData = null;
  40308. this._alphaTestData = null;
  40309. this._transparentData = null;
  40310. this.opaqueDirty = this.alphaTestDirty = this.transparentDirty = this.transparentOrderDirty = false;
  40311. }
  40312. GroupInstanceInfo.prototype.dispose = function () {
  40313. if (this._isDisposed) {
  40314. return false;
  40315. }
  40316. if (this.modelRenderCache) {
  40317. this.modelRenderCache.dispose();
  40318. }
  40319. var engine = this.owner.owner.engine;
  40320. if (this.opaqueData) {
  40321. this.opaqueData.forEach(function (d) { return d.dispose(engine); });
  40322. this.opaqueData = null;
  40323. }
  40324. this.partIndexFromId = null;
  40325. this._isDisposed = true;
  40326. return true;
  40327. };
  40328. Object.defineProperty(GroupInstanceInfo.prototype, "hasOpaqueData", {
  40329. get: function () {
  40330. return this._opaqueData != null;
  40331. },
  40332. enumerable: true,
  40333. configurable: true
  40334. });
  40335. Object.defineProperty(GroupInstanceInfo.prototype, "hasAlphaTestData", {
  40336. get: function () {
  40337. return this._alphaTestData != null;
  40338. },
  40339. enumerable: true,
  40340. configurable: true
  40341. });
  40342. Object.defineProperty(GroupInstanceInfo.prototype, "hasTransparentData", {
  40343. get: function () {
  40344. return this._transparentData != null;
  40345. },
  40346. enumerable: true,
  40347. configurable: true
  40348. });
  40349. Object.defineProperty(GroupInstanceInfo.prototype, "opaqueData", {
  40350. get: function () {
  40351. if (!this._opaqueData) {
  40352. this._opaqueData = new Array(this._partCount);
  40353. for (var i = 0; i < this._partCount; i++) {
  40354. this._opaqueData[i] = new GroupInfoPartData(this._strides[i]);
  40355. }
  40356. }
  40357. return this._opaqueData;
  40358. },
  40359. enumerable: true,
  40360. configurable: true
  40361. });
  40362. Object.defineProperty(GroupInstanceInfo.prototype, "alphaTestData", {
  40363. get: function () {
  40364. if (!this._alphaTestData) {
  40365. this._alphaTestData = new Array(this._partCount);
  40366. for (var i = 0; i < this._partCount; i++) {
  40367. this._alphaTestData[i] = new GroupInfoPartData(this._strides[i]);
  40368. }
  40369. }
  40370. return this._alphaTestData;
  40371. },
  40372. enumerable: true,
  40373. configurable: true
  40374. });
  40375. Object.defineProperty(GroupInstanceInfo.prototype, "transparentData", {
  40376. get: function () {
  40377. if (!this._transparentData) {
  40378. this._transparentData = new Array(this._partCount);
  40379. for (var i = 0; i < this._partCount; i++) {
  40380. var zoff = this.modelRenderCache._partData[i]._zBiasOffset;
  40381. this._transparentData[i] = new TransparentGroupInfoPartData(this._strides[i], zoff);
  40382. }
  40383. }
  40384. return this._transparentData;
  40385. },
  40386. enumerable: true,
  40387. configurable: true
  40388. });
  40389. GroupInstanceInfo.prototype.sortTransparentData = function () {
  40390. if (!this.transparentOrderDirty) {
  40391. return;
  40392. }
  40393. for (var i = 0; i < this._transparentData.length; i++) {
  40394. var td = this._transparentData[i];
  40395. td._partData.sort();
  40396. }
  40397. this.transparentOrderDirty = false;
  40398. };
  40399. Object.defineProperty(GroupInstanceInfo.prototype, "usedShaderCategories", {
  40400. get: function () {
  40401. return this._usedShaderCategories;
  40402. },
  40403. enumerable: true,
  40404. configurable: true
  40405. });
  40406. Object.defineProperty(GroupInstanceInfo.prototype, "strides", {
  40407. get: function () {
  40408. return this._strides;
  40409. },
  40410. enumerable: true,
  40411. configurable: true
  40412. });
  40413. return GroupInstanceInfo;
  40414. }());
  40415. BABYLON.GroupInstanceInfo = GroupInstanceInfo;
  40416. var TransparentSegment = (function () {
  40417. function TransparentSegment() {
  40418. this.groupInsanceInfo = null;
  40419. this.startZ = 0;
  40420. this.endZ = 0;
  40421. this.startDataIndex = 0;
  40422. this.endDataIndex = 0;
  40423. this.partBuffers = null;
  40424. }
  40425. TransparentSegment.prototype.dispose = function (engine) {
  40426. if (this.partBuffers) {
  40427. this.partBuffers.forEach(function (b) { return engine._releaseBuffer(b); });
  40428. this.partBuffers.splice(0);
  40429. this.partBuffers = null;
  40430. }
  40431. };
  40432. return TransparentSegment;
  40433. }());
  40434. BABYLON.TransparentSegment = TransparentSegment;
  40435. var GroupInfoPartData = (function () {
  40436. function GroupInfoPartData(stride) {
  40437. this._partData = null;
  40438. this._partBuffer = null;
  40439. this._partBufferSize = 0;
  40440. this._partData = new BABYLON.DynamicFloatArray(stride / 4, 50);
  40441. this._isDisposed = false;
  40442. }
  40443. GroupInfoPartData.prototype.dispose = function (engine) {
  40444. if (this._isDisposed) {
  40445. return false;
  40446. }
  40447. if (this._partBuffer) {
  40448. engine._releaseBuffer(this._partBuffer);
  40449. this._partBuffer = null;
  40450. }
  40451. this._partData = null;
  40452. this._isDisposed = true;
  40453. };
  40454. return GroupInfoPartData;
  40455. }());
  40456. BABYLON.GroupInfoPartData = GroupInfoPartData;
  40457. var TransparentGroupInfoPartData = (function (_super) {
  40458. __extends(TransparentGroupInfoPartData, _super);
  40459. function TransparentGroupInfoPartData(stride, zoff) {
  40460. _super.call(this, stride);
  40461. this._partData.compareValueOffset = zoff;
  40462. this._partData.sortingAscending = false;
  40463. }
  40464. return TransparentGroupInfoPartData;
  40465. }(GroupInfoPartData));
  40466. BABYLON.TransparentGroupInfoPartData = TransparentGroupInfoPartData;
  40467. var ModelRenderCache = (function () {
  40468. function ModelRenderCache(engine, modelKey) {
  40469. this._engine = engine;
  40470. this._modelKey = modelKey;
  40471. this._nextKey = 1;
  40472. this._refCounter = 1;
  40473. this._instancesData = new BABYLON.StringDictionary();
  40474. this._partData = null;
  40475. }
  40476. ModelRenderCache.prototype.dispose = function () {
  40477. if (--this._refCounter !== 0) {
  40478. return false;
  40479. }
  40480. // Remove the Model Render Cache from the global dictionary
  40481. var edata = this._engine.getExternalData("__BJSCANVAS2D__");
  40482. if (edata) {
  40483. edata.DisposeModelRenderCache(this);
  40484. }
  40485. return true;
  40486. };
  40487. Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
  40488. get: function () {
  40489. return this._refCounter <= 0;
  40490. },
  40491. enumerable: true,
  40492. configurable: true
  40493. });
  40494. ModelRenderCache.prototype.addRef = function () {
  40495. return ++this._refCounter;
  40496. };
  40497. Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
  40498. get: function () {
  40499. return this._modelKey;
  40500. },
  40501. enumerable: true,
  40502. configurable: true
  40503. });
  40504. /**
  40505. * Render the model instances
  40506. * @param instanceInfo
  40507. * @param context
  40508. * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
  40509. */
  40510. ModelRenderCache.prototype.render = function (instanceInfo, context) {
  40511. return true;
  40512. };
  40513. ModelRenderCache.prototype.addInstanceDataParts = function (data) {
  40514. var key = this._nextKey.toString();
  40515. if (!this._instancesData.add(key, data)) {
  40516. throw Error("Key: " + key + " is already allocated");
  40517. }
  40518. ++this._nextKey;
  40519. return key;
  40520. };
  40521. ModelRenderCache.prototype.removeInstanceData = function (key) {
  40522. this._instancesData.remove(key);
  40523. };
  40524. ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
  40525. for (var i = 0; i < this._partData.length; i++) {
  40526. if (this._partData[i]._partId === partId) {
  40527. return i;
  40528. }
  40529. }
  40530. return null;
  40531. };
  40532. ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
  40533. var i = this.getPartIndexFromId(partId);
  40534. if (i === null) {
  40535. return null;
  40536. }
  40537. var ci = this._partsClassInfo[i];
  40538. var categories = this._partData[i]._partUsedCategories;
  40539. var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
  40540. return res;
  40541. };
  40542. ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
  40543. var pd = this._partData[partIndex];
  40544. var offset = (pd._partDataStride / 4) * elementCount;
  40545. var pci = this._partsClassInfo[partIndex];
  40546. var self = this;
  40547. pci.fullContent.forEach(function (k, v) {
  40548. if (!v.category || pd._partUsedCategories.indexOf(v.category) !== -1) {
  40549. switch (v.dataType) {
  40550. case 4 /* float */:
  40551. {
  40552. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  40553. effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
  40554. break;
  40555. }
  40556. case 0 /* Vector2 */:
  40557. {
  40558. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  40559. ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
  40560. ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
  40561. effect.setVector2(v.attributeName, ModelRenderCache.v2);
  40562. break;
  40563. }
  40564. case 5 /* Color3 */:
  40565. case 1 /* Vector3 */:
  40566. {
  40567. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  40568. ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
  40569. ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
  40570. ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
  40571. effect.setVector3(v.attributeName, ModelRenderCache.v3);
  40572. break;
  40573. }
  40574. case 6 /* Color4 */:
  40575. case 2 /* Vector4 */:
  40576. {
  40577. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  40578. ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
  40579. ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
  40580. ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
  40581. ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
  40582. effect.setVector4(v.attributeName, ModelRenderCache.v4);
  40583. break;
  40584. }
  40585. default:
  40586. }
  40587. }
  40588. });
  40589. };
  40590. //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
  40591. // let i = this.getPartIndexFromId(partId);
  40592. // if (i === null) {
  40593. // return null;
  40594. // }
  40595. // let pci = this._partsClassInfo[i];
  40596. // pci.fullContent.forEach((k, v) => {
  40597. // if (uniforms.indexOf(v.attributeName) !== -1) {
  40598. // v.uniformLocation = effect.getUniform(v.attributeName);
  40599. // }
  40600. // });
  40601. //}
  40602. ModelRenderCache.v2 = BABYLON.Vector2.Zero();
  40603. ModelRenderCache.v3 = BABYLON.Vector3.Zero();
  40604. ModelRenderCache.v4 = BABYLON.Vector4.Zero();
  40605. return ModelRenderCache;
  40606. }());
  40607. BABYLON.ModelRenderCache = ModelRenderCache;
  40608. var ModelRenderCachePartData = (function () {
  40609. function ModelRenderCachePartData() {
  40610. }
  40611. return ModelRenderCachePartData;
  40612. }());
  40613. BABYLON.ModelRenderCachePartData = ModelRenderCachePartData;
  40614. })(BABYLON || (BABYLON = {}));
  40615. var BABYLON;
  40616. (function (BABYLON) {
  40617. var InstanceClassInfo = (function () {
  40618. function InstanceClassInfo(base) {
  40619. this._baseInfo = base;
  40620. this._nextOffset = new BABYLON.StringDictionary();
  40621. this._attributes = new Array();
  40622. }
  40623. InstanceClassInfo.prototype.mapProperty = function (propInfo, push) {
  40624. var curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
  40625. propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
  40626. //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
  40627. this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
  40628. if (push) {
  40629. this._attributes.push(propInfo);
  40630. }
  40631. };
  40632. InstanceClassInfo.prototype.getInstancingAttributeInfos = function (effect, categories) {
  40633. var catInline = ";" + categories.join(";") + ";";
  40634. var res = new Array();
  40635. var curInfo = this;
  40636. while (curInfo) {
  40637. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  40638. var attrib = _a[_i];
  40639. // 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
  40640. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  40641. var index = effect.getAttributeLocationByName(attrib.attributeName);
  40642. var iai = new BABYLON.InstancingAttributeInfo();
  40643. iai.index = index;
  40644. 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)
  40645. iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
  40646. iai.attributeName = attrib.attributeName;
  40647. res.push(iai);
  40648. }
  40649. }
  40650. curInfo = curInfo._baseInfo;
  40651. }
  40652. return res;
  40653. };
  40654. InstanceClassInfo.prototype.getShaderAttributes = function (categories) {
  40655. var res = new Array();
  40656. var curInfo = this;
  40657. while (curInfo) {
  40658. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  40659. var attrib = _a[_i];
  40660. // 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
  40661. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  40662. res.push(attrib.attributeName);
  40663. }
  40664. }
  40665. curInfo = curInfo._baseInfo;
  40666. }
  40667. return res;
  40668. };
  40669. InstanceClassInfo.prototype._getBaseOffset = function (categories) {
  40670. var curOffset = 0;
  40671. var curBase = this._baseInfo;
  40672. while (curBase) {
  40673. curOffset += curBase._nextOffset.getOrAdd(categories, 0);
  40674. curBase = curBase._baseInfo;
  40675. }
  40676. return curOffset;
  40677. };
  40678. return InstanceClassInfo;
  40679. }());
  40680. BABYLON.InstanceClassInfo = InstanceClassInfo;
  40681. var InstancePropInfo = (function () {
  40682. function InstancePropInfo() {
  40683. this.instanceOffset = new BABYLON.StringDictionary();
  40684. }
  40685. InstancePropInfo.prototype.setSize = function (val) {
  40686. if (val instanceof BABYLON.Vector2) {
  40687. this.size = 8;
  40688. this.dataType = 0 /* Vector2 */;
  40689. return;
  40690. }
  40691. if (val instanceof BABYLON.Vector3) {
  40692. this.size = 12;
  40693. this.dataType = 1 /* Vector3 */;
  40694. return;
  40695. }
  40696. if (val instanceof BABYLON.Vector4) {
  40697. this.size = 16;
  40698. this.dataType = 2 /* Vector4 */;
  40699. return;
  40700. }
  40701. if (val instanceof BABYLON.Matrix) {
  40702. throw new Error("Matrix type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
  40703. }
  40704. if (typeof (val) === "number") {
  40705. this.size = 4;
  40706. this.dataType = 4 /* float */;
  40707. return;
  40708. }
  40709. if (val instanceof BABYLON.Color3) {
  40710. this.size = 12;
  40711. this.dataType = 5 /* Color3 */;
  40712. return;
  40713. }
  40714. if (val instanceof BABYLON.Color4) {
  40715. this.size = 16;
  40716. this.dataType = 6 /* Color4 */;
  40717. return;
  40718. }
  40719. if (val instanceof BABYLON.Size) {
  40720. this.size = 8;
  40721. this.dataType = 7 /* Size */;
  40722. return;
  40723. }
  40724. return;
  40725. };
  40726. InstancePropInfo.prototype.writeData = function (array, offset, val) {
  40727. switch (this.dataType) {
  40728. case 0 /* Vector2 */:
  40729. {
  40730. var v = val;
  40731. array[offset + 0] = v.x;
  40732. array[offset + 1] = v.y;
  40733. break;
  40734. }
  40735. case 1 /* Vector3 */:
  40736. {
  40737. var v = val;
  40738. array[offset + 0] = v.x;
  40739. array[offset + 1] = v.y;
  40740. array[offset + 2] = v.z;
  40741. break;
  40742. }
  40743. case 2 /* Vector4 */:
  40744. {
  40745. var v = val;
  40746. array[offset + 0] = v.x;
  40747. array[offset + 1] = v.y;
  40748. array[offset + 2] = v.z;
  40749. array[offset + 3] = v.w;
  40750. break;
  40751. }
  40752. case 5 /* Color3 */:
  40753. {
  40754. var v = val;
  40755. array[offset + 0] = v.r;
  40756. array[offset + 1] = v.g;
  40757. array[offset + 2] = v.b;
  40758. break;
  40759. }
  40760. case 6 /* Color4 */:
  40761. {
  40762. var v = val;
  40763. array[offset + 0] = v.r;
  40764. array[offset + 1] = v.g;
  40765. array[offset + 2] = v.b;
  40766. array[offset + 3] = v.a;
  40767. break;
  40768. }
  40769. case 4 /* float */:
  40770. {
  40771. var v = val;
  40772. array[offset] = v;
  40773. break;
  40774. }
  40775. case 3 /* Matrix */:
  40776. {
  40777. var v = val;
  40778. for (var i = 0; i < 16; i++) {
  40779. array[offset + i] = v.m[i];
  40780. }
  40781. break;
  40782. }
  40783. case 7 /* Size */:
  40784. {
  40785. var s = val;
  40786. array[offset + 0] = s.width;
  40787. array[offset + 1] = s.height;
  40788. break;
  40789. }
  40790. }
  40791. };
  40792. return InstancePropInfo;
  40793. }());
  40794. BABYLON.InstancePropInfo = InstancePropInfo;
  40795. function instanceData(category, shaderAttributeName) {
  40796. return function (target, propName, descriptor) {
  40797. var dic = BABYLON.ClassTreeInfo.getOrRegister(target, function (base) { return new InstanceClassInfo(base); });
  40798. var node = dic.getLevelOf(target);
  40799. var instanceDataName = propName;
  40800. shaderAttributeName = shaderAttributeName || instanceDataName;
  40801. var info = node.levelContent.get(instanceDataName);
  40802. if (info) {
  40803. throw new Error("The ID " + instanceDataName + " is already taken by another instance data");
  40804. }
  40805. info = new InstancePropInfo();
  40806. info.attributeName = shaderAttributeName;
  40807. info.category = category || null;
  40808. if (info.category) {
  40809. info.delimitedCategory = ";" + info.category + ";";
  40810. }
  40811. node.levelContent.add(instanceDataName, info);
  40812. descriptor.get = function () {
  40813. return null;
  40814. };
  40815. descriptor.set = function (val) {
  40816. // Check that we're not trying to set a property that belongs to a category that is not allowed (current)
  40817. // Quit if it's the case, otherwise we could overwrite data somewhere...
  40818. if (info.category && InstanceClassInfo._CurCategories.indexOf(info.delimitedCategory) === -1) {
  40819. return;
  40820. }
  40821. if (!info.size) {
  40822. info.setSize(val);
  40823. node.classContent.mapProperty(info, true);
  40824. }
  40825. else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
  40826. node.classContent.mapProperty(info, false);
  40827. }
  40828. var obj = this;
  40829. if (obj.dataBuffer && obj.dataElements) {
  40830. var offset = obj.dataElements[obj.curElement].offset + info.instanceOffset.get(InstanceClassInfo._CurCategories);
  40831. info.writeData(obj.dataBuffer.buffer, offset, val);
  40832. }
  40833. };
  40834. };
  40835. }
  40836. BABYLON.instanceData = instanceData;
  40837. var InstanceDataBase = (function () {
  40838. function InstanceDataBase(partId, dataElementCount) {
  40839. this.id = partId;
  40840. this.curElement = 0;
  40841. this.dataElementCount = dataElementCount;
  40842. this.renderMode = 0;
  40843. this.arrayLengthChanged = false;
  40844. }
  40845. Object.defineProperty(InstanceDataBase.prototype, "zBias", {
  40846. get: function () {
  40847. return null;
  40848. },
  40849. enumerable: true,
  40850. configurable: true
  40851. });
  40852. Object.defineProperty(InstanceDataBase.prototype, "transformX", {
  40853. get: function () {
  40854. return null;
  40855. },
  40856. enumerable: true,
  40857. configurable: true
  40858. });
  40859. Object.defineProperty(InstanceDataBase.prototype, "transformY", {
  40860. get: function () {
  40861. return null;
  40862. },
  40863. enumerable: true,
  40864. configurable: true
  40865. });
  40866. Object.defineProperty(InstanceDataBase.prototype, "opacity", {
  40867. get: function () {
  40868. return null;
  40869. },
  40870. enumerable: true,
  40871. configurable: true
  40872. });
  40873. InstanceDataBase.prototype.getClassTreeInfo = function () {
  40874. if (!this.typeInfo) {
  40875. this.typeInfo = BABYLON.ClassTreeInfo.get(Object.getPrototypeOf(this));
  40876. }
  40877. return this.typeInfo;
  40878. };
  40879. InstanceDataBase.prototype.allocElements = function () {
  40880. if (!this.dataBuffer) {
  40881. return;
  40882. }
  40883. var res = new Array(this.dataElementCount);
  40884. for (var i = 0; i < this.dataElementCount; i++) {
  40885. res[i] = this.dataBuffer.allocElement();
  40886. }
  40887. this.dataElements = res;
  40888. };
  40889. InstanceDataBase.prototype.freeElements = function () {
  40890. if (!this.dataElements) {
  40891. return;
  40892. }
  40893. for (var _i = 0, _a = this.dataElements; _i < _a.length; _i++) {
  40894. var ei = _a[_i];
  40895. this.dataBuffer.freeElement(ei);
  40896. }
  40897. this.dataElements = null;
  40898. };
  40899. Object.defineProperty(InstanceDataBase.prototype, "dataElementCount", {
  40900. get: function () {
  40901. return this._dataElementCount;
  40902. },
  40903. set: function (value) {
  40904. if (value === this._dataElementCount) {
  40905. return;
  40906. }
  40907. this.arrayLengthChanged = true;
  40908. this.freeElements();
  40909. this._dataElementCount = value;
  40910. this.allocElements();
  40911. },
  40912. enumerable: true,
  40913. configurable: true
  40914. });
  40915. __decorate([
  40916. instanceData()
  40917. ], InstanceDataBase.prototype, "zBias", null);
  40918. __decorate([
  40919. instanceData()
  40920. ], InstanceDataBase.prototype, "transformX", null);
  40921. __decorate([
  40922. instanceData()
  40923. ], InstanceDataBase.prototype, "transformY", null);
  40924. __decorate([
  40925. instanceData()
  40926. ], InstanceDataBase.prototype, "opacity", null);
  40927. return InstanceDataBase;
  40928. }());
  40929. BABYLON.InstanceDataBase = InstanceDataBase;
  40930. var RenderablePrim2D = (function (_super) {
  40931. __extends(RenderablePrim2D, _super);
  40932. function RenderablePrim2D(settings) {
  40933. _super.call(this, settings);
  40934. this._isTransparent = false;
  40935. this._isAlphaTest = false;
  40936. this._transparentPrimitiveInfo = null;
  40937. }
  40938. Object.defineProperty(RenderablePrim2D.prototype, "isAlphaTest", {
  40939. get: function () {
  40940. return this._isAlphaTest;
  40941. },
  40942. set: function (value) {
  40943. if (this._isAlphaTest === value) {
  40944. return;
  40945. }
  40946. this._isAlphaTest = value;
  40947. this._updateRenderMode();
  40948. },
  40949. enumerable: true,
  40950. configurable: true
  40951. });
  40952. Object.defineProperty(RenderablePrim2D.prototype, "isTransparent", {
  40953. get: function () {
  40954. return this._isTransparent || (this._opacity < 1);
  40955. },
  40956. set: function (value) {
  40957. if (this._isTransparent === value) {
  40958. return;
  40959. }
  40960. this._isTransparent = value;
  40961. this._updateRenderMode();
  40962. },
  40963. enumerable: true,
  40964. configurable: true
  40965. });
  40966. Object.defineProperty(RenderablePrim2D.prototype, "renderMode", {
  40967. get: function () {
  40968. return this._renderMode;
  40969. },
  40970. enumerable: true,
  40971. configurable: true
  40972. });
  40973. /**
  40974. * Dispose the primitive and its resources, remove it from its parent
  40975. */
  40976. RenderablePrim2D.prototype.dispose = function () {
  40977. if (!_super.prototype.dispose.call(this)) {
  40978. return false;
  40979. }
  40980. if (this._transparentPrimitiveInfo) {
  40981. this.renderGroup._renderableData.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  40982. this._transparentPrimitiveInfo = null;
  40983. }
  40984. if (this._modelRenderInstanceID) {
  40985. this._modelRenderCache.removeInstanceData(this._modelRenderInstanceID);
  40986. this._modelRenderInstanceID = null;
  40987. }
  40988. if (this._modelRenderCache) {
  40989. this._modelRenderCache.dispose();
  40990. this._modelRenderCache = null;
  40991. }
  40992. if (this._instanceDataParts) {
  40993. this._instanceDataParts.forEach(function (p) {
  40994. p.freeElements();
  40995. });
  40996. this._instanceDataParts = null;
  40997. }
  40998. return true;
  40999. };
  41000. RenderablePrim2D.prototype._prepareRenderPre = function (context) {
  41001. _super.prototype._prepareRenderPre.call(this, context);
  41002. // If the model changed and we have already an instance, we must remove this instance from the obsolete model
  41003. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty) && this._modelRenderInstanceID) {
  41004. this._modelRenderCache.removeInstanceData(this._modelRenderInstanceID);
  41005. this._modelRenderInstanceID = null;
  41006. }
  41007. // Need to create the model?
  41008. var setupModelRenderCache = false;
  41009. if (!this._modelRenderCache || this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty)) {
  41010. setupModelRenderCache = this._createModelRenderCache();
  41011. }
  41012. var gii = null;
  41013. var newInstance = false;
  41014. // Need to create the instance data parts?
  41015. if (!this._modelRenderInstanceID) {
  41016. // Yes, flag it for later, more processing will have to be done
  41017. newInstance = true;
  41018. gii = this._createModelDataParts();
  41019. }
  41020. // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
  41021. if (setupModelRenderCache) {
  41022. this.setupModelRenderCache(this._modelRenderCache);
  41023. }
  41024. // 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.
  41025. // 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.
  41026. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged) || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep)) {
  41027. this._updateInstanceDataParts(gii);
  41028. }
  41029. };
  41030. RenderablePrim2D.prototype._createModelRenderCache = function () {
  41031. var _this = this;
  41032. var setupModelRenderCache = false;
  41033. if (this._modelRenderCache) {
  41034. this._modelRenderCache.dispose();
  41035. }
  41036. this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, function (key) {
  41037. var mrc = _this.createModelRenderCache(key);
  41038. setupModelRenderCache = true;
  41039. return mrc;
  41040. });
  41041. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  41042. // if this is still false it means the MRC already exists, so we add a reference to it
  41043. if (!setupModelRenderCache) {
  41044. this._modelRenderCache.addRef();
  41045. }
  41046. return setupModelRenderCache;
  41047. };
  41048. RenderablePrim2D.prototype._createModelDataParts = function () {
  41049. var _this = this;
  41050. // Create the instance data parts of the primitive and store them
  41051. var parts = this.createInstanceDataParts();
  41052. this._instanceDataParts = parts;
  41053. // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
  41054. if (!this._modelRenderCache._partData) {
  41055. this._setupModelRenderCache(parts);
  41056. }
  41057. // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
  41058. // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
  41059. // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
  41060. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, function (k) {
  41061. var res = new BABYLON.GroupInstanceInfo(_this.renderGroup, _this._modelRenderCache, _this._modelRenderCache._partData.length);
  41062. for (var j = 0; j < _this._modelRenderCache._partData.length; j++) {
  41063. var part = _this._instanceDataParts[j];
  41064. res.partIndexFromId.add(part.id.toString(), j);
  41065. res.usedShaderCategories[j] = ";" + _this.getUsedShaderCategories(part).join(";") + ";";
  41066. res.strides[j] = _this._modelRenderCache._partData[j]._partDataStride;
  41067. }
  41068. return res;
  41069. });
  41070. // Get the GroupInfoDataPart corresponding to the render category of the part
  41071. var rm = 0;
  41072. var gipd = null;
  41073. if (this.isTransparent) {
  41074. gipd = gii.transparentData;
  41075. rm = BABYLON.Render2DContext.RenderModeTransparent;
  41076. }
  41077. else if (this.isAlphaTest) {
  41078. gipd = gii.alphaTestData;
  41079. rm = BABYLON.Render2DContext.RenderModeAlphaTest;
  41080. }
  41081. else {
  41082. gipd = gii.opaqueData;
  41083. rm = BABYLON.Render2DContext.RenderModeOpaque;
  41084. }
  41085. // For each instance data part of the primitive, allocate the instanced element it needs for render
  41086. for (var i = 0; i < parts.length; i++) {
  41087. var part = parts[i];
  41088. part.dataBuffer = gipd[i]._partData;
  41089. part.allocElements();
  41090. part.renderMode = rm;
  41091. }
  41092. // Add the instance data parts in the ModelRenderCache they belong, track them by storing their ID in the primitive in case we need to change the model later on, so we'll have to release the allocated instance data parts because they won't fit anymore
  41093. this._modelRenderInstanceID = this._modelRenderCache.addInstanceDataParts(this._instanceDataParts);
  41094. return gii;
  41095. };
  41096. RenderablePrim2D.prototype._setupModelRenderCache = function (parts) {
  41097. var ctiArray = new Array();
  41098. this._modelRenderCache._partData = new Array();
  41099. for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
  41100. var dataPart = parts_1[_i];
  41101. var pd = new BABYLON.ModelRenderCachePartData();
  41102. this._modelRenderCache._partData.push(pd);
  41103. var cat = this.getUsedShaderCategories(dataPart);
  41104. var cti = dataPart.getClassTreeInfo();
  41105. // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
  41106. var curVisible = this.isVisible;
  41107. this.isVisible = true;
  41108. // 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.
  41109. //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
  41110. var joinCat = ";" + cat.join(";") + ";";
  41111. pd._partJoinedUsedCategories = joinCat;
  41112. InstanceClassInfo._CurCategories = joinCat;
  41113. var obj = this.beforeRefreshForLayoutConstruction(dataPart);
  41114. if (!this.refreshInstanceDataPart(dataPart)) {
  41115. console.log("Layout construction for " + BABYLON.Tools.getClassName(this._instanceDataParts[0]) + " failed because refresh returned false");
  41116. }
  41117. this.afterRefreshForLayoutConstruction(dataPart, obj);
  41118. this.isVisible = curVisible;
  41119. var size = 0;
  41120. cti.fullContent.forEach(function (k, v) {
  41121. if (!v.category || cat.indexOf(v.category) !== -1) {
  41122. if (v.attributeName === "zBias") {
  41123. pd._zBiasOffset = v.instanceOffset.get(joinCat);
  41124. }
  41125. if (!v.size) {
  41126. console.log("ERROR: Couldn't detect the size of the Property " + v.attributeName + " from type " + BABYLON.Tools.getClassName(cti.type) + ". Property is ignored.");
  41127. }
  41128. else {
  41129. size += v.size;
  41130. }
  41131. }
  41132. });
  41133. pd._partDataStride = size;
  41134. pd._partUsedCategories = cat;
  41135. pd._partId = dataPart.id;
  41136. ctiArray.push(cti);
  41137. }
  41138. this._modelRenderCache._partsClassInfo = ctiArray;
  41139. };
  41140. RenderablePrim2D.prototype.onZOrderChanged = function () {
  41141. if (this.isTransparent && this._transparentPrimitiveInfo) {
  41142. this.renderGroup._renderableData.transparentPrimitiveZChanged(this._transparentPrimitiveInfo);
  41143. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
  41144. // Flag the transparentData dirty has will have to sort it again
  41145. gii.transparentOrderDirty = true;
  41146. }
  41147. };
  41148. RenderablePrim2D.prototype._updateInstanceDataParts = function (gii) {
  41149. // Fetch the GroupInstanceInfo if we don't already have it
  41150. var rd = this.renderGroup._renderableData;
  41151. if (!gii) {
  41152. gii = rd._renderGroupInstancesInfo.get(this.modelKey);
  41153. }
  41154. var isTransparent = this.isTransparent;
  41155. var isAlphaTest = this.isAlphaTest;
  41156. var wereTransparent = false;
  41157. // Check a render mode change
  41158. var rmChanged = false;
  41159. if (this._instanceDataParts.length > 0) {
  41160. var firstPart = this._instanceDataParts[0];
  41161. var partRM = firstPart.renderMode;
  41162. var curRM = this.renderMode;
  41163. if (partRM !== curRM) {
  41164. wereTransparent = partRM === BABYLON.Render2DContext.RenderModeTransparent;
  41165. rmChanged = true;
  41166. var gipd = void 0;
  41167. switch (curRM) {
  41168. case BABYLON.Render2DContext.RenderModeTransparent:
  41169. gipd = gii.transparentData;
  41170. break;
  41171. case BABYLON.Render2DContext.RenderModeAlphaTest:
  41172. gipd = gii.alphaTestData;
  41173. break;
  41174. default:
  41175. gipd = gii.opaqueData;
  41176. }
  41177. for (var i = 0; i < this._instanceDataParts.length; i++) {
  41178. var part = this._instanceDataParts[i];
  41179. part.freeElements();
  41180. part.dataBuffer = gipd[i]._partData;
  41181. part.renderMode = curRM;
  41182. }
  41183. }
  41184. }
  41185. // Handle changes related to ZOffset
  41186. var visChanged = this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged);
  41187. if (isTransparent || wereTransparent) {
  41188. // Handle visibility change, which is also triggered when the primitive just got created
  41189. if (visChanged || rmChanged) {
  41190. if (this.isVisible && !wereTransparent) {
  41191. if (!this._transparentPrimitiveInfo) {
  41192. // Add the primitive to the list of transparent ones in the group that render is
  41193. this._transparentPrimitiveInfo = rd.addNewTransparentPrimitiveInfo(this, gii);
  41194. }
  41195. }
  41196. else {
  41197. if (this._transparentPrimitiveInfo) {
  41198. rd.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  41199. this._transparentPrimitiveInfo = null;
  41200. }
  41201. }
  41202. gii.transparentOrderDirty = true;
  41203. }
  41204. }
  41205. var rebuildTrans = false;
  41206. // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
  41207. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  41208. var part = _a[_i];
  41209. var justAllocated = false;
  41210. // Check if we need to allocate data elements (hidden prim which becomes visible again)
  41211. if (visChanged || !part.dataElements || rmChanged) {
  41212. part.allocElements();
  41213. justAllocated = true;
  41214. }
  41215. InstanceClassInfo._CurCategories = gii.usedShaderCategories[gii.partIndexFromId.get(part.id.toString())];
  41216. // Will return false if the instance should not be rendered (not visible or other any reasons)
  41217. part.arrayLengthChanged = false;
  41218. if (!this.refreshInstanceDataPart(part)) {
  41219. // Free the data element
  41220. if (part.dataElements) {
  41221. part.freeElements();
  41222. }
  41223. }
  41224. rebuildTrans = rebuildTrans || part.arrayLengthChanged || justAllocated;
  41225. }
  41226. this._instanceDirtyFlags = 0;
  41227. // Make the appropriate data dirty
  41228. if (isTransparent) {
  41229. gii.transparentDirty = true;
  41230. if (rebuildTrans) {
  41231. rd._transparentListChanged = true;
  41232. }
  41233. }
  41234. else if (isAlphaTest) {
  41235. gii.alphaTestDirty = true;
  41236. }
  41237. else {
  41238. gii.opaqueDirty = true;
  41239. }
  41240. this._clearFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged); // Reset the flag as we've handled the case
  41241. };
  41242. RenderablePrim2D.prototype._updateTransparentSegmentIndices = function (ts) {
  41243. var minOff = BABYLON.Prim2DBase._bigInt;
  41244. var maxOff = 0;
  41245. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  41246. var part = _a[_i];
  41247. if (part && part.dataElements) {
  41248. part.dataBuffer.pack();
  41249. for (var _b = 0, _c = part.dataElements; _b < _c.length; _b++) {
  41250. var el = _c[_b];
  41251. minOff = Math.min(minOff, el.offset);
  41252. maxOff = Math.max(maxOff, el.offset);
  41253. }
  41254. ts.startDataIndex = minOff / part.dataBuffer.stride;
  41255. ts.endDataIndex = (maxOff / part.dataBuffer.stride) + 1; // +1 for exclusive
  41256. }
  41257. }
  41258. };
  41259. RenderablePrim2D.prototype._getPrimitiveLastIndex = function () {
  41260. var maxOff = 0;
  41261. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  41262. var part = _a[_i];
  41263. if (part) {
  41264. for (var _b = 0, _c = part.dataElements; _b < _c.length; _b++) {
  41265. var el = _c[_b];
  41266. maxOff = Math.max(maxOff, el.offset);
  41267. }
  41268. return (maxOff / part.dataBuffer.stride) + 1; // +1 for exclusive
  41269. }
  41270. }
  41271. };
  41272. // This internal method is mainly used for transparency processing
  41273. RenderablePrim2D.prototype._getNextPrimZOrder = function () {
  41274. var length = this._instanceDataParts.length;
  41275. for (var i = 0; i < length; i++) {
  41276. var part = this._instanceDataParts[i];
  41277. if (part) {
  41278. var stride = part.dataBuffer.stride;
  41279. var lastElementOffset = part.dataElements[part.dataElements.length - 1].offset;
  41280. // check if it's the last in the DFA
  41281. if (part.dataBuffer.totalElementCount * stride <= lastElementOffset) {
  41282. return null;
  41283. }
  41284. // Return the Z of the next primitive that lies in the DFA
  41285. return part.dataBuffer[lastElementOffset + stride + this.modelRenderCache._partData[i]._zBiasOffset];
  41286. }
  41287. }
  41288. return null;
  41289. };
  41290. // This internal method is mainly used for transparency processing
  41291. RenderablePrim2D.prototype._getPrevPrimZOrder = function () {
  41292. var length = this._instanceDataParts.length;
  41293. for (var i = 0; i < length; i++) {
  41294. var part = this._instanceDataParts[i];
  41295. if (part) {
  41296. var stride = part.dataBuffer.stride;
  41297. var firstElementOffset = part.dataElements[0].offset;
  41298. // check if it's the first in the DFA
  41299. if (firstElementOffset === 0) {
  41300. return null;
  41301. }
  41302. // Return the Z of the previous primitive that lies in the DFA
  41303. return part.dataBuffer[firstElementOffset - stride + this.modelRenderCache._partData[i]._zBiasOffset];
  41304. }
  41305. }
  41306. return null;
  41307. };
  41308. /**
  41309. * Transform a given point using the Primitive's origin setting.
  41310. * This method requires the Primitive's actualSize to be accurate
  41311. * @param p the point to transform
  41312. * @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.
  41313. * @param res an allocated Vector2 that will receive the transformed content
  41314. */
  41315. RenderablePrim2D.prototype.transformPointWithOriginByRef = function (p, originOffset, res) {
  41316. var actualSize = this.actualSize;
  41317. res.x = p.x - ((this.origin.x + (originOffset ? originOffset.x : 0)) * actualSize.width);
  41318. res.y = p.y - ((this.origin.y + (originOffset ? originOffset.y : 0)) * actualSize.height);
  41319. };
  41320. RenderablePrim2D.prototype.transformPointWithOriginToRef = function (p, originOffset, res) {
  41321. this.transformPointWithOriginByRef(p, originOffset, res);
  41322. return res;
  41323. };
  41324. /**
  41325. * Get the info for a given effect based on the dataPart metadata
  41326. * @param dataPartId partId in part list to get the info
  41327. * @param vertexBufferAttributes vertex buffer attributes to manually add
  41328. * @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
  41329. */
  41330. RenderablePrim2D.prototype.getDataPartEffectInfo = function (dataPartId, vertexBufferAttributes, useInstanced) {
  41331. if (useInstanced === void 0) { useInstanced = null; }
  41332. var dataPart = BABYLON.Tools.first(this._instanceDataParts, function (i) { return i.id === dataPartId; });
  41333. if (!dataPart) {
  41334. return null;
  41335. }
  41336. var instancedArray = this.owner.supportInstancedArray;
  41337. if (useInstanced != null) {
  41338. // Check if the caller ask for Instanced Array and the engine does not support it, return null if it's the case
  41339. if (useInstanced && instancedArray === false) {
  41340. return null;
  41341. }
  41342. // Use the caller's setting
  41343. instancedArray = useInstanced;
  41344. }
  41345. var cti = dataPart.getClassTreeInfo();
  41346. var categories = this.getUsedShaderCategories(dataPart);
  41347. var att = cti.classContent.getShaderAttributes(categories);
  41348. var defines = "";
  41349. categories.forEach(function (c) { defines += "#define " + c + "\n"; });
  41350. if (instancedArray) {
  41351. defines += "#define Instanced\n";
  41352. }
  41353. return { attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes, uniforms: instancedArray ? [] : att, defines: defines };
  41354. };
  41355. Object.defineProperty(RenderablePrim2D.prototype, "modelRenderCache", {
  41356. get: function () {
  41357. return this._modelRenderCache;
  41358. },
  41359. enumerable: true,
  41360. configurable: true
  41361. });
  41362. RenderablePrim2D.prototype.createModelRenderCache = function (modelKey) {
  41363. return null;
  41364. };
  41365. RenderablePrim2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  41366. };
  41367. RenderablePrim2D.prototype.createInstanceDataParts = function () {
  41368. return null;
  41369. };
  41370. RenderablePrim2D.prototype.getUsedShaderCategories = function (dataPart) {
  41371. return [];
  41372. };
  41373. RenderablePrim2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  41374. };
  41375. RenderablePrim2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  41376. };
  41377. RenderablePrim2D.prototype.refreshInstanceDataPart = function (part) {
  41378. if (!this.isVisible) {
  41379. return false;
  41380. }
  41381. part.isVisible = this.isVisible;
  41382. // 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)
  41383. if (part.dataElementCount === 1) {
  41384. part.curElement = 0;
  41385. this.updateInstanceDataPart(part);
  41386. }
  41387. return true;
  41388. };
  41389. /**
  41390. * Update the instanceDataBase level properties of a part
  41391. * @param part the part to update
  41392. * @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).
  41393. */
  41394. RenderablePrim2D.prototype.updateInstanceDataPart = function (part, positionOffset) {
  41395. if (positionOffset === void 0) { positionOffset = null; }
  41396. var t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform);
  41397. var size = this.renderGroup.viewportSize;
  41398. var zBias = this.actualZOffset;
  41399. var offX = 0;
  41400. var offY = 0;
  41401. // If there's an offset, apply the global transformation matrix on it to get a global offset
  41402. if (positionOffset) {
  41403. offX = positionOffset.x * t.m[0] + positionOffset.y * t.m[4];
  41404. offY = positionOffset.x * t.m[1] + positionOffset.y * t.m[5];
  41405. }
  41406. // 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
  41407. // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
  41408. // So for X:
  41409. // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
  41410. // - 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].
  41411. var w = size.width;
  41412. var h = size.height;
  41413. var invZBias = 1 / zBias;
  41414. 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);
  41415. 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);
  41416. part.transformX = tx;
  41417. part.transformY = ty;
  41418. part.opacity = this.actualOpacity;
  41419. // 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)
  41420. part.zBias = new BABYLON.Vector2(zBias, invZBias);
  41421. };
  41422. RenderablePrim2D.prototype._updateRenderMode = function () {
  41423. if (this.isTransparent) {
  41424. this._renderMode = BABYLON.Render2DContext.RenderModeTransparent;
  41425. }
  41426. else if (this.isAlphaTest) {
  41427. this._renderMode = BABYLON.Render2DContext.RenderModeAlphaTest;
  41428. }
  41429. else {
  41430. this._renderMode = BABYLON.Render2DContext.RenderModeOpaque;
  41431. }
  41432. };
  41433. RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  41434. __decorate([
  41435. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 0, function (pi) { return RenderablePrim2D.isAlphaTestProperty = pi; })
  41436. ], RenderablePrim2D.prototype, "isAlphaTest", null);
  41437. __decorate([
  41438. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return RenderablePrim2D.isTransparentProperty = pi; })
  41439. ], RenderablePrim2D.prototype, "isTransparent", null);
  41440. RenderablePrim2D = __decorate([
  41441. BABYLON.className("RenderablePrim2D")
  41442. ], RenderablePrim2D);
  41443. return RenderablePrim2D;
  41444. }(BABYLON.Prim2DBase));
  41445. BABYLON.RenderablePrim2D = RenderablePrim2D;
  41446. })(BABYLON || (BABYLON = {}));
  41447. var BABYLON;
  41448. (function (BABYLON) {
  41449. var Shape2D = (function (_super) {
  41450. __extends(Shape2D, _super);
  41451. function Shape2D(settings) {
  41452. _super.call(this, settings);
  41453. if (!settings) {
  41454. settings = {};
  41455. }
  41456. var borderBrush = null;
  41457. if (settings.border) {
  41458. if (typeof (settings.border) === "string") {
  41459. borderBrush = BABYLON.Canvas2D.GetBrushFromString(settings.border);
  41460. }
  41461. else {
  41462. borderBrush = settings.border;
  41463. }
  41464. }
  41465. var fillBrush = null;
  41466. if (settings.fill) {
  41467. if (typeof (settings.fill) === "string") {
  41468. fillBrush = BABYLON.Canvas2D.GetBrushFromString(settings.fill);
  41469. }
  41470. else {
  41471. fillBrush = settings.fill;
  41472. }
  41473. }
  41474. this.border = borderBrush;
  41475. this.fill = fillBrush;
  41476. this.borderThickness = settings.borderThickness;
  41477. }
  41478. Object.defineProperty(Shape2D.prototype, "border", {
  41479. get: function () {
  41480. return this._border;
  41481. },
  41482. set: function (value) {
  41483. this._border = value;
  41484. this._updateTransparencyStatus();
  41485. },
  41486. enumerable: true,
  41487. configurable: true
  41488. });
  41489. Object.defineProperty(Shape2D.prototype, "fill", {
  41490. /**
  41491. * Get/set the brush to render the Fill part of the Primitive
  41492. */
  41493. get: function () {
  41494. return this._fill;
  41495. },
  41496. set: function (value) {
  41497. this._fill = value;
  41498. this._updateTransparencyStatus();
  41499. },
  41500. enumerable: true,
  41501. configurable: true
  41502. });
  41503. Object.defineProperty(Shape2D.prototype, "borderThickness", {
  41504. get: function () {
  41505. return this._borderThickness;
  41506. },
  41507. set: function (value) {
  41508. this._borderThickness = value;
  41509. },
  41510. enumerable: true,
  41511. configurable: true
  41512. });
  41513. Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
  41514. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  41515. // Fill Part
  41516. if (dataPart.id === Shape2D.SHAPE2D_FILLPARTID) {
  41517. var fill = this.fill;
  41518. if (fill instanceof BABYLON.SolidColorBrush2D) {
  41519. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLSOLID);
  41520. }
  41521. if (fill instanceof BABYLON.GradientColorBrush2D) {
  41522. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT);
  41523. }
  41524. }
  41525. // Border Part
  41526. if (dataPart.id === Shape2D.SHAPE2D_BORDERPARTID) {
  41527. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDER);
  41528. var border = this.border;
  41529. if (border instanceof BABYLON.SolidColorBrush2D) {
  41530. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID);
  41531. }
  41532. if (border instanceof BABYLON.GradientColorBrush2D) {
  41533. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT);
  41534. }
  41535. }
  41536. return cat;
  41537. };
  41538. Shape2D.prototype.refreshInstanceDataPart = function (part) {
  41539. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  41540. return false;
  41541. }
  41542. // Fill Part
  41543. if (part.id === Shape2D.SHAPE2D_FILLPARTID) {
  41544. var d = part;
  41545. if (this.fill) {
  41546. var fill = this.fill;
  41547. if (fill instanceof BABYLON.SolidColorBrush2D) {
  41548. d.fillSolidColor = fill.color;
  41549. }
  41550. else if (fill instanceof BABYLON.GradientColorBrush2D) {
  41551. d.fillGradientColor1 = fill.color1;
  41552. d.fillGradientColor2 = fill.color2;
  41553. 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));
  41554. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  41555. d.fillGradientTY = ty;
  41556. }
  41557. }
  41558. }
  41559. else if (part.id === Shape2D.SHAPE2D_BORDERPARTID) {
  41560. var d = part;
  41561. if (this.border) {
  41562. d.borderThickness = this.borderThickness;
  41563. var border = this.border;
  41564. if (border instanceof BABYLON.SolidColorBrush2D) {
  41565. d.borderSolidColor = border.color;
  41566. }
  41567. else if (border instanceof BABYLON.GradientColorBrush2D) {
  41568. d.borderGradientColor1 = border.color1;
  41569. d.borderGradientColor2 = border.color2;
  41570. 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));
  41571. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  41572. d.borderGradientTY = ty;
  41573. }
  41574. }
  41575. }
  41576. return true;
  41577. };
  41578. Shape2D.prototype._updateTransparencyStatus = function () {
  41579. this.isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent()) || (this.actualOpacity < 1);
  41580. };
  41581. Shape2D.SHAPE2D_BORDERPARTID = 1;
  41582. Shape2D.SHAPE2D_FILLPARTID = 2;
  41583. Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
  41584. Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
  41585. Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
  41586. Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
  41587. Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
  41588. Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
  41589. __decorate([
  41590. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D.borderProperty = pi; }, true)
  41591. ], Shape2D.prototype, "border", null);
  41592. __decorate([
  41593. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D.fillProperty = pi; }, true)
  41594. ], Shape2D.prototype, "fill", null);
  41595. __decorate([
  41596. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D.borderThicknessProperty = pi; })
  41597. ], Shape2D.prototype, "borderThickness", null);
  41598. Shape2D = __decorate([
  41599. BABYLON.className("Shape2D")
  41600. ], Shape2D);
  41601. return Shape2D;
  41602. }(BABYLON.RenderablePrim2D));
  41603. BABYLON.Shape2D = Shape2D;
  41604. var Shape2DInstanceData = (function (_super) {
  41605. __extends(Shape2DInstanceData, _super);
  41606. function Shape2DInstanceData() {
  41607. _super.apply(this, arguments);
  41608. }
  41609. Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
  41610. // FILL ATTRIBUTES
  41611. get: function () {
  41612. return null;
  41613. },
  41614. enumerable: true,
  41615. configurable: true
  41616. });
  41617. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
  41618. get: function () {
  41619. return null;
  41620. },
  41621. enumerable: true,
  41622. configurable: true
  41623. });
  41624. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
  41625. get: function () {
  41626. return null;
  41627. },
  41628. enumerable: true,
  41629. configurable: true
  41630. });
  41631. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
  41632. get: function () {
  41633. return null;
  41634. },
  41635. enumerable: true,
  41636. configurable: true
  41637. });
  41638. Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
  41639. // BORDER ATTRIBUTES
  41640. get: function () {
  41641. return null;
  41642. },
  41643. enumerable: true,
  41644. configurable: true
  41645. });
  41646. Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
  41647. get: function () {
  41648. return null;
  41649. },
  41650. enumerable: true,
  41651. configurable: true
  41652. });
  41653. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
  41654. get: function () {
  41655. return null;
  41656. },
  41657. enumerable: true,
  41658. configurable: true
  41659. });
  41660. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
  41661. get: function () {
  41662. return null;
  41663. },
  41664. enumerable: true,
  41665. configurable: true
  41666. });
  41667. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
  41668. get: function () {
  41669. return null;
  41670. },
  41671. enumerable: true,
  41672. configurable: true
  41673. });
  41674. __decorate([
  41675. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
  41676. ], Shape2DInstanceData.prototype, "fillSolidColor", null);
  41677. __decorate([
  41678. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  41679. ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
  41680. __decorate([
  41681. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  41682. ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
  41683. __decorate([
  41684. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  41685. ], Shape2DInstanceData.prototype, "fillGradientTY", null);
  41686. __decorate([
  41687. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
  41688. ], Shape2DInstanceData.prototype, "borderThickness", null);
  41689. __decorate([
  41690. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
  41691. ], Shape2DInstanceData.prototype, "borderSolidColor", null);
  41692. __decorate([
  41693. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  41694. ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
  41695. __decorate([
  41696. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  41697. ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
  41698. __decorate([
  41699. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  41700. ], Shape2DInstanceData.prototype, "borderGradientTY", null);
  41701. return Shape2DInstanceData;
  41702. }(BABYLON.InstanceDataBase));
  41703. BABYLON.Shape2DInstanceData = Shape2DInstanceData;
  41704. })(BABYLON || (BABYLON = {}));
  41705. var BABYLON;
  41706. (function (BABYLON) {
  41707. var Group2D = (function (_super) {
  41708. __extends(Group2D, _super);
  41709. /**
  41710. * Create an Logical or Renderable Group.
  41711. * @param settings a combination of settings, possible ones are
  41712. * - 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)
  41713. * - children: an array of direct children
  41714. * - id a text identifier, for information purpose
  41715. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  41716. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  41717. * - scale: the initial scale of the primitive. default is 1
  41718. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  41719. * - origin: define the normalized origin point location, default [0.5;0.5]
  41720. * - 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.
  41721. * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY
  41722. * - 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).
  41723. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  41724. * - 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!
  41725. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41726. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41727. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41728. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41729. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  41730. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  41731. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  41732. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  41733. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41734. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41735. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41736. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41737. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  41738. */
  41739. function Group2D(settings) {
  41740. if (settings == null) {
  41741. settings = {};
  41742. }
  41743. if (settings.origin == null) {
  41744. settings.origin = new BABYLON.Vector2(0, 0);
  41745. }
  41746. _super.call(this, settings);
  41747. var size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new BABYLON.Size(settings.width || 0, settings.height || 0)));
  41748. this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode;
  41749. if (this._trackedNode && this.owner) {
  41750. this.owner._registerTrackedNode(this);
  41751. }
  41752. this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior;
  41753. this.size = size;
  41754. this._viewportPosition = BABYLON.Vector2.Zero();
  41755. }
  41756. Group2D._createCachedCanvasGroup = function (owner) {
  41757. var g = new Group2D({ parent: owner, id: "__cachedCanvasGroup__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), size: null, isVisible: true });
  41758. return g;
  41759. };
  41760. Group2D.prototype.applyCachedTexture = function (vertexData, material) {
  41761. this._bindCacheTarget();
  41762. if (vertexData) {
  41763. var uv = vertexData.uvs;
  41764. var nodeuv = this._renderableData._cacheNodeUVs;
  41765. for (var i = 0; i < 4; i++) {
  41766. uv[i * 2 + 0] = nodeuv[i].x;
  41767. uv[i * 2 + 1] = nodeuv[i].y;
  41768. }
  41769. }
  41770. if (material) {
  41771. material.diffuseTexture = this._renderableData._cacheTexture;
  41772. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  41773. }
  41774. this._renderableData._cacheTexture.hasAlpha = true;
  41775. this._unbindCacheTarget();
  41776. };
  41777. Object.defineProperty(Group2D.prototype, "cachedRect", {
  41778. /**
  41779. * Allow you to access the information regarding the cached rectangle of the Group2D into the MapTexture.
  41780. * 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.
  41781. */
  41782. get: function () {
  41783. if (!this._renderableData) {
  41784. return null;
  41785. }
  41786. return this._renderableData._cacheNode;
  41787. },
  41788. enumerable: true,
  41789. configurable: true
  41790. });
  41791. Object.defineProperty(Group2D.prototype, "cachedUVs", {
  41792. /**
  41793. * The UVs into the MapTexture that map the cached group
  41794. */
  41795. get: function () {
  41796. if (!this._renderableData) {
  41797. return null;
  41798. }
  41799. return this._renderableData._cacheNodeUVs;
  41800. },
  41801. enumerable: true,
  41802. configurable: true
  41803. });
  41804. Object.defineProperty(Group2D.prototype, "cachedUVsChanged", {
  41805. get: function () {
  41806. if (!this._renderableData) {
  41807. return null;
  41808. }
  41809. if (!this._renderableData._cacheNodeUVsChangedObservable) {
  41810. this._renderableData._cacheNodeUVsChangedObservable = new BABYLON.Observable();
  41811. }
  41812. return this._renderableData._cacheNodeUVsChangedObservable;
  41813. },
  41814. enumerable: true,
  41815. configurable: true
  41816. });
  41817. Object.defineProperty(Group2D.prototype, "cacheTexture", {
  41818. /**
  41819. * Access the texture that maintains a cached version of the Group2D.
  41820. * This is useful only if you're not using a WorldSpaceNode for your WorldSpace Canvas and therefore need to perform the rendering yourself.
  41821. */
  41822. get: function () {
  41823. if (!this._renderableData) {
  41824. return null;
  41825. }
  41826. return this._renderableData._cacheTexture;
  41827. },
  41828. enumerable: true,
  41829. configurable: true
  41830. });
  41831. /**
  41832. * Call this method to remove this Group and its children from the Canvas
  41833. */
  41834. Group2D.prototype.dispose = function () {
  41835. if (!_super.prototype.dispose.call(this)) {
  41836. return false;
  41837. }
  41838. if (this._trackedNode != null) {
  41839. this.owner._unregisterTrackedNode(this);
  41840. this._trackedNode = null;
  41841. }
  41842. if (this._renderableData) {
  41843. this._renderableData.dispose(this.owner.engine);
  41844. this._renderableData = null;
  41845. }
  41846. return true;
  41847. };
  41848. Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
  41849. /**
  41850. * @returns Returns true if the Group render content, false if it's a logical group only
  41851. */
  41852. get: function () {
  41853. return this._isRenderableGroup;
  41854. },
  41855. enumerable: true,
  41856. configurable: true
  41857. });
  41858. Object.defineProperty(Group2D.prototype, "isCachedGroup", {
  41859. /**
  41860. * @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
  41861. */
  41862. get: function () {
  41863. return this._isCachedGroup;
  41864. },
  41865. enumerable: true,
  41866. configurable: true
  41867. });
  41868. Object.defineProperty(Group2D.prototype, "size", {
  41869. get: function () {
  41870. return this._size;
  41871. },
  41872. /**
  41873. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  41874. * 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.
  41875. */
  41876. set: function (val) {
  41877. this._size = val;
  41878. },
  41879. enumerable: true,
  41880. configurable: true
  41881. });
  41882. Object.defineProperty(Group2D.prototype, "viewportSize", {
  41883. get: function () {
  41884. return this._viewportSize;
  41885. },
  41886. enumerable: true,
  41887. configurable: true
  41888. });
  41889. Object.defineProperty(Group2D.prototype, "actualSize", {
  41890. get: function () {
  41891. // The computed size will be floor on both width and height
  41892. var actualSize;
  41893. // Return the size if set by the user
  41894. if (this._size) {
  41895. actualSize = new BABYLON.Size(Math.ceil(this._size.width), Math.ceil(this._size.height));
  41896. }
  41897. else {
  41898. var m = this.boundingInfo.max();
  41899. actualSize = new BABYLON.Size(Math.ceil(m.x), Math.ceil(m.y));
  41900. }
  41901. // 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)
  41902. if (!actualSize.equals(this._actualSize)) {
  41903. this.onPrimitivePropertyDirty(Group2D.actualSizeProperty.flagId);
  41904. this._actualSize = actualSize;
  41905. this.handleGroupChanged(Group2D.actualSizeProperty);
  41906. }
  41907. return actualSize;
  41908. },
  41909. enumerable: true,
  41910. configurable: true
  41911. });
  41912. Object.defineProperty(Group2D.prototype, "cacheBehavior", {
  41913. /**
  41914. * 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.
  41915. * 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.
  41916. */
  41917. get: function () {
  41918. return this._cacheBehavior;
  41919. },
  41920. enumerable: true,
  41921. configurable: true
  41922. });
  41923. Group2D.prototype._addPrimToDirtyList = function (prim) {
  41924. this._renderableData._primDirtyList.push(prim);
  41925. };
  41926. Group2D.prototype._renderCachedCanvas = function () {
  41927. this.owner._addGroupRenderCount(1);
  41928. this.updateCachedStates(true);
  41929. var context = new BABYLON.PrepareRender2DContext();
  41930. this._prepareGroupRender(context);
  41931. this._groupRender();
  41932. };
  41933. Object.defineProperty(Group2D.prototype, "trackedNode", {
  41934. /**
  41935. * Get/set the Scene's Node that should be tracked, the group's position will follow the projected position of the Node.
  41936. */
  41937. get: function () {
  41938. return this._trackedNode;
  41939. },
  41940. set: function (val) {
  41941. if (val != null) {
  41942. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  41943. this.owner._registerTrackedNode(this);
  41944. }
  41945. this._trackedNode = val;
  41946. }
  41947. else {
  41948. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  41949. this.owner._unregisterTrackedNode(this);
  41950. }
  41951. this._trackedNode = null;
  41952. }
  41953. },
  41954. enumerable: true,
  41955. configurable: true
  41956. });
  41957. Group2D.prototype.levelIntersect = function (intersectInfo) {
  41958. // 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
  41959. return true;
  41960. };
  41961. Group2D.prototype.updateLevelBoundingInfo = function () {
  41962. var size;
  41963. // If the size is set by the user, the boundingInfo is computed from this value
  41964. if (this.size) {
  41965. size = this.size;
  41966. }
  41967. else {
  41968. size = new BABYLON.Size(0, 0);
  41969. }
  41970. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  41971. };
  41972. // Method called only on renderable groups to prepare the rendering
  41973. Group2D.prototype._prepareGroupRender = function (context) {
  41974. var sortedDirtyList = null;
  41975. // Update the Global Transformation and visibility status of the changed primitives
  41976. if ((this._renderableData._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  41977. sortedDirtyList = this._renderableData._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  41978. this.updateCachedStatesOf(sortedDirtyList, true);
  41979. }
  41980. // Setup the size of the rendering viewport
  41981. // 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
  41982. if (!this._isCachedGroup) {
  41983. // Compute the WebGL viewport's location/size
  41984. var t = this._globalTransform.getTranslation();
  41985. var s = this.actualSize.clone();
  41986. var rs = this.owner._renderingSize;
  41987. s.height = Math.min(s.height, rs.height - t.y);
  41988. s.width = Math.min(s.width, rs.width - t.x);
  41989. var x = t.x;
  41990. var y = t.y;
  41991. // 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
  41992. this._viewportPosition.x = x;
  41993. this._viewportPosition.y = y;
  41994. var vw = s.width;
  41995. var vh = s.height;
  41996. if (!this._viewportSize) {
  41997. this._viewportSize = new BABYLON.Size(vw, vh);
  41998. }
  41999. else {
  42000. if (this._viewportSize.width !== vw || this._viewportSize.height !== vh) {
  42001. context.forceRefreshPrimitive = true;
  42002. }
  42003. this._viewportSize.width = vw;
  42004. this._viewportSize.height = vh;
  42005. }
  42006. }
  42007. else {
  42008. var newSize = this.actualSize.clone();
  42009. if (!newSize.equals(this._viewportSize)) {
  42010. context.forceRefreshPrimitive = true;
  42011. }
  42012. this._viewportSize = newSize;
  42013. }
  42014. if ((this._renderableData._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  42015. // If the group is cached, set the dirty flag to true because of the incoming changes
  42016. this._cacheGroupDirty = this._isCachedGroup;
  42017. // If it's a force refresh, prepare all the children
  42018. if (context.forceRefreshPrimitive) {
  42019. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  42020. var p = _a[_i];
  42021. p._prepareRender(context);
  42022. }
  42023. }
  42024. else {
  42025. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  42026. // the hierarchyDepth in order to prepare primitives from top to bottom
  42027. if (!sortedDirtyList) {
  42028. sortedDirtyList = this._renderableData._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  42029. }
  42030. sortedDirtyList.forEach(function (p) {
  42031. // 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.
  42032. // 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.
  42033. if (!p.isDisposed && p._needPrepare()) {
  42034. p._prepareRender(context);
  42035. }
  42036. });
  42037. // Everything is updated, clear the dirty list
  42038. this._renderableData._primDirtyList.forEach(function (p) { return p._resetPropertiesDirty(); });
  42039. this._renderableData._primDirtyList.splice(0);
  42040. }
  42041. }
  42042. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  42043. this._renderableData._childrenRenderableGroups.forEach(function (g) {
  42044. g._prepareGroupRender(context);
  42045. });
  42046. };
  42047. Group2D.prototype._groupRender = function () {
  42048. var _this = this;
  42049. var engine = this.owner.engine;
  42050. var failedCount = 0;
  42051. // First recurse to children render group to render them (in their cache or on screen)
  42052. for (var _i = 0, _a = this._renderableData._childrenRenderableGroups; _i < _a.length; _i++) {
  42053. var childGroup = _a[_i];
  42054. childGroup._groupRender();
  42055. }
  42056. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  42057. if (!this.isCachedGroup || this._cacheGroupDirty) {
  42058. this.owner._addGroupRenderCount(1);
  42059. if (this.isCachedGroup) {
  42060. this._bindCacheTarget();
  42061. }
  42062. else {
  42063. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  42064. }
  42065. var curAlphaTest = engine.getAlphaTesting() === true;
  42066. var curDepthWrite = engine.getDepthWrite() === true;
  42067. // ===================================================================
  42068. // First pass, update the InstancedArray and render Opaque primitives
  42069. // Disable Alpha Testing, Enable Depth Write
  42070. engine.setAlphaTesting(false);
  42071. engine.setDepthWrite(true);
  42072. // For each different model of primitive to render
  42073. var context_1 = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeOpaque);
  42074. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  42075. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  42076. var renderCount = _this._prepareContext(engine, context_1, v);
  42077. // If null is returned, there's no opaque data to render
  42078. if (renderCount === null) {
  42079. return;
  42080. }
  42081. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  42082. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  42083. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  42084. var renderFailed = !v.modelRenderCache.render(v, context_1);
  42085. // Update dirty flag/related
  42086. v.opaqueDirty = renderFailed;
  42087. failedCount += renderFailed ? 1 : 0;
  42088. }
  42089. });
  42090. // =======================================================================
  42091. // Second pass, update the InstancedArray and render AlphaTest primitives
  42092. // Enable Alpha Testing, Enable Depth Write
  42093. engine.setAlphaTesting(true);
  42094. engine.setDepthWrite(true);
  42095. // For each different model of primitive to render
  42096. context_1 = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeAlphaTest);
  42097. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  42098. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  42099. var renderCount = _this._prepareContext(engine, context_1, v);
  42100. // If null is returned, there's no opaque data to render
  42101. if (renderCount === null) {
  42102. return;
  42103. }
  42104. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  42105. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  42106. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  42107. var renderFailed = !v.modelRenderCache.render(v, context_1);
  42108. // Update dirty flag/related
  42109. v.opaqueDirty = renderFailed;
  42110. failedCount += renderFailed ? 1 : 0;
  42111. }
  42112. });
  42113. // =======================================================================
  42114. // Third pass, transparent primitive rendering
  42115. // Enable Alpha Testing, Disable Depth Write
  42116. engine.setAlphaTesting(true);
  42117. engine.setDepthWrite(false);
  42118. // First Check if the transparent List change so we can update the TransparentSegment and PartData (sort if needed)
  42119. if (this._renderableData._transparentListChanged) {
  42120. this._updateTransparentData();
  42121. }
  42122. // From this point on we have up to date data to render, so let's go
  42123. failedCount += this._renderTransparentData();
  42124. // =======================================================================
  42125. // Unbind target/restore viewport setting, clear dirty flag, and quit
  42126. // The group's content is no longer dirty
  42127. this._cacheGroupDirty = failedCount !== 0;
  42128. if (this.isCachedGroup) {
  42129. this._unbindCacheTarget();
  42130. }
  42131. else {
  42132. if (curVP) {
  42133. engine.setViewport(curVP);
  42134. }
  42135. }
  42136. // Restore saved states
  42137. engine.setAlphaTesting(curAlphaTest);
  42138. engine.setDepthWrite(curDepthWrite);
  42139. }
  42140. };
  42141. Group2D.prototype._updateTransparentData = function () {
  42142. this.owner._addUpdateTransparentDataCount(1);
  42143. var rd = this._renderableData;
  42144. // Sort all the primitive from their depth, max (bottom) to min (top)
  42145. rd._transparentPrimitives.sort(function (a, b) { return b._primitive.actualZOffset - a._primitive.actualZOffset; });
  42146. var checkAndAddPrimInSegment = function (seg, tpiI) {
  42147. var tpi = rd._transparentPrimitives[tpiI];
  42148. // Fast rejection: if gii are different
  42149. if (seg.groupInsanceInfo !== tpi._groupInstanceInfo) {
  42150. return false;
  42151. }
  42152. //let tpiZ = tpi._primitive.actualZOffset;
  42153. // We've made it so far, the tpi can be part of the segment, add it
  42154. tpi._transparentSegment = seg;
  42155. seg.endDataIndex = tpi._primitive._getPrimitiveLastIndex();
  42156. return true;
  42157. };
  42158. // Free the existing TransparentSegments
  42159. for (var _i = 0, _a = rd._transparentSegments; _i < _a.length; _i++) {
  42160. var ts = _a[_i];
  42161. ts.dispose(this.owner.engine);
  42162. }
  42163. rd._transparentSegments.splice(0);
  42164. var prevSeg = null;
  42165. for (var tpiI = 0; tpiI < rd._transparentPrimitives.length; tpiI++) {
  42166. var tpi = rd._transparentPrimitives[tpiI];
  42167. // Check if the Data in which the primitive is stored is not sorted properly
  42168. if (tpi._groupInstanceInfo.transparentOrderDirty) {
  42169. tpi._groupInstanceInfo.sortTransparentData();
  42170. }
  42171. // Reset the segment, we have to create/rebuild it
  42172. tpi._transparentSegment = null;
  42173. // If there's a previous valid segment, check if this prim can be part of it
  42174. if (prevSeg) {
  42175. checkAndAddPrimInSegment(prevSeg, tpiI);
  42176. }
  42177. // If we couldn't insert in the adjacent segments, he have to create one
  42178. if (!tpi._transparentSegment) {
  42179. var ts = new BABYLON.TransparentSegment();
  42180. ts.groupInsanceInfo = tpi._groupInstanceInfo;
  42181. var prim = tpi._primitive;
  42182. ts.startZ = prim.actualZOffset;
  42183. prim._updateTransparentSegmentIndices(ts);
  42184. ts.endZ = ts.startZ;
  42185. tpi._transparentSegment = ts;
  42186. rd._transparentSegments.push(ts);
  42187. }
  42188. // Update prevSeg
  42189. prevSeg = tpi._transparentSegment;
  42190. }
  42191. //rd._firstChangedPrim = null;
  42192. rd._transparentListChanged = false;
  42193. };
  42194. Group2D.prototype._renderTransparentData = function () {
  42195. var failedCount = 0;
  42196. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeTransparent);
  42197. var rd = this._renderableData;
  42198. var useInstanced = this.owner.supportInstancedArray;
  42199. var length = rd._transparentSegments.length;
  42200. for (var i = 0; i < length; i++) {
  42201. context.instancedBuffers = null;
  42202. var ts = rd._transparentSegments[i];
  42203. var gii = ts.groupInsanceInfo;
  42204. var mrc = gii.modelRenderCache;
  42205. var engine = this.owner.engine;
  42206. var count = ts.endDataIndex - ts.startDataIndex;
  42207. // Use Instanced Array if it's supported and if there's at least 5 prims to draw.
  42208. // We don't want to create an Instanced Buffer for less that 5 prims
  42209. if (useInstanced && count >= 5) {
  42210. if (!ts.partBuffers) {
  42211. var buffers = new Array();
  42212. for (var j = 0; j < gii.transparentData.length; j++) {
  42213. var gitd = gii.transparentData[j];
  42214. var dfa = gitd._partData;
  42215. var data = dfa.pack();
  42216. var stride = dfa.stride;
  42217. var neededSize = count * stride * 4;
  42218. var buffer = engine.createInstancesBuffer(neededSize); // Create + bind
  42219. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  42220. engine.updateArrayBuffer(segData);
  42221. buffers.push(buffer);
  42222. }
  42223. ts.partBuffers = buffers;
  42224. }
  42225. else if (gii.transparentDirty) {
  42226. for (var j = 0; j < gii.transparentData.length; j++) {
  42227. var gitd = gii.transparentData[j];
  42228. var dfa = gitd._partData;
  42229. var data = dfa.pack();
  42230. var stride = dfa.stride;
  42231. var buffer = ts.partBuffers[j];
  42232. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  42233. engine.bindArrayBuffer(buffer);
  42234. engine.updateArrayBuffer(segData);
  42235. }
  42236. }
  42237. context.useInstancing = true;
  42238. context.instancesCount = count;
  42239. context.instancedBuffers = ts.partBuffers;
  42240. context.groupInfoPartData = gii.transparentData;
  42241. var renderFailed = !mrc.render(gii, context);
  42242. failedCount += renderFailed ? 1 : 0;
  42243. }
  42244. else {
  42245. context.useInstancing = false;
  42246. context.partDataStartIndex = ts.startDataIndex;
  42247. context.partDataEndIndex = ts.endDataIndex;
  42248. context.groupInfoPartData = gii.transparentData;
  42249. var renderFailed = !mrc.render(gii, context);
  42250. failedCount += renderFailed ? 1 : 0;
  42251. }
  42252. }
  42253. return failedCount;
  42254. };
  42255. Group2D.prototype._prepareContext = function (engine, context, gii) {
  42256. var gipd = null;
  42257. var setDirty;
  42258. var getDirty;
  42259. // Render Mode specifics
  42260. switch (context.renderMode) {
  42261. case BABYLON.Render2DContext.RenderModeOpaque:
  42262. {
  42263. if (!gii.hasOpaqueData) {
  42264. return null;
  42265. }
  42266. setDirty = function (dirty) { gii.opaqueDirty = dirty; };
  42267. getDirty = function () { return gii.opaqueDirty; };
  42268. context.groupInfoPartData = gii.opaqueData;
  42269. gipd = gii.opaqueData;
  42270. break;
  42271. }
  42272. case BABYLON.Render2DContext.RenderModeAlphaTest:
  42273. {
  42274. if (!gii.hasAlphaTestData) {
  42275. return null;
  42276. }
  42277. setDirty = function (dirty) { gii.alphaTestDirty = dirty; };
  42278. getDirty = function () { return gii.alphaTestDirty; };
  42279. context.groupInfoPartData = gii.alphaTestData;
  42280. gipd = gii.alphaTestData;
  42281. break;
  42282. }
  42283. default:
  42284. throw new Error("_prepareContext is only for opaque or alphaTest");
  42285. }
  42286. var renderCount = 0;
  42287. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  42288. // Skip it if instanced arrays are not supported
  42289. if (this.owner.supportInstancedArray) {
  42290. // Flag for instancing
  42291. context.useInstancing = true;
  42292. // Make sure all the WebGLBuffers of the Instanced Array are created/up to date for the parts to render.
  42293. for (var i = 0; i < gipd.length; i++) {
  42294. var pid = gipd[i];
  42295. // If the instances of the model was changed, pack the data
  42296. var array = pid._partData;
  42297. var instanceData_1 = array.pack();
  42298. renderCount += array.usedElementCount;
  42299. // Compute the size the instance buffer should have
  42300. var neededSize = array.usedElementCount * array.stride * 4;
  42301. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  42302. if (!pid._partBuffer || (pid._partBufferSize < neededSize)) {
  42303. if (pid._partBuffer) {
  42304. engine.deleteInstancesBuffer(pid._partBuffer);
  42305. }
  42306. pid._partBuffer = engine.createInstancesBuffer(neededSize); // Create + bind
  42307. pid._partBufferSize = neededSize;
  42308. setDirty(false);
  42309. // Update the WebGL buffer to match the new content of the instances data
  42310. engine.updateArrayBuffer(instanceData_1);
  42311. }
  42312. else if (getDirty()) {
  42313. // Update the WebGL buffer to match the new content of the instances data
  42314. engine.bindArrayBuffer(pid._partBuffer);
  42315. engine.updateArrayBuffer(instanceData_1);
  42316. }
  42317. }
  42318. setDirty(false);
  42319. }
  42320. else {
  42321. context.partDataStartIndex = 0;
  42322. // Find the first valid object to get the count
  42323. if (context.groupInfoPartData.length > 0) {
  42324. var i = 0;
  42325. while (!context.groupInfoPartData[i]) {
  42326. i++;
  42327. }
  42328. context.partDataEndIndex = context.groupInfoPartData[i]._partData.usedElementCount;
  42329. }
  42330. }
  42331. return renderCount;
  42332. };
  42333. Group2D.prototype._setRenderingScale = function (scale) {
  42334. if (this._renderableData._renderingScale === scale) {
  42335. return;
  42336. }
  42337. this._renderableData._renderingScale = scale;
  42338. };
  42339. Group2D.prototype._bindCacheTarget = function () {
  42340. var curWidth;
  42341. var curHeight;
  42342. var rd = this._renderableData;
  42343. var rs = rd._renderingScale;
  42344. Group2D._s.width = Math.ceil(this.actualSize.width * rs);
  42345. Group2D._s.height = Math.ceil(this.actualSize.height * rs);
  42346. var sizeChanged = !Group2D._s.equals(rd._cacheSize);
  42347. if (rd._cacheNode) {
  42348. var size = rd._cacheNode.contentSize;
  42349. // Check if we have to deallocate because the size is too small
  42350. if ((size.width < Group2D._s.width) || (size.height < Group2D._s.height)) {
  42351. // For Screen space: over-provisioning of 7% more to avoid frequent resizing for few pixels...
  42352. // For World space: no over-provisioning
  42353. var overprovisioning = this.owner.isScreenSpace ? 1.07 : 1;
  42354. curWidth = Math.floor(Group2D._s.width * overprovisioning);
  42355. curHeight = Math.floor(Group2D._s.height * overprovisioning);
  42356. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  42357. rd._cacheTexture.freeRect(rd._cacheNode);
  42358. rd._cacheNode = null;
  42359. }
  42360. }
  42361. if (!rd._cacheNode) {
  42362. // Check if we have to allocate a rendering zone in the global cache texture
  42363. var res = this.owner._allocateGroupCache(this, this.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null, rd._useMipMap, rd._anisotropicLevel);
  42364. rd._cacheNode = res.node;
  42365. rd._cacheTexture = res.texture;
  42366. rd._cacheRenderSprite = res.sprite;
  42367. sizeChanged = true;
  42368. }
  42369. if (sizeChanged) {
  42370. rd._cacheSize.copyFrom(Group2D._s);
  42371. rd._cacheNodeUVs = rd._cacheNode.getUVsForCustomSize(rd._cacheSize);
  42372. this.scale = this._renderableData._renderingScale;
  42373. if (rd._cacheNodeUVsChangedObservable && rd._cacheNodeUVsChangedObservable.hasObservers()) {
  42374. rd._cacheNodeUVsChangedObservable.notifyObservers(rd._cacheNodeUVs);
  42375. }
  42376. this._setFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  42377. }
  42378. var n = rd._cacheNode;
  42379. rd._cacheTexture.bindTextureForPosSize(n.pos, Group2D._s, true);
  42380. };
  42381. Group2D.prototype._unbindCacheTarget = function () {
  42382. if (this._renderableData._cacheTexture) {
  42383. this._renderableData._cacheTexture.unbindTexture();
  42384. }
  42385. };
  42386. Group2D.prototype.handleGroupChanged = function (prop) {
  42387. // This method is only for cachedGroup
  42388. var rd = this._renderableData;
  42389. if (!this.isCachedGroup || !rd._cacheRenderSprite) {
  42390. return;
  42391. }
  42392. // For now we only support these property changes
  42393. // TODO: add more! :)
  42394. if (prop.id === BABYLON.Prim2DBase.actualPositionProperty.id) {
  42395. rd._cacheRenderSprite.actualPosition = this.actualPosition.clone();
  42396. }
  42397. else if (prop.id === BABYLON.Prim2DBase.rotationProperty.id) {
  42398. rd._cacheRenderSprite.rotation = this.rotation;
  42399. }
  42400. else if (prop.id === BABYLON.Prim2DBase.scaleProperty.id) {
  42401. rd._cacheRenderSprite.scale = this.scale;
  42402. }
  42403. else if (prop.id === BABYLON.Prim2DBase.originProperty.id) {
  42404. rd._cacheRenderSprite.origin = this.origin.clone();
  42405. }
  42406. else if (prop.id === Group2D.actualSizeProperty.id) {
  42407. rd._cacheRenderSprite.size = this.actualSize.clone();
  42408. }
  42409. };
  42410. Group2D.prototype.detectGroupStates = function () {
  42411. var isCanvas = this instanceof BABYLON.Canvas2D;
  42412. var canvasStrat = this.owner.cachingStrategy;
  42413. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  42414. if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
  42415. this._isRenderableGroup = isCanvas;
  42416. this._isCachedGroup = false;
  42417. }
  42418. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
  42419. if (isCanvas) {
  42420. this._isRenderableGroup = true;
  42421. this._isCachedGroup = true;
  42422. }
  42423. else {
  42424. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  42425. this._isCachedGroup = false;
  42426. }
  42427. }
  42428. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  42429. if (isCanvas) {
  42430. this._isRenderableGroup = true;
  42431. this._isCachedGroup = false;
  42432. }
  42433. else {
  42434. if (this.hierarchyDepth === 1) {
  42435. this._isRenderableGroup = true;
  42436. this._isCachedGroup = true;
  42437. }
  42438. else {
  42439. this._isRenderableGroup = false;
  42440. this._isCachedGroup = false;
  42441. }
  42442. }
  42443. }
  42444. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  42445. var gcb = this.cacheBehavior;
  42446. if ((gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  42447. this._isRenderableGroup = gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  42448. this._isCachedGroup = false;
  42449. }
  42450. if (gcb === Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  42451. this._isRenderableGroup = true;
  42452. this._isCachedGroup = true;
  42453. }
  42454. }
  42455. if (this._isRenderableGroup) {
  42456. // Yes, we do need that check, trust me, unfortunately we can call _detectGroupStates many time on the same object...
  42457. if (!this._renderableData) {
  42458. this._renderableData = new RenderableGroupData();
  42459. }
  42460. }
  42461. // If the group is tagged as renderable we add it to the renderable tree
  42462. if (this._isCachedGroup) {
  42463. var cur = this.parent;
  42464. while (cur) {
  42465. if (cur instanceof Group2D && cur._isRenderableGroup) {
  42466. if (cur._renderableData._childrenRenderableGroups.indexOf(this) === -1) {
  42467. cur._renderableData._childrenRenderableGroups.push(this);
  42468. }
  42469. break;
  42470. }
  42471. cur = cur.parent;
  42472. }
  42473. }
  42474. };
  42475. Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  42476. /**
  42477. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  42478. */
  42479. Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  42480. /**
  42481. * When used, this group's content won't be cached, no matter which strategy used.
  42482. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  42483. */
  42484. Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  42485. /**
  42486. * When used, the group's content will be cached in the nearest cached parent group/canvas
  42487. */
  42488. Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  42489. Group2D._s = BABYLON.Size.Zero();
  42490. __decorate([
  42491. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D.sizeProperty = pi; }, false, true)
  42492. ], Group2D.prototype, "size", null);
  42493. __decorate([
  42494. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 2, function (pi) { return Group2D.actualSizeProperty = pi; })
  42495. ], Group2D.prototype, "actualSize", null);
  42496. Group2D = __decorate([
  42497. BABYLON.className("Group2D")
  42498. ], Group2D);
  42499. return Group2D;
  42500. }(BABYLON.Prim2DBase));
  42501. BABYLON.Group2D = Group2D;
  42502. var RenderableGroupData = (function () {
  42503. function RenderableGroupData() {
  42504. this._primDirtyList = new Array();
  42505. this._childrenRenderableGroups = new Array();
  42506. this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
  42507. this._transparentPrimitives = new Array();
  42508. this._transparentSegments = new Array();
  42509. this._transparentListChanged = false;
  42510. this._cacheNode = null;
  42511. this._cacheTexture = null;
  42512. this._cacheRenderSprite = null;
  42513. this._renderingScale = 1;
  42514. this._cacheNodeUVs = null;
  42515. this._cacheNodeUVsChangedObservable = null;
  42516. this._cacheSize = BABYLON.Size.Zero();
  42517. this._useMipMap = false;
  42518. this._anisotropicLevel = 1;
  42519. }
  42520. RenderableGroupData.prototype.dispose = function (engine) {
  42521. if (this._cacheRenderSprite) {
  42522. this._cacheRenderSprite.dispose();
  42523. this._cacheRenderSprite = null;
  42524. }
  42525. if (this._cacheTexture && this._cacheNode) {
  42526. this._cacheTexture.freeRect(this._cacheNode);
  42527. this._cacheTexture = null;
  42528. this._cacheNode = null;
  42529. }
  42530. if (this._primDirtyList) {
  42531. this._primDirtyList.splice(0);
  42532. this._primDirtyList = null;
  42533. }
  42534. if (this._renderGroupInstancesInfo) {
  42535. this._renderGroupInstancesInfo.forEach(function (k, v) {
  42536. v.dispose();
  42537. });
  42538. this._renderGroupInstancesInfo = null;
  42539. }
  42540. if (this._cacheNodeUVsChangedObservable) {
  42541. this._cacheNodeUVsChangedObservable.clear();
  42542. this._cacheNodeUVsChangedObservable = null;
  42543. }
  42544. if (this._transparentSegments) {
  42545. for (var _i = 0, _a = this._transparentSegments; _i < _a.length; _i++) {
  42546. var ts = _a[_i];
  42547. ts.dispose(engine);
  42548. }
  42549. this._transparentSegments.splice(0);
  42550. this._transparentSegments = null;
  42551. }
  42552. };
  42553. RenderableGroupData.prototype.addNewTransparentPrimitiveInfo = function (prim, gii) {
  42554. var tpi = new TransparentPrimitiveInfo();
  42555. tpi._primitive = prim;
  42556. tpi._groupInstanceInfo = gii;
  42557. tpi._transparentSegment = null;
  42558. this._transparentPrimitives.push(tpi);
  42559. this._transparentListChanged = true;
  42560. return tpi;
  42561. };
  42562. RenderableGroupData.prototype.removeTransparentPrimitiveInfo = function (tpi) {
  42563. var index = this._transparentPrimitives.indexOf(tpi);
  42564. if (index !== -1) {
  42565. this._transparentPrimitives.splice(index, 1);
  42566. this._transparentListChanged = true;
  42567. }
  42568. };
  42569. RenderableGroupData.prototype.transparentPrimitiveZChanged = function (tpi) {
  42570. this._transparentListChanged = true;
  42571. //this.updateSmallestZChangedPrim(tpi);
  42572. };
  42573. return RenderableGroupData;
  42574. }());
  42575. BABYLON.RenderableGroupData = RenderableGroupData;
  42576. var TransparentPrimitiveInfo = (function () {
  42577. function TransparentPrimitiveInfo() {
  42578. }
  42579. return TransparentPrimitiveInfo;
  42580. }());
  42581. BABYLON.TransparentPrimitiveInfo = TransparentPrimitiveInfo;
  42582. })(BABYLON || (BABYLON = {}));
  42583. var BABYLON;
  42584. (function (BABYLON) {
  42585. var Rectangle2DRenderCache = (function (_super) {
  42586. __extends(Rectangle2DRenderCache, _super);
  42587. function Rectangle2DRenderCache(engine, modelKey) {
  42588. _super.call(this, engine, modelKey);
  42589. this.effectsReady = false;
  42590. this.fillVB = null;
  42591. this.fillIB = null;
  42592. this.fillIndicesCount = 0;
  42593. this.instancingFillAttributes = null;
  42594. this.effectFill = null;
  42595. this.effectFillInstanced = null;
  42596. this.borderVB = null;
  42597. this.borderIB = null;
  42598. this.borderIndicesCount = 0;
  42599. this.instancingBorderAttributes = null;
  42600. this.effectBorder = null;
  42601. this.effectBorderInstanced = null;
  42602. }
  42603. Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
  42604. // Do nothing if the shader is still loading/preparing
  42605. if (!this.effectsReady) {
  42606. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  42607. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  42608. return false;
  42609. }
  42610. this.effectsReady = true;
  42611. }
  42612. var canvas = instanceInfo.owner.owner;
  42613. var engine = canvas.engine;
  42614. var depthFunction = 0;
  42615. if (this.effectFill && this.effectBorder) {
  42616. depthFunction = engine.getDepthFunction();
  42617. engine.setDepthFunctionToLessOrEqual();
  42618. }
  42619. var curAlphaMode = engine.getAlphaMode();
  42620. if (this.effectFill) {
  42621. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  42622. var pid = context.groupInfoPartData[partIndex];
  42623. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  42624. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42625. }
  42626. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  42627. engine.enableEffect(effect);
  42628. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  42629. if (context.useInstancing) {
  42630. if (!this.instancingFillAttributes) {
  42631. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  42632. }
  42633. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  42634. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  42635. canvas._addDrawCallCount(1, context.renderMode);
  42636. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  42637. engine.draw(true, 0, this.fillIndicesCount, count);
  42638. engine.unbindInstanceAttributes();
  42639. }
  42640. else {
  42641. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  42642. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  42643. this.setupUniforms(effect, partIndex, pid._partData, i);
  42644. engine.draw(true, 0, this.fillIndicesCount);
  42645. }
  42646. }
  42647. }
  42648. if (this.effectBorder) {
  42649. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  42650. var pid = context.groupInfoPartData[partIndex];
  42651. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  42652. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42653. }
  42654. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  42655. engine.enableEffect(effect);
  42656. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  42657. if (context.useInstancing) {
  42658. if (!this.instancingBorderAttributes) {
  42659. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  42660. }
  42661. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  42662. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  42663. canvas._addDrawCallCount(1, context.renderMode);
  42664. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  42665. engine.draw(true, 0, this.borderIndicesCount, count);
  42666. engine.unbindInstanceAttributes();
  42667. }
  42668. else {
  42669. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  42670. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  42671. this.setupUniforms(effect, partIndex, pid._partData, i);
  42672. engine.draw(true, 0, this.borderIndicesCount);
  42673. }
  42674. }
  42675. }
  42676. engine.setAlphaMode(curAlphaMode);
  42677. if (this.effectFill && this.effectBorder) {
  42678. engine.setDepthFunction(depthFunction);
  42679. }
  42680. return true;
  42681. };
  42682. Rectangle2DRenderCache.prototype.dispose = function () {
  42683. if (!_super.prototype.dispose.call(this)) {
  42684. return false;
  42685. }
  42686. if (this.fillVB) {
  42687. this._engine._releaseBuffer(this.fillVB);
  42688. this.fillVB = null;
  42689. }
  42690. if (this.fillIB) {
  42691. this._engine._releaseBuffer(this.fillIB);
  42692. this.fillIB = null;
  42693. }
  42694. if (this.effectFill) {
  42695. this._engine._releaseEffect(this.effectFill);
  42696. this.effectFill = null;
  42697. }
  42698. if (this.effectFillInstanced) {
  42699. this._engine._releaseEffect(this.effectFillInstanced);
  42700. this.effectFillInstanced = null;
  42701. }
  42702. if (this.borderVB) {
  42703. this._engine._releaseBuffer(this.borderVB);
  42704. this.borderVB = null;
  42705. }
  42706. if (this.borderIB) {
  42707. this._engine._releaseBuffer(this.borderIB);
  42708. this.borderIB = null;
  42709. }
  42710. if (this.effectBorder) {
  42711. this._engine._releaseEffect(this.effectBorder);
  42712. this.effectBorder = null;
  42713. }
  42714. if (this.effectBorderInstanced) {
  42715. this._engine._releaseEffect(this.effectBorderInstanced);
  42716. this.effectBorderInstanced = null;
  42717. }
  42718. return true;
  42719. };
  42720. return Rectangle2DRenderCache;
  42721. }(BABYLON.ModelRenderCache));
  42722. BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
  42723. var Rectangle2DInstanceData = (function (_super) {
  42724. __extends(Rectangle2DInstanceData, _super);
  42725. function Rectangle2DInstanceData(partId) {
  42726. _super.call(this, partId, 1);
  42727. }
  42728. Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
  42729. get: function () {
  42730. return null;
  42731. },
  42732. enumerable: true,
  42733. configurable: true
  42734. });
  42735. __decorate([
  42736. BABYLON.instanceData()
  42737. ], Rectangle2DInstanceData.prototype, "properties", null);
  42738. return Rectangle2DInstanceData;
  42739. }(BABYLON.Shape2DInstanceData));
  42740. BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
  42741. var Rectangle2D = (function (_super) {
  42742. __extends(Rectangle2D, _super);
  42743. /**
  42744. * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
  42745. * @param settings a combination of settings, possible ones are
  42746. * - 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)
  42747. * - children: an array of direct children
  42748. * - id a text identifier, for information purpose
  42749. * - position: the X & Y positions relative to its parent. Alternatively the x and y settings can be set. Default is [0;0]
  42750. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  42751. * - scale: the initial scale of the primitive. default is 1
  42752. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  42753. * - origin: define the normalized origin point location, default [0.5;0.5]
  42754. * - size: the size of the group. Alternatively the width and height settings can be set. Default will be [10;10].
  42755. * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp edges rectangle).
  42756. * - 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)
  42757. * - 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)
  42758. * - borderThickness: the thickness of the drawn border, default is 1.
  42759. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  42760. * - 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!
  42761. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42762. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42763. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42764. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42765. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  42766. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  42767. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  42768. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  42769. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42770. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42771. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42772. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42773. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  42774. */
  42775. function Rectangle2D(settings) {
  42776. // Avoid checking every time if the object exists
  42777. if (settings == null) {
  42778. settings = {};
  42779. }
  42780. _super.call(this, settings);
  42781. if (settings.size != null) {
  42782. this.size = settings.size;
  42783. }
  42784. else if (settings.width || settings.height) {
  42785. var size = new BABYLON.Size(settings.width, settings.height);
  42786. this.size = size;
  42787. }
  42788. //let size = settings.size || (new Size((settings.width === null) ? null : (settings.width || 10), (settings.height === null) ? null : (settings.height || 10)));
  42789. var roundRadius = (settings.roundRadius == null) ? 0 : settings.roundRadius;
  42790. var borderThickness = (settings.borderThickness == null) ? 1 : settings.borderThickness;
  42791. //this.size = size;
  42792. this.roundRadius = roundRadius;
  42793. this.borderThickness = borderThickness;
  42794. }
  42795. Object.defineProperty(Rectangle2D.prototype, "actualSize", {
  42796. get: function () {
  42797. if (this._actualSize) {
  42798. return this._actualSize;
  42799. }
  42800. return this.size;
  42801. },
  42802. set: function (value) {
  42803. this._actualSize = value;
  42804. },
  42805. enumerable: true,
  42806. configurable: true
  42807. });
  42808. Object.defineProperty(Rectangle2D.prototype, "notRounded", {
  42809. get: function () {
  42810. return this._notRounded;
  42811. },
  42812. set: function (value) {
  42813. this._notRounded = value;
  42814. },
  42815. enumerable: true,
  42816. configurable: true
  42817. });
  42818. Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
  42819. get: function () {
  42820. return this._roundRadius;
  42821. },
  42822. set: function (value) {
  42823. this._roundRadius = value;
  42824. this.notRounded = value === 0;
  42825. this._positioningDirty();
  42826. },
  42827. enumerable: true,
  42828. configurable: true
  42829. });
  42830. Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
  42831. // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
  42832. if (this.notRounded) {
  42833. return true;
  42834. }
  42835. // 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.
  42836. // 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)
  42837. // 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.
  42838. // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
  42839. var size = this.size;
  42840. Rectangle2D._i0.x = intersectInfo._localPickPosition.x;
  42841. Rectangle2D._i0.y = intersectInfo._localPickPosition.y;
  42842. var rr = this.roundRadius;
  42843. var rrs = rr * rr;
  42844. // Check if the point is in the bottom/left quarter area
  42845. Rectangle2D._i1.x = rr;
  42846. Rectangle2D._i1.y = rr;
  42847. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  42848. // Compute the intersection point in the quarter local space
  42849. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  42850. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  42851. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  42852. return Rectangle2D._i2.lengthSquared() <= rrs;
  42853. }
  42854. // Check if the point is in the top/left quarter area
  42855. Rectangle2D._i1.x = rr;
  42856. Rectangle2D._i1.y = size.height - rr;
  42857. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  42858. // Compute the intersection point in the quarter local space
  42859. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  42860. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  42861. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  42862. return Rectangle2D._i2.lengthSquared() <= rrs;
  42863. }
  42864. // Check if the point is in the top/right quarter area
  42865. Rectangle2D._i1.x = size.width - rr;
  42866. Rectangle2D._i1.y = size.height - rr;
  42867. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  42868. // Compute the intersection point in the quarter local space
  42869. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  42870. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  42871. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  42872. return Rectangle2D._i2.lengthSquared() <= rrs;
  42873. }
  42874. // Check if the point is in the bottom/right quarter area
  42875. Rectangle2D._i1.x = size.width - rr;
  42876. Rectangle2D._i1.y = rr;
  42877. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  42878. // Compute the intersection point in the quarter local space
  42879. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  42880. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  42881. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  42882. return Rectangle2D._i2.lengthSquared() <= rrs;
  42883. }
  42884. // At any other locations the point is guarantied to be inside
  42885. return true;
  42886. };
  42887. Rectangle2D.prototype.updateLevelBoundingInfo = function () {
  42888. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  42889. };
  42890. Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
  42891. var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
  42892. return renderCache;
  42893. };
  42894. Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  42895. var renderCache = modelRenderCache;
  42896. var engine = this.owner.engine;
  42897. // Need to create WebGL resources for fill part?
  42898. if (this.fill) {
  42899. var vbSize = ((this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4) + 1;
  42900. var vb = new Float32Array(vbSize);
  42901. for (var i = 0; i < vbSize; i++) {
  42902. vb[i] = i;
  42903. }
  42904. renderCache.fillVB = engine.createVertexBuffer(vb);
  42905. var triCount = vbSize - 1;
  42906. var ib = new Float32Array(triCount * 3);
  42907. for (var i = 0; i < triCount; i++) {
  42908. ib[i * 3 + 0] = 0;
  42909. ib[i * 3 + 2] = i + 1;
  42910. ib[i * 3 + 1] = i + 2;
  42911. }
  42912. ib[triCount * 3 - 2] = 1;
  42913. renderCache.fillIB = engine.createIndexBuffer(ib);
  42914. renderCache.fillIndicesCount = triCount * 3;
  42915. // 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
  42916. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], true);
  42917. if (ei) {
  42918. renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  42919. }
  42920. // Get the non instanced version
  42921. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], false);
  42922. renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  42923. }
  42924. // Need to create WebGL resource for border part?
  42925. if (this.border) {
  42926. var vbSize = (this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4 * 2;
  42927. var vb = new Float32Array(vbSize);
  42928. for (var i = 0; i < vbSize; i++) {
  42929. vb[i] = i;
  42930. }
  42931. renderCache.borderVB = engine.createVertexBuffer(vb);
  42932. var triCount = vbSize;
  42933. var rs = triCount / 2;
  42934. var ib = new Float32Array(triCount * 3);
  42935. for (var i = 0; i < rs; i++) {
  42936. var r0 = i;
  42937. var r1 = (i + 1) % rs;
  42938. ib[i * 6 + 0] = rs + r1;
  42939. ib[i * 6 + 1] = rs + r0;
  42940. ib[i * 6 + 2] = r0;
  42941. ib[i * 6 + 3] = r1;
  42942. ib[i * 6 + 4] = rs + r1;
  42943. ib[i * 6 + 5] = r0;
  42944. }
  42945. renderCache.borderIB = engine.createIndexBuffer(ib);
  42946. renderCache.borderIndicesCount = triCount * 3;
  42947. // 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
  42948. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], true);
  42949. if (ei) {
  42950. renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  42951. }
  42952. // Get the non instanced version
  42953. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], false);
  42954. renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  42955. }
  42956. return renderCache;
  42957. };
  42958. // 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
  42959. Rectangle2D.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  42960. // Fall back to default implementation if there's no round Radius
  42961. if (this._notRounded) {
  42962. _super.prototype._getInitialContentAreaToRef.call(this, primSize, initialContentPosition, initialContentArea);
  42963. }
  42964. else {
  42965. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  42966. initialContentPosition.x = initialContentPosition.y = rr;
  42967. initialContentArea.width = Math.max(0, primSize.width - (rr * 2));
  42968. initialContentArea.height = Math.max(0, primSize.height - (rr * 2));
  42969. }
  42970. };
  42971. Rectangle2D.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  42972. // Fall back to default implementation if there's no round Radius
  42973. if (this._notRounded) {
  42974. _super.prototype._getActualSizeFromContentToRef.call(this, primSize, newPrimSize);
  42975. }
  42976. else {
  42977. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  42978. newPrimSize.copyFrom(primSize);
  42979. newPrimSize.width += rr * 2;
  42980. newPrimSize.height += rr * 2;
  42981. }
  42982. };
  42983. Rectangle2D.prototype.createInstanceDataParts = function () {
  42984. var res = new Array();
  42985. if (this.border) {
  42986. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  42987. }
  42988. if (this.fill) {
  42989. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  42990. }
  42991. return res;
  42992. };
  42993. Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
  42994. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  42995. return false;
  42996. }
  42997. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  42998. var d = part;
  42999. var size = this.actualSize;
  43000. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  43001. }
  43002. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  43003. var d = part;
  43004. var size = this.actualSize;
  43005. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  43006. }
  43007. return true;
  43008. };
  43009. Rectangle2D._i0 = BABYLON.Vector2.Zero();
  43010. Rectangle2D._i1 = BABYLON.Vector2.Zero();
  43011. Rectangle2D._i2 = BABYLON.Vector2.Zero();
  43012. Rectangle2D.roundSubdivisions = 16;
  43013. __decorate([
  43014. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D.actualSizeProperty = pi; }, false, true)
  43015. ], Rectangle2D.prototype, "actualSize", null);
  43016. __decorate([
  43017. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D.notRoundedProperty = pi; })
  43018. ], Rectangle2D.prototype, "notRounded", null);
  43019. __decorate([
  43020. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D.roundRadiusProperty = pi; })
  43021. ], Rectangle2D.prototype, "roundRadius", null);
  43022. Rectangle2D = __decorate([
  43023. BABYLON.className("Rectangle2D")
  43024. ], Rectangle2D);
  43025. return Rectangle2D;
  43026. }(BABYLON.Shape2D));
  43027. BABYLON.Rectangle2D = Rectangle2D;
  43028. })(BABYLON || (BABYLON = {}));
  43029. var BABYLON;
  43030. (function (BABYLON) {
  43031. var Ellipse2DRenderCache = (function (_super) {
  43032. __extends(Ellipse2DRenderCache, _super);
  43033. function Ellipse2DRenderCache(engine, modelKey) {
  43034. _super.call(this, engine, modelKey);
  43035. this.effectsReady = false;
  43036. this.fillVB = null;
  43037. this.fillIB = null;
  43038. this.fillIndicesCount = 0;
  43039. this.instancingFillAttributes = null;
  43040. this.effectFillInstanced = null;
  43041. this.effectFill = null;
  43042. this.borderVB = null;
  43043. this.borderIB = null;
  43044. this.borderIndicesCount = 0;
  43045. this.instancingBorderAttributes = null;
  43046. this.effectBorderInstanced = null;
  43047. this.effectBorder = null;
  43048. }
  43049. Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
  43050. // Do nothing if the shader is still loading/preparing
  43051. if (!this.effectsReady) {
  43052. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  43053. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  43054. return false;
  43055. }
  43056. this.effectsReady = true;
  43057. }
  43058. var canvas = instanceInfo.owner.owner;
  43059. var engine = canvas.engine;
  43060. var depthFunction = 0;
  43061. if (this.effectFill && this.effectBorder) {
  43062. depthFunction = engine.getDepthFunction();
  43063. engine.setDepthFunctionToLessOrEqual();
  43064. }
  43065. var curAlphaMode = engine.getAlphaMode();
  43066. if (this.effectFill) {
  43067. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  43068. var pid = context.groupInfoPartData[partIndex];
  43069. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  43070. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  43071. }
  43072. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  43073. engine.enableEffect(effect);
  43074. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  43075. if (context.useInstancing) {
  43076. if (!this.instancingFillAttributes) {
  43077. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  43078. }
  43079. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  43080. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  43081. canvas._addDrawCallCount(1, context.renderMode);
  43082. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  43083. engine.draw(true, 0, this.fillIndicesCount, count);
  43084. engine.unbindInstanceAttributes();
  43085. }
  43086. else {
  43087. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  43088. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  43089. this.setupUniforms(effect, partIndex, pid._partData, i);
  43090. engine.draw(true, 0, this.fillIndicesCount);
  43091. }
  43092. }
  43093. }
  43094. if (this.effectBorder) {
  43095. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  43096. var pid = context.groupInfoPartData[partIndex];
  43097. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  43098. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  43099. }
  43100. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  43101. engine.enableEffect(effect);
  43102. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  43103. if (context.useInstancing) {
  43104. if (!this.instancingBorderAttributes) {
  43105. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  43106. }
  43107. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  43108. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  43109. canvas._addDrawCallCount(1, context.renderMode);
  43110. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  43111. engine.draw(true, 0, this.borderIndicesCount, count);
  43112. engine.unbindInstanceAttributes();
  43113. }
  43114. else {
  43115. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  43116. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  43117. this.setupUniforms(effect, partIndex, pid._partData, i);
  43118. engine.draw(true, 0, this.borderIndicesCount);
  43119. }
  43120. }
  43121. }
  43122. engine.setAlphaMode(curAlphaMode);
  43123. if (this.effectFill && this.effectBorder) {
  43124. engine.setDepthFunction(depthFunction);
  43125. }
  43126. return true;
  43127. };
  43128. Ellipse2DRenderCache.prototype.dispose = function () {
  43129. if (!_super.prototype.dispose.call(this)) {
  43130. return false;
  43131. }
  43132. if (this.fillVB) {
  43133. this._engine._releaseBuffer(this.fillVB);
  43134. this.fillVB = null;
  43135. }
  43136. if (this.fillIB) {
  43137. this._engine._releaseBuffer(this.fillIB);
  43138. this.fillIB = null;
  43139. }
  43140. if (this.effectFill) {
  43141. this._engine._releaseEffect(this.effectFill);
  43142. this.effectFill = null;
  43143. }
  43144. if (this.effectFillInstanced) {
  43145. this._engine._releaseEffect(this.effectFillInstanced);
  43146. this.effectFillInstanced = null;
  43147. }
  43148. if (this.borderVB) {
  43149. this._engine._releaseBuffer(this.borderVB);
  43150. this.borderVB = null;
  43151. }
  43152. if (this.borderIB) {
  43153. this._engine._releaseBuffer(this.borderIB);
  43154. this.borderIB = null;
  43155. }
  43156. if (this.effectBorder) {
  43157. this._engine._releaseEffect(this.effectBorder);
  43158. this.effectBorder = null;
  43159. }
  43160. if (this.effectBorderInstanced) {
  43161. this._engine._releaseEffect(this.effectBorderInstanced);
  43162. this.effectBorderInstanced = null;
  43163. }
  43164. return true;
  43165. };
  43166. return Ellipse2DRenderCache;
  43167. }(BABYLON.ModelRenderCache));
  43168. BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
  43169. var Ellipse2DInstanceData = (function (_super) {
  43170. __extends(Ellipse2DInstanceData, _super);
  43171. function Ellipse2DInstanceData(partId) {
  43172. _super.call(this, partId, 1);
  43173. }
  43174. Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
  43175. get: function () {
  43176. return null;
  43177. },
  43178. enumerable: true,
  43179. configurable: true
  43180. });
  43181. __decorate([
  43182. BABYLON.instanceData()
  43183. ], Ellipse2DInstanceData.prototype, "properties", null);
  43184. return Ellipse2DInstanceData;
  43185. }(BABYLON.Shape2DInstanceData));
  43186. BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
  43187. var Ellipse2D = (function (_super) {
  43188. __extends(Ellipse2D, _super);
  43189. /**
  43190. * Create an Ellipse 2D Shape primitive
  43191. * @param settings a combination of settings, possible ones are
  43192. * - 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)
  43193. * - children: an array of direct children
  43194. * - id: a text identifier, for information purpose
  43195. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  43196. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  43197. * - scale: the initial scale of the primitive. default is 1
  43198. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  43199. * - origin: define the normalized origin point location, default [0.5;0.5]
  43200. * - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
  43201. * - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
  43202. * - 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)
  43203. * - 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)
  43204. * - borderThickness: the thickness of the drawn border, default is 1.
  43205. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  43206. * - 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!
  43207. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43208. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43209. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43210. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43211. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  43212. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  43213. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  43214. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  43215. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43216. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43217. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43218. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43219. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  43220. */
  43221. function Ellipse2D(settings) {
  43222. // Avoid checking every time if the object exists
  43223. if (settings == null) {
  43224. settings = {};
  43225. }
  43226. _super.call(this, settings);
  43227. if (settings.size != null) {
  43228. this.size = settings.size;
  43229. }
  43230. else if (settings.width || settings.height) {
  43231. var size = new BABYLON.Size(settings.width, settings.height);
  43232. this.size = size;
  43233. }
  43234. var sub = (settings.subdivisions == null) ? 64 : settings.subdivisions;
  43235. this.subdivisions = sub;
  43236. }
  43237. Object.defineProperty(Ellipse2D.prototype, "actualSize", {
  43238. get: function () {
  43239. if (this._actualSize) {
  43240. return this._actualSize;
  43241. }
  43242. return this.size;
  43243. },
  43244. set: function (value) {
  43245. this._actualSize = value;
  43246. },
  43247. enumerable: true,
  43248. configurable: true
  43249. });
  43250. Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
  43251. get: function () {
  43252. return this._subdivisions;
  43253. },
  43254. set: function (value) {
  43255. this._subdivisions = value;
  43256. },
  43257. enumerable: true,
  43258. configurable: true
  43259. });
  43260. Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
  43261. var w = this.size.width / 2;
  43262. var h = this.size.height / 2;
  43263. var x = intersectInfo._localPickPosition.x - w;
  43264. var y = intersectInfo._localPickPosition.y - h;
  43265. return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
  43266. };
  43267. Ellipse2D.prototype.updateLevelBoundingInfo = function () {
  43268. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  43269. };
  43270. Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
  43271. var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
  43272. return renderCache;
  43273. };
  43274. Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  43275. var renderCache = modelRenderCache;
  43276. var engine = this.owner.engine;
  43277. // Need to create WebGL resources for fill part?
  43278. if (this.fill) {
  43279. var vbSize = this.subdivisions + 1;
  43280. var vb = new Float32Array(vbSize);
  43281. for (var i = 0; i < vbSize; i++) {
  43282. vb[i] = i;
  43283. }
  43284. renderCache.fillVB = engine.createVertexBuffer(vb);
  43285. var triCount = vbSize - 1;
  43286. var ib = new Float32Array(triCount * 3);
  43287. for (var i = 0; i < triCount; i++) {
  43288. ib[i * 3 + 0] = 0;
  43289. ib[i * 3 + 2] = i + 1;
  43290. ib[i * 3 + 1] = i + 2;
  43291. }
  43292. ib[triCount * 3 - 2] = 1;
  43293. renderCache.fillIB = engine.createIndexBuffer(ib);
  43294. renderCache.fillIndicesCount = triCount * 3;
  43295. // 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
  43296. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], true);
  43297. if (ei) {
  43298. renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  43299. }
  43300. // Get the non instanced version
  43301. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], false);
  43302. renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  43303. }
  43304. // Need to create WebGL resource for border part?
  43305. if (this.border) {
  43306. var vbSize = this.subdivisions * 2;
  43307. var vb = new Float32Array(vbSize);
  43308. for (var i = 0; i < vbSize; i++) {
  43309. vb[i] = i;
  43310. }
  43311. renderCache.borderVB = engine.createVertexBuffer(vb);
  43312. var triCount = vbSize;
  43313. var rs = triCount / 2;
  43314. var ib = new Float32Array(triCount * 3);
  43315. for (var i = 0; i < rs; i++) {
  43316. var r0 = i;
  43317. var r1 = (i + 1) % rs;
  43318. ib[i * 6 + 0] = rs + r1;
  43319. ib[i * 6 + 1] = rs + r0;
  43320. ib[i * 6 + 2] = r0;
  43321. ib[i * 6 + 3] = r1;
  43322. ib[i * 6 + 4] = rs + r1;
  43323. ib[i * 6 + 5] = r0;
  43324. }
  43325. renderCache.borderIB = engine.createIndexBuffer(ib);
  43326. renderCache.borderIndicesCount = (triCount * 3);
  43327. // 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
  43328. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], true);
  43329. if (ei) {
  43330. renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  43331. }
  43332. // Get the non instanced version
  43333. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], false);
  43334. renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  43335. }
  43336. return renderCache;
  43337. };
  43338. Ellipse2D.prototype.createInstanceDataParts = function () {
  43339. var res = new Array();
  43340. if (this.border) {
  43341. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  43342. }
  43343. if (this.fill) {
  43344. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  43345. }
  43346. return res;
  43347. };
  43348. Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
  43349. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  43350. return false;
  43351. }
  43352. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  43353. var d = part;
  43354. var size = this.actualSize;
  43355. d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
  43356. }
  43357. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  43358. var d = part;
  43359. var size = this.actualSize;
  43360. d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
  43361. }
  43362. return true;
  43363. };
  43364. __decorate([
  43365. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Ellipse2D.acutalSizeProperty = pi; }, false, true)
  43366. ], Ellipse2D.prototype, "actualSize", null);
  43367. __decorate([
  43368. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D.subdivisionsProperty = pi; })
  43369. ], Ellipse2D.prototype, "subdivisions", null);
  43370. Ellipse2D = __decorate([
  43371. BABYLON.className("Ellipse2D")
  43372. ], Ellipse2D);
  43373. return Ellipse2D;
  43374. }(BABYLON.Shape2D));
  43375. BABYLON.Ellipse2D = Ellipse2D;
  43376. })(BABYLON || (BABYLON = {}));
  43377. var BABYLON;
  43378. (function (BABYLON) {
  43379. var Sprite2DRenderCache = (function (_super) {
  43380. __extends(Sprite2DRenderCache, _super);
  43381. function Sprite2DRenderCache() {
  43382. _super.apply(this, arguments);
  43383. this.effectsReady = false;
  43384. this.vb = null;
  43385. this.ib = null;
  43386. this.instancingAttributes = null;
  43387. this.texture = null;
  43388. this.effect = null;
  43389. this.effectInstanced = null;
  43390. }
  43391. Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
  43392. // Do nothing if the shader is still loading/preparing
  43393. if (!this.effectsReady) {
  43394. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  43395. return false;
  43396. }
  43397. this.effectsReady = true;
  43398. }
  43399. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  43400. var canvas = instanceInfo.owner.owner;
  43401. var engine = canvas.engine;
  43402. var cur = engine.getAlphaMode();
  43403. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  43404. engine.enableEffect(effect);
  43405. effect.setTexture("diffuseSampler", this.texture);
  43406. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  43407. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  43408. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  43409. }
  43410. var pid = context.groupInfoPartData[0];
  43411. if (context.useInstancing) {
  43412. if (!this.instancingAttributes) {
  43413. this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, effect);
  43414. }
  43415. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  43416. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  43417. canvas._addDrawCallCount(1, context.renderMode);
  43418. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  43419. engine.draw(true, 0, 6, count);
  43420. engine.unbindInstanceAttributes();
  43421. }
  43422. else {
  43423. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  43424. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  43425. this.setupUniforms(effect, 0, pid._partData, i);
  43426. engine.draw(true, 0, 6);
  43427. }
  43428. }
  43429. engine.setAlphaMode(cur);
  43430. return true;
  43431. };
  43432. Sprite2DRenderCache.prototype.dispose = function () {
  43433. if (!_super.prototype.dispose.call(this)) {
  43434. return false;
  43435. }
  43436. if (this.vb) {
  43437. this._engine._releaseBuffer(this.vb);
  43438. this.vb = null;
  43439. }
  43440. if (this.ib) {
  43441. this._engine._releaseBuffer(this.ib);
  43442. this.ib = null;
  43443. }
  43444. if (this.texture) {
  43445. this.texture.dispose();
  43446. this.texture = null;
  43447. }
  43448. if (this.effect) {
  43449. this._engine._releaseEffect(this.effect);
  43450. this.effect = null;
  43451. }
  43452. if (this.effectInstanced) {
  43453. this._engine._releaseEffect(this.effectInstanced);
  43454. this.effectInstanced = null;
  43455. }
  43456. return true;
  43457. };
  43458. return Sprite2DRenderCache;
  43459. }(BABYLON.ModelRenderCache));
  43460. BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
  43461. var Sprite2DInstanceData = (function (_super) {
  43462. __extends(Sprite2DInstanceData, _super);
  43463. function Sprite2DInstanceData(partId) {
  43464. _super.call(this, partId, 1);
  43465. }
  43466. Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
  43467. get: function () {
  43468. return null;
  43469. },
  43470. enumerable: true,
  43471. configurable: true
  43472. });
  43473. Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
  43474. get: function () {
  43475. return null;
  43476. },
  43477. enumerable: true,
  43478. configurable: true
  43479. });
  43480. Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
  43481. get: function () {
  43482. return null;
  43483. },
  43484. enumerable: true,
  43485. configurable: true
  43486. });
  43487. Object.defineProperty(Sprite2DInstanceData.prototype, "properties", {
  43488. // 3 floats being:
  43489. // - x: frame number to display
  43490. // - y: invertY setting
  43491. // - z: alignToPixel setting
  43492. get: function () {
  43493. return null;
  43494. },
  43495. enumerable: true,
  43496. configurable: true
  43497. });
  43498. __decorate([
  43499. BABYLON.instanceData()
  43500. ], Sprite2DInstanceData.prototype, "topLeftUV", null);
  43501. __decorate([
  43502. BABYLON.instanceData()
  43503. ], Sprite2DInstanceData.prototype, "sizeUV", null);
  43504. __decorate([
  43505. BABYLON.instanceData()
  43506. ], Sprite2DInstanceData.prototype, "textureSize", null);
  43507. __decorate([
  43508. BABYLON.instanceData()
  43509. ], Sprite2DInstanceData.prototype, "properties", null);
  43510. return Sprite2DInstanceData;
  43511. }(BABYLON.InstanceDataBase));
  43512. BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
  43513. var Sprite2D = (function (_super) {
  43514. __extends(Sprite2D, _super);
  43515. /**
  43516. * Create an 2D Sprite primitive
  43517. * @param texture the texture that stores the sprite to render
  43518. * @param settings a combination of settings, possible ones are
  43519. * - 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)
  43520. * - children: an array of direct children
  43521. * - id a text identifier, for information purpose
  43522. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  43523. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  43524. * - scale: the initial scale of the primitive. default is 1
  43525. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  43526. * - origin: define the normalized origin point location, default [0.5;0.5]
  43527. * - spriteSize: the size of the sprite (in pixels), if null the size of the given texture will be used, default is null.
  43528. * - spriteLocation: the location (in pixels) in the texture of the top/left corner of the Sprite to display, default is null (0,0)
  43529. * - invertY: if true the texture Y will be inverted, default is false.
  43530. * - 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.
  43531. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  43532. * - 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!
  43533. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43534. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43535. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43536. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43537. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  43538. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  43539. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  43540. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  43541. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43542. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43543. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43544. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43545. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  43546. */
  43547. function Sprite2D(texture, settings) {
  43548. var _this = this;
  43549. if (!settings) {
  43550. settings = {};
  43551. }
  43552. _super.call(this, settings);
  43553. this.texture = texture;
  43554. this.texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43555. this.texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43556. this.size = settings.spriteSize;
  43557. this.spriteLocation = settings.spriteLocation || new BABYLON.Vector2(0, 0);
  43558. this.spriteFrame = 0;
  43559. this.invertY = (settings.invertY == null) ? false : settings.invertY;
  43560. this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  43561. this.isAlphaTest = true;
  43562. if (settings.spriteSize == null) {
  43563. if (texture.isReady()) {
  43564. this.size = texture.getSize();
  43565. }
  43566. else {
  43567. texture.onLoadObservable.add(function () {
  43568. _this.size = texture.getSize();
  43569. });
  43570. }
  43571. }
  43572. }
  43573. Object.defineProperty(Sprite2D.prototype, "texture", {
  43574. get: function () {
  43575. return this._texture;
  43576. },
  43577. set: function (value) {
  43578. this._texture = value;
  43579. },
  43580. enumerable: true,
  43581. configurable: true
  43582. });
  43583. Object.defineProperty(Sprite2D.prototype, "actualSize", {
  43584. get: function () {
  43585. if (this._actualSize) {
  43586. return this._actualSize;
  43587. }
  43588. return this.size;
  43589. },
  43590. set: function (value) {
  43591. this._actualSize = value;
  43592. },
  43593. enumerable: true,
  43594. configurable: true
  43595. });
  43596. Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
  43597. get: function () {
  43598. return this._location;
  43599. },
  43600. set: function (value) {
  43601. this._location = value;
  43602. },
  43603. enumerable: true,
  43604. configurable: true
  43605. });
  43606. Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
  43607. get: function () {
  43608. return this._spriteFrame;
  43609. },
  43610. set: function (value) {
  43611. this._spriteFrame = value;
  43612. },
  43613. enumerable: true,
  43614. configurable: true
  43615. });
  43616. Object.defineProperty(Sprite2D.prototype, "invertY", {
  43617. get: function () {
  43618. return this._invertY;
  43619. },
  43620. set: function (value) {
  43621. this._invertY = value;
  43622. },
  43623. enumerable: true,
  43624. configurable: true
  43625. });
  43626. Object.defineProperty(Sprite2D.prototype, "alignToPixel", {
  43627. /**
  43628. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  43629. */
  43630. get: function () {
  43631. return this._alignToPixel;
  43632. },
  43633. set: function (value) {
  43634. this._alignToPixel = value;
  43635. },
  43636. enumerable: true,
  43637. configurable: true
  43638. });
  43639. Sprite2D.prototype.updateLevelBoundingInfo = function () {
  43640. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo);
  43641. };
  43642. /**
  43643. * Get the animatable array (see http://doc.babylonjs.com/tutorials/Animations)
  43644. */
  43645. Sprite2D.prototype.getAnimatables = function () {
  43646. var res = new Array();
  43647. if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
  43648. res.push(this.texture);
  43649. }
  43650. return res;
  43651. };
  43652. Sprite2D.prototype.levelIntersect = function (intersectInfo) {
  43653. // 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
  43654. return true;
  43655. };
  43656. Sprite2D._createCachedCanvasSprite = function (owner, texture, size, pos) {
  43657. var sprite = new Sprite2D(texture, { parent: owner, id: "__cachedCanvasSprite__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), spriteSize: size, spriteLocation: pos, alignToPixel: true });
  43658. return sprite;
  43659. };
  43660. Sprite2D.prototype.createModelRenderCache = function (modelKey) {
  43661. var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey);
  43662. return renderCache;
  43663. };
  43664. Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  43665. var renderCache = modelRenderCache;
  43666. var engine = this.owner.engine;
  43667. var vb = new Float32Array(4);
  43668. for (var i = 0; i < 4; i++) {
  43669. vb[i] = i;
  43670. }
  43671. renderCache.vb = engine.createVertexBuffer(vb);
  43672. var ib = new Float32Array(6);
  43673. ib[0] = 0;
  43674. ib[1] = 2;
  43675. ib[2] = 1;
  43676. ib[3] = 0;
  43677. ib[4] = 3;
  43678. ib[5] = 2;
  43679. renderCache.ib = engine.createIndexBuffer(ib);
  43680. renderCache.texture = this.texture;
  43681. // 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
  43682. var ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], true);
  43683. if (ei) {
  43684. renderCache.effectInstanced = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  43685. }
  43686. ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], false);
  43687. renderCache.effect = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  43688. return renderCache;
  43689. };
  43690. Sprite2D.prototype.createInstanceDataParts = function () {
  43691. return [new Sprite2DInstanceData(Sprite2D.SPRITE2D_MAINPARTID)];
  43692. };
  43693. Sprite2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  43694. Sprite2D.layoutConstructMode = true;
  43695. };
  43696. // if obj contains something, we restore the _text property
  43697. Sprite2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  43698. Sprite2D.layoutConstructMode = false;
  43699. };
  43700. Sprite2D.prototype.refreshInstanceDataPart = function (part) {
  43701. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  43702. return false;
  43703. }
  43704. if (!this.texture.isReady() && !Sprite2D.layoutConstructMode) {
  43705. return false;
  43706. }
  43707. if (part.id === Sprite2D.SPRITE2D_MAINPARTID) {
  43708. var d = this._instanceDataParts[0];
  43709. if (Sprite2D.layoutConstructMode) {
  43710. d.topLeftUV = BABYLON.Vector2.Zero();
  43711. d.sizeUV = BABYLON.Vector2.Zero();
  43712. d.properties = BABYLON.Vector3.Zero();
  43713. d.textureSize = BABYLON.Vector2.Zero();
  43714. }
  43715. else {
  43716. var ts = this.texture.getBaseSize();
  43717. var sl = this.spriteLocation;
  43718. var ss = this.actualSize;
  43719. d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
  43720. var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
  43721. d.sizeUV = suv;
  43722. Sprite2D._prop.x = this.spriteFrame;
  43723. Sprite2D._prop.y = this.invertY ? 1 : 0;
  43724. Sprite2D._prop.z = this.alignToPixel ? 1 : 0;
  43725. d.properties = Sprite2D._prop;
  43726. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  43727. }
  43728. }
  43729. return true;
  43730. };
  43731. Sprite2D.SPRITE2D_MAINPARTID = 1;
  43732. Sprite2D._prop = BABYLON.Vector3.Zero();
  43733. Sprite2D.layoutConstructMode = false;
  43734. __decorate([
  43735. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D.textureProperty = pi; })
  43736. ], Sprite2D.prototype, "texture", null);
  43737. __decorate([
  43738. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D.actualSizeProperty = pi; }, false, true)
  43739. ], Sprite2D.prototype, "actualSize", null);
  43740. __decorate([
  43741. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Sprite2D.spriteLocationProperty = pi; })
  43742. ], Sprite2D.prototype, "spriteLocation", null);
  43743. __decorate([
  43744. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D.spriteFrameProperty = pi; })
  43745. ], Sprite2D.prototype, "spriteFrame", null);
  43746. __decorate([
  43747. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D.invertYProperty = pi; })
  43748. ], Sprite2D.prototype, "invertY", null);
  43749. Sprite2D = __decorate([
  43750. BABYLON.className("Sprite2D")
  43751. ], Sprite2D);
  43752. return Sprite2D;
  43753. }(BABYLON.RenderablePrim2D));
  43754. BABYLON.Sprite2D = Sprite2D;
  43755. })(BABYLON || (BABYLON = {}));
  43756. var BABYLON;
  43757. (function (BABYLON) {
  43758. var Text2DRenderCache = (function (_super) {
  43759. __extends(Text2DRenderCache, _super);
  43760. function Text2DRenderCache() {
  43761. _super.apply(this, arguments);
  43762. this.effectsReady = false;
  43763. this.vb = null;
  43764. this.ib = null;
  43765. this.instancingAttributes = null;
  43766. this.fontTexture = null;
  43767. this.effect = null;
  43768. this.effectInstanced = null;
  43769. }
  43770. Text2DRenderCache.prototype.render = function (instanceInfo, context) {
  43771. // Do nothing if the shader is still loading/preparing
  43772. if (!this.effectsReady) {
  43773. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  43774. return false;
  43775. }
  43776. this.effectsReady = true;
  43777. }
  43778. var canvas = instanceInfo.owner.owner;
  43779. var engine = canvas.engine;
  43780. this.fontTexture.update();
  43781. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  43782. engine.enableEffect(effect);
  43783. effect.setTexture("diffuseSampler", this.fontTexture);
  43784. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  43785. var curAlphaMode = engine.getAlphaMode();
  43786. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  43787. var pid = context.groupInfoPartData[0];
  43788. if (context.useInstancing) {
  43789. if (!this.instancingAttributes) {
  43790. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
  43791. }
  43792. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  43793. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  43794. canvas._addDrawCallCount(1, context.renderMode);
  43795. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  43796. engine.draw(true, 0, 6, count);
  43797. engine.unbindInstanceAttributes();
  43798. }
  43799. else {
  43800. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  43801. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  43802. this.setupUniforms(effect, 0, pid._partData, i);
  43803. engine.draw(true, 0, 6);
  43804. }
  43805. }
  43806. engine.setAlphaMode(curAlphaMode);
  43807. return true;
  43808. };
  43809. Text2DRenderCache.prototype.dispose = function () {
  43810. if (!_super.prototype.dispose.call(this)) {
  43811. return false;
  43812. }
  43813. if (this.vb) {
  43814. this._engine._releaseBuffer(this.vb);
  43815. this.vb = null;
  43816. }
  43817. if (this.ib) {
  43818. this._engine._releaseBuffer(this.ib);
  43819. this.ib = null;
  43820. }
  43821. if (this.fontTexture) {
  43822. this.fontTexture.dispose();
  43823. this.fontTexture = null;
  43824. }
  43825. if (this.effect) {
  43826. this._engine._releaseEffect(this.effect);
  43827. this.effect = null;
  43828. }
  43829. if (this.effectInstanced) {
  43830. this._engine._releaseEffect(this.effectInstanced);
  43831. this.effectInstanced = null;
  43832. }
  43833. return true;
  43834. };
  43835. return Text2DRenderCache;
  43836. }(BABYLON.ModelRenderCache));
  43837. BABYLON.Text2DRenderCache = Text2DRenderCache;
  43838. var Text2DInstanceData = (function (_super) {
  43839. __extends(Text2DInstanceData, _super);
  43840. function Text2DInstanceData(partId, dataElementCount) {
  43841. _super.call(this, partId, dataElementCount);
  43842. }
  43843. Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
  43844. get: function () {
  43845. return null;
  43846. },
  43847. enumerable: true,
  43848. configurable: true
  43849. });
  43850. Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
  43851. get: function () {
  43852. return null;
  43853. },
  43854. enumerable: true,
  43855. configurable: true
  43856. });
  43857. Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
  43858. get: function () {
  43859. return null;
  43860. },
  43861. enumerable: true,
  43862. configurable: true
  43863. });
  43864. Object.defineProperty(Text2DInstanceData.prototype, "color", {
  43865. get: function () {
  43866. return null;
  43867. },
  43868. enumerable: true,
  43869. configurable: true
  43870. });
  43871. Object.defineProperty(Text2DInstanceData.prototype, "superSampleFactor", {
  43872. get: function () {
  43873. return null;
  43874. },
  43875. enumerable: true,
  43876. configurable: true
  43877. });
  43878. __decorate([
  43879. BABYLON.instanceData()
  43880. ], Text2DInstanceData.prototype, "topLeftUV", null);
  43881. __decorate([
  43882. BABYLON.instanceData()
  43883. ], Text2DInstanceData.prototype, "sizeUV", null);
  43884. __decorate([
  43885. BABYLON.instanceData()
  43886. ], Text2DInstanceData.prototype, "textureSize", null);
  43887. __decorate([
  43888. BABYLON.instanceData()
  43889. ], Text2DInstanceData.prototype, "color", null);
  43890. __decorate([
  43891. BABYLON.instanceData()
  43892. ], Text2DInstanceData.prototype, "superSampleFactor", null);
  43893. return Text2DInstanceData;
  43894. }(BABYLON.InstanceDataBase));
  43895. BABYLON.Text2DInstanceData = Text2DInstanceData;
  43896. var Text2D = (function (_super) {
  43897. __extends(Text2D, _super);
  43898. /**
  43899. * Create a Text primitive
  43900. * @param text the text to display
  43901. * @param settings a combination of settings, possible ones are
  43902. * - 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)
  43903. * - children: an array of direct children
  43904. * - id a text identifier, for information purpose
  43905. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  43906. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  43907. * - scale: the initial scale of the primitive. default is 1
  43908. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  43909. * - origin: define the normalized origin point location, default [0.5;0.5]
  43910. * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
  43911. * - 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.
  43912. * - defaultColor: the color by default to apply on each letter of the text to display, default is plain white.
  43913. * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
  43914. * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
  43915. * - isVisible: true if the text must be visible, false for hidden. Default is true.
  43916. * - 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!
  43917. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43918. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43919. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43920. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43921. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  43922. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  43923. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  43924. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  43925. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43926. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43927. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43928. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43929. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  43930. */
  43931. function Text2D(text, settings) {
  43932. if (!settings) {
  43933. settings = {};
  43934. }
  43935. _super.call(this, settings);
  43936. this.fontName = (settings.fontName == null) ? "12pt Arial" : settings.fontName;
  43937. this._fontSuperSample = (settings.fontSuperSample != null && settings.fontSuperSample);
  43938. this.defaultFontColor = (settings.defaultFontColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : settings.defaultFontColor;
  43939. this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize;
  43940. this._textSize = null;
  43941. this.text = text;
  43942. this.size = (settings.size == null) ? null : settings.size;
  43943. this.isTransparent = true;
  43944. }
  43945. Object.defineProperty(Text2D.prototype, "fontName", {
  43946. get: function () {
  43947. return this._fontName;
  43948. },
  43949. set: function (value) {
  43950. if (this._fontName) {
  43951. throw new Error("Font Name change is not supported right now.");
  43952. }
  43953. this._fontName = value;
  43954. },
  43955. enumerable: true,
  43956. configurable: true
  43957. });
  43958. Object.defineProperty(Text2D.prototype, "defaultFontColor", {
  43959. get: function () {
  43960. return this._defaultFontColor;
  43961. },
  43962. set: function (value) {
  43963. this._defaultFontColor = value;
  43964. },
  43965. enumerable: true,
  43966. configurable: true
  43967. });
  43968. Object.defineProperty(Text2D.prototype, "text", {
  43969. get: function () {
  43970. return this._text;
  43971. },
  43972. set: function (value) {
  43973. this._text = value;
  43974. this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used
  43975. this._size = null;
  43976. this._updateCharCount();
  43977. // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute
  43978. var s = this.textSize;
  43979. },
  43980. enumerable: true,
  43981. configurable: true
  43982. });
  43983. Object.defineProperty(Text2D.prototype, "size", {
  43984. get: function () {
  43985. if (this._size != null) {
  43986. return this._size;
  43987. }
  43988. return this.textSize;
  43989. },
  43990. set: function (value) {
  43991. this._size = value;
  43992. },
  43993. enumerable: true,
  43994. configurable: true
  43995. });
  43996. Object.defineProperty(Text2D.prototype, "actualSize", {
  43997. /**
  43998. * Get the actual size of the Text2D primitive
  43999. */
  44000. get: function () {
  44001. if (this._actualSize) {
  44002. return this._actualSize;
  44003. }
  44004. return this.size;
  44005. },
  44006. enumerable: true,
  44007. configurable: true
  44008. });
  44009. Object.defineProperty(Text2D.prototype, "textSize", {
  44010. /**
  44011. * Get the area that bounds the text associated to the primitive
  44012. */
  44013. get: function () {
  44014. if (!this._textSize) {
  44015. if (this.owner) {
  44016. var newSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  44017. if (!newSize.equals(this._textSize)) {
  44018. this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  44019. this._positioningDirty();
  44020. }
  44021. this._textSize = newSize;
  44022. }
  44023. else {
  44024. return Text2D.nullSize;
  44025. }
  44026. }
  44027. return this._textSize;
  44028. },
  44029. enumerable: true,
  44030. configurable: true
  44031. });
  44032. Object.defineProperty(Text2D.prototype, "fontTexture", {
  44033. get: function () {
  44034. if (this._fontTexture) {
  44035. return this._fontTexture;
  44036. }
  44037. this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  44038. return this._fontTexture;
  44039. },
  44040. enumerable: true,
  44041. configurable: true
  44042. });
  44043. /**
  44044. * Dispose the primitive, remove it from its parent
  44045. */
  44046. Text2D.prototype.dispose = function () {
  44047. if (!_super.prototype.dispose.call(this)) {
  44048. return false;
  44049. }
  44050. if (this._fontTexture) {
  44051. BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  44052. this._fontTexture = null;
  44053. }
  44054. return true;
  44055. };
  44056. Text2D.prototype.updateLevelBoundingInfo = function () {
  44057. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  44058. };
  44059. Text2D.prototype.levelIntersect = function (intersectInfo) {
  44060. // 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...
  44061. return true;
  44062. };
  44063. Text2D.prototype.createModelRenderCache = function (modelKey) {
  44064. var renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
  44065. return renderCache;
  44066. };
  44067. Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  44068. var renderCache = modelRenderCache;
  44069. var engine = this.owner.engine;
  44070. renderCache.fontTexture = this.fontTexture;
  44071. var vb = new Float32Array(4);
  44072. for (var i = 0; i < 4; i++) {
  44073. vb[i] = i;
  44074. }
  44075. renderCache.vb = engine.createVertexBuffer(vb);
  44076. var ib = new Float32Array(6);
  44077. ib[0] = 0;
  44078. ib[1] = 2;
  44079. ib[2] = 1;
  44080. ib[3] = 0;
  44081. ib[4] = 3;
  44082. ib[5] = 2;
  44083. renderCache.ib = engine.createIndexBuffer(ib);
  44084. // 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
  44085. var ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], true);
  44086. if (ei) {
  44087. renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  44088. }
  44089. ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], false);
  44090. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  44091. return renderCache;
  44092. };
  44093. Text2D.prototype.createInstanceDataParts = function () {
  44094. return [new Text2DInstanceData(Text2D.TEXT2D_MAINPARTID, this._charCount)];
  44095. };
  44096. // Looks like a hack!? Yes! Because that's what it is!
  44097. // 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
  44098. // 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)
  44099. Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  44100. if (!this._charCount) {
  44101. var curText = this._text;
  44102. this.text = "A";
  44103. return curText;
  44104. }
  44105. };
  44106. // if obj contains something, we restore the _text property
  44107. Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  44108. if (obj !== undefined) {
  44109. this.text = obj;
  44110. }
  44111. };
  44112. Text2D.prototype.refreshInstanceDataPart = function (part) {
  44113. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  44114. return false;
  44115. }
  44116. if (part.id === Text2D.TEXT2D_MAINPARTID) {
  44117. var d = part;
  44118. var texture = this.fontTexture;
  44119. var superSampleFactor = texture.isSuperSampled ? 0.5 : 1;
  44120. var ts = texture.getSize();
  44121. var offset = BABYLON.Vector2.Zero();
  44122. var lh = this.fontTexture.lineHeight;
  44123. 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
  44124. var charxpos = 0;
  44125. d.dataElementCount = this._charCount;
  44126. d.curElement = 0;
  44127. for (var _i = 0, _a = this.text; _i < _a.length; _i++) {
  44128. var char = _a[_i];
  44129. // Line feed
  44130. if (char === "\n") {
  44131. offset.x = 0;
  44132. offset.y -= texture.lineHeight;
  44133. }
  44134. // Tabulation ?
  44135. if (char === "\t") {
  44136. var nextPos = charxpos + this._tabulationSize;
  44137. nextPos = nextPos - (nextPos % this._tabulationSize);
  44138. offset.x += (nextPos - charxpos) * texture.spaceWidth;
  44139. charxpos = nextPos;
  44140. continue;
  44141. }
  44142. if (char < " ") {
  44143. continue;
  44144. }
  44145. this.updateInstanceDataPart(d, offset);
  44146. var ci = texture.getChar(char);
  44147. offset.x += ci.charWidth;
  44148. d.topLeftUV = ci.topLeftUV;
  44149. var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  44150. d.sizeUV = suv;
  44151. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  44152. d.color = this.defaultFontColor;
  44153. d.superSampleFactor = superSampleFactor;
  44154. ++d.curElement;
  44155. }
  44156. }
  44157. return true;
  44158. };
  44159. Text2D.prototype._updateCharCount = function () {
  44160. var count = 0;
  44161. for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
  44162. var char = _a[_i];
  44163. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  44164. continue;
  44165. }
  44166. ++count;
  44167. }
  44168. this._charCount = count;
  44169. };
  44170. Text2D.TEXT2D_MAINPARTID = 1;
  44171. __decorate([
  44172. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D.fontProperty = pi; }, false, true)
  44173. ], Text2D.prototype, "fontName", null);
  44174. __decorate([
  44175. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D.defaultFontColorProperty = pi; })
  44176. ], Text2D.prototype, "defaultFontColor", null);
  44177. __decorate([
  44178. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D.textProperty = pi; }, false, true)
  44179. ], Text2D.prototype, "text", null);
  44180. __decorate([
  44181. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D.sizeProperty = pi; })
  44182. ], Text2D.prototype, "size", null);
  44183. Text2D = __decorate([
  44184. BABYLON.className("Text2D")
  44185. ], Text2D);
  44186. return Text2D;
  44187. }(BABYLON.RenderablePrim2D));
  44188. BABYLON.Text2D = Text2D;
  44189. })(BABYLON || (BABYLON = {}));
  44190. var BABYLON;
  44191. (function (BABYLON) {
  44192. var Lines2DRenderCache = (function (_super) {
  44193. __extends(Lines2DRenderCache, _super);
  44194. function Lines2DRenderCache(engine, modelKey) {
  44195. _super.call(this, engine, modelKey);
  44196. this.effectsReady = false;
  44197. this.fillVB = null;
  44198. this.fillIB = null;
  44199. this.fillIndicesCount = 0;
  44200. this.instancingFillAttributes = null;
  44201. this.effectFill = null;
  44202. this.effectFillInstanced = null;
  44203. this.borderVB = null;
  44204. this.borderIB = null;
  44205. this.borderIndicesCount = 0;
  44206. this.instancingBorderAttributes = null;
  44207. this.effectBorder = null;
  44208. this.effectBorderInstanced = null;
  44209. }
  44210. Lines2DRenderCache.prototype.render = function (instanceInfo, context) {
  44211. // Do nothing if the shader is still loading/preparing
  44212. if (!this.effectsReady) {
  44213. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  44214. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  44215. return false;
  44216. }
  44217. this.effectsReady = true;
  44218. }
  44219. var canvas = instanceInfo.owner.owner;
  44220. var engine = canvas.engine;
  44221. var depthFunction = 0;
  44222. if (this.effectFill && this.effectBorder) {
  44223. depthFunction = engine.getDepthFunction();
  44224. engine.setDepthFunctionToLessOrEqual();
  44225. }
  44226. var curAlphaMode = engine.getAlphaMode();
  44227. if (this.effectFill) {
  44228. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  44229. var pid = context.groupInfoPartData[partIndex];
  44230. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44231. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44232. }
  44233. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  44234. engine.enableEffect(effect);
  44235. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [2], 2 * 4, effect);
  44236. if (context.useInstancing) {
  44237. if (!this.instancingFillAttributes) {
  44238. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  44239. }
  44240. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44241. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44242. canvas._addDrawCallCount(1, context.renderMode);
  44243. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  44244. engine.draw(true, 0, this.fillIndicesCount, count);
  44245. engine.unbindInstanceAttributes();
  44246. }
  44247. else {
  44248. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44249. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44250. this.setupUniforms(effect, partIndex, pid._partData, i);
  44251. engine.draw(true, 0, this.fillIndicesCount);
  44252. }
  44253. }
  44254. }
  44255. if (this.effectBorder) {
  44256. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  44257. var pid = context.groupInfoPartData[partIndex];
  44258. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44259. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44260. }
  44261. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  44262. engine.enableEffect(effect);
  44263. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [2], 2 * 4, effect);
  44264. if (context.useInstancing) {
  44265. if (!this.instancingBorderAttributes) {
  44266. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  44267. }
  44268. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44269. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44270. canvas._addDrawCallCount(1, context.renderMode);
  44271. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  44272. engine.draw(true, 0, this.borderIndicesCount, count);
  44273. engine.unbindInstanceAttributes();
  44274. }
  44275. else {
  44276. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44277. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44278. this.setupUniforms(effect, partIndex, pid._partData, i);
  44279. engine.draw(true, 0, this.borderIndicesCount);
  44280. }
  44281. }
  44282. }
  44283. engine.setAlphaMode(curAlphaMode);
  44284. if (this.effectFill && this.effectBorder) {
  44285. engine.setDepthFunction(depthFunction);
  44286. }
  44287. return true;
  44288. };
  44289. Lines2DRenderCache.prototype.dispose = function () {
  44290. if (!_super.prototype.dispose.call(this)) {
  44291. return false;
  44292. }
  44293. if (this.fillVB) {
  44294. this._engine._releaseBuffer(this.fillVB);
  44295. this.fillVB = null;
  44296. }
  44297. if (this.fillIB) {
  44298. this._engine._releaseBuffer(this.fillIB);
  44299. this.fillIB = null;
  44300. }
  44301. if (this.effectFill) {
  44302. this._engine._releaseEffect(this.effectFill);
  44303. this.effectFill = null;
  44304. }
  44305. if (this.effectFillInstanced) {
  44306. this._engine._releaseEffect(this.effectFillInstanced);
  44307. this.effectFillInstanced = null;
  44308. }
  44309. if (this.borderVB) {
  44310. this._engine._releaseBuffer(this.borderVB);
  44311. this.borderVB = null;
  44312. }
  44313. if (this.borderIB) {
  44314. this._engine._releaseBuffer(this.borderIB);
  44315. this.borderIB = null;
  44316. }
  44317. if (this.effectBorder) {
  44318. this._engine._releaseEffect(this.effectBorder);
  44319. this.effectBorder = null;
  44320. }
  44321. if (this.effectBorderInstanced) {
  44322. this._engine._releaseEffect(this.effectBorderInstanced);
  44323. this.effectBorderInstanced = null;
  44324. }
  44325. return true;
  44326. };
  44327. return Lines2DRenderCache;
  44328. }(BABYLON.ModelRenderCache));
  44329. BABYLON.Lines2DRenderCache = Lines2DRenderCache;
  44330. var Lines2DInstanceData = (function (_super) {
  44331. __extends(Lines2DInstanceData, _super);
  44332. function Lines2DInstanceData(partId) {
  44333. _super.call(this, partId, 1);
  44334. }
  44335. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMin", {
  44336. get: function () {
  44337. return null;
  44338. },
  44339. enumerable: true,
  44340. configurable: true
  44341. });
  44342. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMax", {
  44343. get: function () {
  44344. return null;
  44345. },
  44346. enumerable: true,
  44347. configurable: true
  44348. });
  44349. __decorate([
  44350. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  44351. ], Lines2DInstanceData.prototype, "boundingMin", null);
  44352. __decorate([
  44353. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  44354. ], Lines2DInstanceData.prototype, "boundingMax", null);
  44355. return Lines2DInstanceData;
  44356. }(BABYLON.Shape2DInstanceData));
  44357. BABYLON.Lines2DInstanceData = Lines2DInstanceData;
  44358. var Lines2D = (function (_super) {
  44359. __extends(Lines2D, _super);
  44360. /**
  44361. * Create an 2D Lines Shape primitive. The defined lines may be opened or closed (see below)
  44362. * @param points an array that describe the points to use to draw the line, must contain at least two entries.
  44363. * @param settings a combination of settings, possible ones are
  44364. * - 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)
  44365. * - children: an array of direct children
  44366. * - id a text identifier, for information purpose
  44367. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  44368. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  44369. * - scale: the initial scale of the primitive. default is 1
  44370. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  44371. * - origin: define the normalized origin point location, default [0.5;0.5]
  44372. * - 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.
  44373. * - 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.
  44374. * - 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.
  44375. * - 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.
  44376. * - 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)
  44377. * - 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)
  44378. * - borderThickness: the thickness of the drawn border, default is 1.
  44379. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  44380. * - 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!
  44381. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44382. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44383. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44384. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44385. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  44386. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  44387. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  44388. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  44389. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44390. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44391. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44392. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44393. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  44394. */
  44395. function Lines2D(points, settings) {
  44396. if (!settings) {
  44397. settings = {};
  44398. }
  44399. _super.call(this, settings);
  44400. this._fillVB = null;
  44401. this._fillIB = null;
  44402. this._borderVB = null;
  44403. this._borderIB = null;
  44404. this._size = BABYLON.Size.Zero();
  44405. this._boundingMin = null;
  44406. this._boundingMax = null;
  44407. var fillThickness = (settings.fillThickness == null) ? 1 : settings.fillThickness;
  44408. var startCap = (settings.startCap == null) ? 0 : settings.startCap;
  44409. var endCap = (settings.endCap == null) ? 0 : settings.endCap;
  44410. var closed = (settings.closed == null) ? false : settings.closed;
  44411. this.points = points;
  44412. this.fillThickness = fillThickness;
  44413. this.startCap = startCap;
  44414. this.endCap = endCap;
  44415. this.closed = closed;
  44416. }
  44417. Object.defineProperty(Lines2D, "NoCap", {
  44418. /**
  44419. * No Cap to apply on the extremity
  44420. */
  44421. get: function () { return Lines2D._noCap; },
  44422. enumerable: true,
  44423. configurable: true
  44424. });
  44425. Object.defineProperty(Lines2D, "RoundCap", {
  44426. /**
  44427. * A round cap, will use the line thickness as diameter
  44428. */
  44429. get: function () { return Lines2D._roundCap; },
  44430. enumerable: true,
  44431. configurable: true
  44432. });
  44433. Object.defineProperty(Lines2D, "TriangleCap", {
  44434. /**
  44435. * Creates a triangle at the extremity.
  44436. */
  44437. get: function () { return Lines2D._triangleCap; },
  44438. enumerable: true,
  44439. configurable: true
  44440. });
  44441. Object.defineProperty(Lines2D, "SquareAnchorCap", {
  44442. /**
  44443. * Creates a Square anchor at the extremity, the square size is twice the thickness of the line
  44444. */
  44445. get: function () { return Lines2D._squareAnchorCap; },
  44446. enumerable: true,
  44447. configurable: true
  44448. });
  44449. Object.defineProperty(Lines2D, "RoundAnchorCap", {
  44450. /**
  44451. * Creates a round anchor at the extremity, the diameter is twice the thickness of the line
  44452. */
  44453. get: function () { return Lines2D._roundAnchorCap; },
  44454. enumerable: true,
  44455. configurable: true
  44456. });
  44457. Object.defineProperty(Lines2D, "DiamondAnchorCap", {
  44458. /**
  44459. * Creates a diamond anchor at the extremity.
  44460. */
  44461. get: function () { return Lines2D._diamondAnchorCap; },
  44462. enumerable: true,
  44463. configurable: true
  44464. });
  44465. Object.defineProperty(Lines2D, "ArrowCap", {
  44466. /**
  44467. * Creates an arrow anchor at the extremity. the arrow base size is twice the thickness of the line
  44468. */
  44469. get: function () { return Lines2D._arrowCap; },
  44470. enumerable: true,
  44471. configurable: true
  44472. });
  44473. Object.defineProperty(Lines2D.prototype, "points", {
  44474. get: function () {
  44475. return this._points;
  44476. },
  44477. set: function (value) {
  44478. this._points = value;
  44479. this._boundingBoxDirty();
  44480. },
  44481. enumerable: true,
  44482. configurable: true
  44483. });
  44484. Object.defineProperty(Lines2D.prototype, "fillThickness", {
  44485. get: function () {
  44486. return this._fillThickness;
  44487. },
  44488. set: function (value) {
  44489. this._fillThickness = value;
  44490. },
  44491. enumerable: true,
  44492. configurable: true
  44493. });
  44494. Object.defineProperty(Lines2D.prototype, "closed", {
  44495. get: function () {
  44496. return this._closed;
  44497. },
  44498. set: function (value) {
  44499. this._closed = value;
  44500. },
  44501. enumerable: true,
  44502. configurable: true
  44503. });
  44504. Object.defineProperty(Lines2D.prototype, "startCap", {
  44505. get: function () {
  44506. return this._startCap;
  44507. },
  44508. set: function (value) {
  44509. this._startCap = value;
  44510. },
  44511. enumerable: true,
  44512. configurable: true
  44513. });
  44514. Object.defineProperty(Lines2D.prototype, "endCap", {
  44515. get: function () {
  44516. return this._endCap;
  44517. },
  44518. set: function (value) {
  44519. this._endCap = value;
  44520. },
  44521. enumerable: true,
  44522. configurable: true
  44523. });
  44524. Lines2D.prototype.levelIntersect = function (intersectInfo) {
  44525. var _this = this;
  44526. if (this._contour == null) {
  44527. this._computeLines2D();
  44528. }
  44529. var pl = this.points.length;
  44530. var l = this.closed ? pl + 1 : pl;
  44531. var p = intersectInfo._localPickPosition;
  44532. this.transformPointWithOriginToRef(this._contour[0], null, Lines2D._prevA);
  44533. this.transformPointWithOriginToRef(this._contour[1], null, Lines2D._prevB);
  44534. for (var i = 1; i < l; i++) {
  44535. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 0], null, Lines2D._curA);
  44536. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 1], null, Lines2D._curB);
  44537. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curA)) {
  44538. return true;
  44539. }
  44540. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._curA, Lines2D._prevB, Lines2D._curB)) {
  44541. return true;
  44542. }
  44543. Lines2D._prevA.x = Lines2D._curA.x;
  44544. Lines2D._prevA.y = Lines2D._curA.y;
  44545. Lines2D._prevB.x = Lines2D._curB.x;
  44546. Lines2D._prevB.y = Lines2D._curB.y;
  44547. }
  44548. var capIntersect = function (tri, points) {
  44549. var l = tri.length;
  44550. for (var i = 0; i < l; i += 3) {
  44551. Lines2D._curA.x = points[tri[i + 0] * 2 + 0];
  44552. Lines2D._curA.y = points[tri[i + 0] * 2 + 1];
  44553. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._curB);
  44554. Lines2D._curA.x = points[tri[i + 1] * 2 + 0];
  44555. Lines2D._curA.y = points[tri[i + 1] * 2 + 1];
  44556. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevA);
  44557. Lines2D._curA.x = points[tri[i + 2] * 2 + 0];
  44558. Lines2D._curA.y = points[tri[i + 2] * 2 + 1];
  44559. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevB);
  44560. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curB)) {
  44561. return true;
  44562. }
  44563. }
  44564. return false;
  44565. };
  44566. if (this._startCapTriIndices) {
  44567. if (capIntersect(this._startCapTriIndices, this._startCapContour)) {
  44568. return true;
  44569. }
  44570. if (capIntersect(this._endCapTriIndices, this._endCapContour)) {
  44571. return true;
  44572. }
  44573. }
  44574. return false;
  44575. };
  44576. Object.defineProperty(Lines2D.prototype, "boundingMin", {
  44577. get: function () {
  44578. if (!this._boundingMin) {
  44579. this._computeLines2D();
  44580. }
  44581. return this._boundingMin;
  44582. },
  44583. enumerable: true,
  44584. configurable: true
  44585. });
  44586. Object.defineProperty(Lines2D.prototype, "boundingMax", {
  44587. get: function () {
  44588. if (!this._boundingMax) {
  44589. this._computeLines2D();
  44590. }
  44591. return this._boundingMax;
  44592. },
  44593. enumerable: true,
  44594. configurable: true
  44595. });
  44596. Lines2D.prototype.getUsedShaderCategories = function (dataPart) {
  44597. var res = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  44598. // Remove the BORDER category, we don't use it in the VertexShader
  44599. var i = res.indexOf(BABYLON.Shape2D.SHAPE2D_CATEGORY_BORDER);
  44600. if (i !== -1) {
  44601. res.splice(i, 1);
  44602. }
  44603. return res;
  44604. };
  44605. Lines2D.prototype.updateLevelBoundingInfo = function () {
  44606. if (!this._boundingMin) {
  44607. this._computeLines2D();
  44608. }
  44609. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(this._boundingMin.x, this._boundingMax.x, this._boundingMin.y, this._boundingMax.y, this._levelBoundingInfo);
  44610. };
  44611. Lines2D.prototype.createModelRenderCache = function (modelKey) {
  44612. var renderCache = new Lines2DRenderCache(this.owner.engine, modelKey);
  44613. return renderCache;
  44614. };
  44615. ///////////////////////////////////////////////////////////////////////////////////
  44616. // Methods for Lines building
  44617. Lines2D.prototype._perp = function (v, res) {
  44618. res.x = v.y;
  44619. res.y = -v.x;
  44620. };
  44621. ;
  44622. Lines2D.prototype._direction = function (a, b, res) {
  44623. a.subtractToRef(b, res);
  44624. res.normalize();
  44625. };
  44626. Lines2D.prototype._computeMiter = function (tangent, miter, a, b) {
  44627. a.addToRef(b, tangent);
  44628. tangent.normalize();
  44629. miter.x = -tangent.y;
  44630. miter.y = tangent.x;
  44631. Lines2D._miterTps.x = -a.y;
  44632. Lines2D._miterTps.y = a.x;
  44633. return 1 / BABYLON.Vector2.Dot(miter, Lines2D._miterTps);
  44634. };
  44635. Lines2D.prototype._intersect = function (x1, y1, x2, y2, x3, y3, x4, y4) {
  44636. var d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  44637. if (d === 0)
  44638. return false;
  44639. var xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; // Intersection point is xi/yi, just in case...
  44640. //let yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; // That's why I left it commented
  44641. if (xi < Math.min(x1, x2) || xi > Math.max(x1, x2))
  44642. return false;
  44643. if (xi < Math.min(x3, x4) || xi > Math.max(x3, x4))
  44644. return false;
  44645. return true;
  44646. };
  44647. Lines2D.prototype._updateMinMax = function (array, offset) {
  44648. if (offset >= array.length) {
  44649. return;
  44650. }
  44651. this._boundingMin.x = Math.min(this._boundingMin.x, array[offset]);
  44652. this._boundingMax.x = Math.max(this._boundingMax.x, array[offset]);
  44653. this._boundingMin.y = Math.min(this._boundingMin.y, array[offset + 1]);
  44654. this._boundingMax.y = Math.max(this._boundingMax.y, array[offset + 1]);
  44655. };
  44656. Lines2D.prototype._store = function (array, contour, index, max, p, n, halfThickness, borderThickness, detectFlip) {
  44657. var borderMode = borderThickness != null && !isNaN(borderThickness);
  44658. var off = index * (borderMode ? 8 : 4);
  44659. // 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)
  44660. if (off >= array.length) {
  44661. return;
  44662. }
  44663. // Store start/end normal, we need it for the cap construction
  44664. if (index === 0) {
  44665. this._perp(n, Lines2D._startDir);
  44666. }
  44667. else if (index === max - 1) {
  44668. this._perp(n, Lines2D._endDir);
  44669. Lines2D._endDir.x *= -1;
  44670. Lines2D._endDir.y *= -1;
  44671. }
  44672. var swap = false;
  44673. array[off + 0] = p.x + n.x * halfThickness;
  44674. array[off + 1] = p.y + n.y * halfThickness;
  44675. array[off + 2] = p.x + n.x * -halfThickness;
  44676. array[off + 3] = p.y + n.y * -halfThickness;
  44677. this._updateMinMax(array, off);
  44678. this._updateMinMax(array, off + 2);
  44679. // If an index is given we check if the two segments formed between [index+0;detectFlip+0] and [index+2;detectFlip+2] intersect themselves.
  44680. // 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
  44681. if (detectFlip !== undefined) {
  44682. // Flip if intersect
  44683. var flipOff = detectFlip * (borderMode ? 8 : 4);
  44684. 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])) {
  44685. swap = true;
  44686. var tps = array[off + 0];
  44687. array[off + 0] = array[off + 2];
  44688. array[off + 2] = tps;
  44689. tps = array[off + 1];
  44690. array[off + 1] = array[off + 3];
  44691. array[off + 3] = tps;
  44692. }
  44693. }
  44694. if (borderMode) {
  44695. var t = halfThickness + borderThickness;
  44696. array[off + 4] = p.x + n.x * (swap ? -t : t);
  44697. array[off + 5] = p.y + n.y * (swap ? -t : t);
  44698. array[off + 6] = p.x + n.x * (swap ? t : -t);
  44699. array[off + 7] = p.y + n.y * (swap ? t : -t);
  44700. this._updateMinMax(array, off + 4);
  44701. this._updateMinMax(array, off + 6);
  44702. }
  44703. if (contour) {
  44704. off += borderMode ? 4 : 0;
  44705. contour.push(new BABYLON.Vector2(array[off + 0], array[off + 1]));
  44706. contour.push(new BABYLON.Vector2(array[off + 2], array[off + 3]));
  44707. }
  44708. };
  44709. Lines2D.prototype._getCapSize = function (type, border) {
  44710. if (border === void 0) { border = false; }
  44711. var sd = Lines2D._roundCapSubDiv;
  44712. // If no array given, we call this to get the size
  44713. var vbsize = 0, ibsize = 0;
  44714. switch (type) {
  44715. case Lines2D.NoCap:
  44716. {
  44717. // If the line is not close and we're computing border, we add the size to generate the edge border
  44718. if (!this.closed && border) {
  44719. vbsize = 4;
  44720. ibsize = 6;
  44721. }
  44722. else {
  44723. vbsize = ibsize = 0;
  44724. }
  44725. break;
  44726. }
  44727. case Lines2D.RoundCap:
  44728. {
  44729. if (border) {
  44730. vbsize = sd;
  44731. ibsize = (sd - 2) * 3;
  44732. }
  44733. else {
  44734. vbsize = (sd / 2) + 1;
  44735. ibsize = (sd / 2) * 3;
  44736. }
  44737. break;
  44738. }
  44739. case Lines2D.ArrowCap:
  44740. {
  44741. if (border) {
  44742. vbsize = 12;
  44743. ibsize = 24;
  44744. }
  44745. else {
  44746. vbsize = 3;
  44747. ibsize = 3;
  44748. }
  44749. break;
  44750. }
  44751. case Lines2D.TriangleCap:
  44752. {
  44753. if (border) {
  44754. vbsize = 6;
  44755. ibsize = 12;
  44756. }
  44757. else {
  44758. vbsize = 3;
  44759. ibsize = 3;
  44760. }
  44761. break;
  44762. }
  44763. case Lines2D.DiamondAnchorCap:
  44764. {
  44765. if (border) {
  44766. vbsize = 10;
  44767. ibsize = 24;
  44768. }
  44769. else {
  44770. vbsize = 5;
  44771. ibsize = 9;
  44772. }
  44773. break;
  44774. }
  44775. case Lines2D.SquareAnchorCap:
  44776. {
  44777. if (border) {
  44778. vbsize = 12;
  44779. ibsize = 30;
  44780. }
  44781. else {
  44782. vbsize = 4;
  44783. ibsize = 6;
  44784. }
  44785. break;
  44786. }
  44787. case Lines2D.RoundAnchorCap:
  44788. {
  44789. if (border) {
  44790. vbsize = sd * 2;
  44791. ibsize = (sd - 1) * 6;
  44792. }
  44793. else {
  44794. vbsize = sd + 1;
  44795. ibsize = (sd + 1) * 3;
  44796. }
  44797. break;
  44798. }
  44799. }
  44800. return { vbsize: vbsize * 2, ibsize: ibsize };
  44801. };
  44802. Lines2D.prototype._storeVertex = function (vb, baseOffset, index, basePos, rotation, vertex, contour) {
  44803. var c = Math.cos(rotation);
  44804. var s = Math.sin(rotation);
  44805. Lines2D._tpsV.x = (c * vertex.x) + (-s * vertex.y) + basePos.x;
  44806. Lines2D._tpsV.y = (s * vertex.x) + (c * vertex.y) + basePos.y;
  44807. var offset = baseOffset + (index * 2);
  44808. vb[offset + 0] = Lines2D._tpsV.x;
  44809. vb[offset + 1] = Lines2D._tpsV.y;
  44810. if (contour) {
  44811. contour.push(Lines2D._tpsV.x);
  44812. contour.push(Lines2D._tpsV.y);
  44813. }
  44814. this._updateMinMax(vb, offset);
  44815. return (baseOffset + index * 2) / 2;
  44816. };
  44817. Lines2D.prototype._storeIndex = function (ib, baseOffset, index, vertexIndex) {
  44818. ib[baseOffset + index] = vertexIndex;
  44819. };
  44820. Lines2D.prototype._buildCap = function (vb, vbi, ib, ibi, pos, thickness, borderThickness, type, capDir, contour) {
  44821. // 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
  44822. var sd = Lines2D._roundCapSubDiv;
  44823. var dir = new BABYLON.Vector2(1, 0);
  44824. var angle = Math.atan2(capDir.y, capDir.x) - Math.atan2(dir.y, dir.x);
  44825. var ht = thickness / 2;
  44826. var t = thickness;
  44827. var borderMode = borderThickness != null;
  44828. var bt = borderThickness;
  44829. switch (type) {
  44830. case Lines2D.NoCap:
  44831. if (borderMode && !this.closed) {
  44832. var vi = 0;
  44833. var ii = 0;
  44834. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), contour);
  44835. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, ht + bt), contour);
  44836. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, -(ht + bt)), contour);
  44837. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), contour);
  44838. this._storeIndex(ib, ibi, ii++, v1);
  44839. this._storeIndex(ib, ibi, ii++, v2);
  44840. this._storeIndex(ib, ibi, ii++, v3);
  44841. this._storeIndex(ib, ibi, ii++, v1);
  44842. this._storeIndex(ib, ibi, ii++, v3);
  44843. this._storeIndex(ib, ibi, ii++, v4);
  44844. }
  44845. break;
  44846. case Lines2D.ArrowCap:
  44847. ht *= 2;
  44848. case Lines2D.TriangleCap:
  44849. {
  44850. if (borderMode) {
  44851. var f = type === Lines2D.TriangleCap ? bt : Math.sqrt(bt * bt * 2);
  44852. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), null);
  44853. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), null);
  44854. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), null);
  44855. var v4 = this._storeVertex(vb, vbi, 3, pos, angle, new BABYLON.Vector2(0, ht + f), contour);
  44856. var v5 = this._storeVertex(vb, vbi, 4, pos, angle, new BABYLON.Vector2(ht + f, 0), contour);
  44857. var v6 = this._storeVertex(vb, vbi, 5, pos, angle, new BABYLON.Vector2(0, -(ht + f)), contour);
  44858. var ii = 0;
  44859. this._storeIndex(ib, ibi, ii++, v1);
  44860. this._storeIndex(ib, ibi, ii++, v4);
  44861. this._storeIndex(ib, ibi, ii++, v5);
  44862. this._storeIndex(ib, ibi, ii++, v1);
  44863. this._storeIndex(ib, ibi, ii++, v5);
  44864. this._storeIndex(ib, ibi, ii++, v2);
  44865. this._storeIndex(ib, ibi, ii++, v6);
  44866. this._storeIndex(ib, ibi, ii++, v3);
  44867. this._storeIndex(ib, ibi, ii++, v2);
  44868. this._storeIndex(ib, ibi, ii++, v6);
  44869. this._storeIndex(ib, ibi, ii++, v2);
  44870. this._storeIndex(ib, ibi, ii++, v5);
  44871. if (type === Lines2D.ArrowCap) {
  44872. var rht = thickness / 2;
  44873. var v10 = this._storeVertex(vb, vbi, 9, pos, angle, new BABYLON.Vector2(0, -(rht + bt)), null);
  44874. var v12 = this._storeVertex(vb, vbi, 11, pos, angle, new BABYLON.Vector2(-bt, -(ht + f)), contour);
  44875. var v11 = this._storeVertex(vb, vbi, 10, pos, angle, new BABYLON.Vector2(-bt, -(rht + bt)), contour);
  44876. var v7 = this._storeVertex(vb, vbi, 6, pos, angle, new BABYLON.Vector2(0, rht + bt), null);
  44877. var v8 = this._storeVertex(vb, vbi, 7, pos, angle, new BABYLON.Vector2(-bt, rht + bt), contour);
  44878. var v9 = this._storeVertex(vb, vbi, 8, pos, angle, new BABYLON.Vector2(-bt, ht + f), contour);
  44879. this._storeIndex(ib, ibi, ii++, v7);
  44880. this._storeIndex(ib, ibi, ii++, v8);
  44881. this._storeIndex(ib, ibi, ii++, v9);
  44882. this._storeIndex(ib, ibi, ii++, v7);
  44883. this._storeIndex(ib, ibi, ii++, v9);
  44884. this._storeIndex(ib, ibi, ii++, v4);
  44885. this._storeIndex(ib, ibi, ii++, v10);
  44886. this._storeIndex(ib, ibi, ii++, v12);
  44887. this._storeIndex(ib, ibi, ii++, v11);
  44888. this._storeIndex(ib, ibi, ii++, v10);
  44889. this._storeIndex(ib, ibi, ii++, v6);
  44890. this._storeIndex(ib, ibi, ii++, v12);
  44891. }
  44892. }
  44893. else {
  44894. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), contour);
  44895. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), contour);
  44896. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), contour);
  44897. this._storeIndex(ib, ibi, 0, v1);
  44898. this._storeIndex(ib, ibi, 1, v2);
  44899. this._storeIndex(ib, ibi, 2, v3);
  44900. }
  44901. break;
  44902. }
  44903. case Lines2D.RoundCap:
  44904. {
  44905. if (borderMode) {
  44906. var curA = -Math.PI / 2;
  44907. var incA = Math.PI / (sd / 2 - 1);
  44908. var ii = 0;
  44909. for (var i = 0; i < (sd / 2); i++) {
  44910. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  44911. 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);
  44912. if (i > 0) {
  44913. this._storeIndex(ib, ibi, ii++, v1 - 2);
  44914. this._storeIndex(ib, ibi, ii++, v2 - 2);
  44915. this._storeIndex(ib, ibi, ii++, v2);
  44916. this._storeIndex(ib, ibi, ii++, v1 - 2);
  44917. this._storeIndex(ib, ibi, ii++, v2);
  44918. this._storeIndex(ib, ibi, ii++, v1);
  44919. }
  44920. curA += incA;
  44921. }
  44922. }
  44923. else {
  44924. var c = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, 0), null);
  44925. var curA = -Math.PI / 2;
  44926. var incA = Math.PI / (sd / 2 - 1);
  44927. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  44928. curA += incA;
  44929. for (var i = 1; i < (sd / 2); i++) {
  44930. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), contour);
  44931. this._storeIndex(ib, ibi, i * 3 + 0, c);
  44932. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  44933. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  44934. curA += incA;
  44935. }
  44936. }
  44937. break;
  44938. }
  44939. case Lines2D.SquareAnchorCap:
  44940. {
  44941. var vi = 0;
  44942. var c = borderMode ? null : contour;
  44943. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, t), c);
  44944. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, t), c);
  44945. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, -t), c);
  44946. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -t), c);
  44947. if (borderMode) {
  44948. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), null);
  44949. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, ht + bt), contour);
  44950. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, t + bt), contour);
  44951. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, t + bt), contour);
  44952. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, -(t + bt)), contour);
  44953. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(t + bt)), contour);
  44954. var v11 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(ht + bt)), contour);
  44955. var v12 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), null);
  44956. var ii = 0;
  44957. this._storeIndex(ib, ibi, ii++, v6);
  44958. this._storeIndex(ib, ibi, ii++, v1);
  44959. this._storeIndex(ib, ibi, ii++, v5);
  44960. this._storeIndex(ib, ibi, ii++, v6);
  44961. this._storeIndex(ib, ibi, ii++, v7);
  44962. this._storeIndex(ib, ibi, ii++, v1);
  44963. this._storeIndex(ib, ibi, ii++, v1);
  44964. this._storeIndex(ib, ibi, ii++, v7);
  44965. this._storeIndex(ib, ibi, ii++, v8);
  44966. this._storeIndex(ib, ibi, ii++, v1);
  44967. this._storeIndex(ib, ibi, ii++, v8);
  44968. this._storeIndex(ib, ibi, ii++, v2);
  44969. this._storeIndex(ib, ibi, ii++, v2);
  44970. this._storeIndex(ib, ibi, ii++, v8);
  44971. this._storeIndex(ib, ibi, ii++, v9);
  44972. this._storeIndex(ib, ibi, ii++, v2);
  44973. this._storeIndex(ib, ibi, ii++, v9);
  44974. this._storeIndex(ib, ibi, ii++, v3);
  44975. this._storeIndex(ib, ibi, ii++, v3);
  44976. this._storeIndex(ib, ibi, ii++, v9);
  44977. this._storeIndex(ib, ibi, ii++, v10);
  44978. this._storeIndex(ib, ibi, ii++, v3);
  44979. this._storeIndex(ib, ibi, ii++, v10);
  44980. this._storeIndex(ib, ibi, ii++, v4);
  44981. this._storeIndex(ib, ibi, ii++, v10);
  44982. this._storeIndex(ib, ibi, ii++, v11);
  44983. this._storeIndex(ib, ibi, ii++, v4);
  44984. this._storeIndex(ib, ibi, ii++, v11);
  44985. this._storeIndex(ib, ibi, ii++, v12);
  44986. this._storeIndex(ib, ibi, ii++, v4);
  44987. }
  44988. else {
  44989. this._storeIndex(ib, ibi, 0, v1);
  44990. this._storeIndex(ib, ibi, 1, v2);
  44991. this._storeIndex(ib, ibi, 2, v3);
  44992. this._storeIndex(ib, ibi, 3, v1);
  44993. this._storeIndex(ib, ibi, 4, v3);
  44994. this._storeIndex(ib, ibi, 5, v4);
  44995. }
  44996. break;
  44997. }
  44998. case Lines2D.RoundAnchorCap:
  44999. {
  45000. var cpos = Math.sqrt(t * t - ht * ht);
  45001. var center = new BABYLON.Vector2(cpos, 0);
  45002. var curA = BABYLON.Tools.ToRadians(-150);
  45003. var incA = BABYLON.Tools.ToRadians(300) / (sd - 1);
  45004. if (borderMode) {
  45005. var ii = 0;
  45006. for (var i = 0; i < sd; i++) {
  45007. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  45008. 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);
  45009. if (i > 0) {
  45010. this._storeIndex(ib, ibi, ii++, v1 - 2);
  45011. this._storeIndex(ib, ibi, ii++, v2 - 2);
  45012. this._storeIndex(ib, ibi, ii++, v2);
  45013. this._storeIndex(ib, ibi, ii++, v1 - 2);
  45014. this._storeIndex(ib, ibi, ii++, v2);
  45015. this._storeIndex(ib, ibi, ii++, v1);
  45016. }
  45017. curA += incA;
  45018. }
  45019. }
  45020. else {
  45021. var c = this._storeVertex(vb, vbi, 0, pos, angle, center, null);
  45022. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  45023. curA += incA;
  45024. for (var i = 1; i < sd; i++) {
  45025. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), contour);
  45026. this._storeIndex(ib, ibi, i * 3 + 0, c);
  45027. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  45028. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  45029. curA += incA;
  45030. }
  45031. this._storeIndex(ib, ibi, sd * 3 + 0, c);
  45032. this._storeIndex(ib, ibi, sd * 3 + 1, c + 1);
  45033. this._storeIndex(ib, ibi, sd * 3 + 2, c + sd);
  45034. }
  45035. break;
  45036. }
  45037. case Lines2D.DiamondAnchorCap:
  45038. {
  45039. var vi = 0;
  45040. var c = borderMode ? null : contour;
  45041. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht), c);
  45042. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t), c);
  45043. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3, 0), c);
  45044. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -t), c);
  45045. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -ht), c);
  45046. if (borderMode) {
  45047. var f = Math.sqrt(bt * bt * 2);
  45048. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, ht), contour);
  45049. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t + f), contour);
  45050. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3 + f, 0), contour);
  45051. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -(t + f)), contour);
  45052. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, -ht), contour);
  45053. var ii = 0;
  45054. this._storeIndex(ib, ibi, ii++, v6);
  45055. this._storeIndex(ib, ibi, ii++, v7);
  45056. this._storeIndex(ib, ibi, ii++, v1);
  45057. this._storeIndex(ib, ibi, ii++, v1);
  45058. this._storeIndex(ib, ibi, ii++, v7);
  45059. this._storeIndex(ib, ibi, ii++, v2);
  45060. this._storeIndex(ib, ibi, ii++, v2);
  45061. this._storeIndex(ib, ibi, ii++, v7);
  45062. this._storeIndex(ib, ibi, ii++, v8);
  45063. this._storeIndex(ib, ibi, ii++, v2);
  45064. this._storeIndex(ib, ibi, ii++, v8);
  45065. this._storeIndex(ib, ibi, ii++, v3);
  45066. this._storeIndex(ib, ibi, ii++, v3);
  45067. this._storeIndex(ib, ibi, ii++, v8);
  45068. this._storeIndex(ib, ibi, ii++, v9);
  45069. this._storeIndex(ib, ibi, ii++, v3);
  45070. this._storeIndex(ib, ibi, ii++, v9);
  45071. this._storeIndex(ib, ibi, ii++, v4);
  45072. this._storeIndex(ib, ibi, ii++, v4);
  45073. this._storeIndex(ib, ibi, ii++, v9);
  45074. this._storeIndex(ib, ibi, ii++, v10);
  45075. this._storeIndex(ib, ibi, ii++, v4);
  45076. this._storeIndex(ib, ibi, ii++, v10);
  45077. this._storeIndex(ib, ibi, ii++, v5);
  45078. }
  45079. else {
  45080. this._storeIndex(ib, ibi, 0, v1);
  45081. this._storeIndex(ib, ibi, 1, v2);
  45082. this._storeIndex(ib, ibi, 2, v3);
  45083. this._storeIndex(ib, ibi, 3, v1);
  45084. this._storeIndex(ib, ibi, 4, v3);
  45085. this._storeIndex(ib, ibi, 5, v5);
  45086. this._storeIndex(ib, ibi, 6, v5);
  45087. this._storeIndex(ib, ibi, 7, v3);
  45088. this._storeIndex(ib, ibi, 8, v4);
  45089. }
  45090. break;
  45091. }
  45092. }
  45093. return null;
  45094. };
  45095. Lines2D.prototype._buildLine = function (vb, contour, ht, bt) {
  45096. var lineA = BABYLON.Vector2.Zero();
  45097. var lineB = BABYLON.Vector2.Zero();
  45098. var tangent = BABYLON.Vector2.Zero();
  45099. var miter = BABYLON.Vector2.Zero();
  45100. var curNormal = null;
  45101. if (this.closed) {
  45102. this.points.push(this.points[0]);
  45103. }
  45104. var total = this.points.length;
  45105. for (var i = 1; i < total; i++) {
  45106. var last = this.points[i - 1];
  45107. var cur = this.points[i];
  45108. var next = (i < (this.points.length - 1)) ? this.points[i + 1] : null;
  45109. this._direction(cur, last, lineA);
  45110. if (!curNormal) {
  45111. curNormal = BABYLON.Vector2.Zero();
  45112. this._perp(lineA, curNormal);
  45113. }
  45114. if (i === 1) {
  45115. this._store(vb, contour, 0, total, this.points[0], curNormal, ht, bt);
  45116. }
  45117. if (!next) {
  45118. this._perp(lineA, curNormal);
  45119. this._store(vb, contour, i, total, this.points[i], curNormal, ht, bt, i - 1);
  45120. }
  45121. else {
  45122. this._direction(next, cur, lineB);
  45123. var miterLen = this._computeMiter(tangent, miter, lineA, lineB);
  45124. this._store(vb, contour, i, total, this.points[i], miter, miterLen * ht, miterLen * bt, i - 1);
  45125. }
  45126. }
  45127. if (this.points.length > 2 && this.closed) {
  45128. var last2 = this.points[total - 2];
  45129. var cur2 = this.points[0];
  45130. var next2 = this.points[1];
  45131. this._direction(cur2, last2, lineA);
  45132. this._direction(next2, cur2, lineB);
  45133. this._perp(lineA, curNormal);
  45134. var miterLen2 = this._computeMiter(tangent, miter, lineA, lineB);
  45135. this._store(vb, null, 0, total, this.points[0], miter, miterLen2 * ht, miterLen2 * bt, 1);
  45136. // Patch contour
  45137. if (contour) {
  45138. var off = (bt == null) ? 0 : 4;
  45139. contour[0].x = vb[off + 0];
  45140. contour[0].y = vb[off + 1];
  45141. contour[1].x = vb[off + 2];
  45142. contour[1].y = vb[off + 3];
  45143. }
  45144. }
  45145. // Remove the point we added at the beginning
  45146. if (this.closed) {
  45147. this.points.splice(total - 1);
  45148. }
  45149. };
  45150. // Methods for Lines building
  45151. ///////////////////////////////////////////////////////////////////////////////////
  45152. Lines2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  45153. var renderCache = modelRenderCache;
  45154. var engine = this.owner.engine;
  45155. if (this._fillVB === null) {
  45156. this._computeLines2D();
  45157. }
  45158. // Need to create WebGL resources for fill part?
  45159. if (this.fill) {
  45160. renderCache.fillVB = engine.createVertexBuffer(this._fillVB);
  45161. renderCache.fillIB = engine.createIndexBuffer(this._fillIB);
  45162. renderCache.fillIndicesCount = this._fillIB.length;
  45163. // 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
  45164. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], true);
  45165. if (ei) {
  45166. renderCache.effectFillInstanced = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45167. }
  45168. // Get the non instanced version
  45169. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], false);
  45170. renderCache.effectFill = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45171. }
  45172. // Need to create WebGL resources for border part?
  45173. if (this.border) {
  45174. renderCache.borderVB = engine.createVertexBuffer(this._borderVB);
  45175. renderCache.borderIB = engine.createIndexBuffer(this._borderIB);
  45176. renderCache.borderIndicesCount = this._borderIB.length;
  45177. // 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
  45178. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], true);
  45179. if (ei) {
  45180. renderCache.effectBorderInstanced = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  45181. }
  45182. // Get the non instanced version
  45183. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], false);
  45184. renderCache.effectBorder = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  45185. }
  45186. this._fillVB = null;
  45187. this._fillIB = null;
  45188. this._borderVB = null;
  45189. this._borderIB = null;
  45190. return renderCache;
  45191. };
  45192. Lines2D.prototype._computeLines2D = function () {
  45193. // Init min/max because their being computed here
  45194. this._boundingMin = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  45195. this._boundingMax = new BABYLON.Vector2(Number.MIN_VALUE, Number.MIN_VALUE);
  45196. var contour = new Array();
  45197. var startCapContour = new Array();
  45198. var endCapContour = new Array();
  45199. // Need to create WebGL resources for fill part?
  45200. if (this.fill) {
  45201. var startCapInfo = this._getCapSize(this.startCap);
  45202. var endCapInfo = this._getCapSize(this.endCap);
  45203. var count = this.points.length;
  45204. var vbSize = (count * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  45205. this._fillVB = new Float32Array(vbSize);
  45206. var vb = this._fillVB;
  45207. var ht = this.fillThickness / 2;
  45208. var total = this.points.length;
  45209. this._buildLine(vb, this.border ? null : contour, ht);
  45210. var max = total * 2;
  45211. var triCount = (count - (this.closed ? 0 : 1)) * 2;
  45212. this._fillIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  45213. var ib = this._fillIB;
  45214. for (var i = 0; i < triCount; i += 2) {
  45215. ib[i * 3 + 0] = i + 0;
  45216. ib[i * 3 + 1] = i + 1;
  45217. ib[i * 3 + 2] = (i + 2) % max;
  45218. ib[i * 3 + 3] = i + 1;
  45219. ib[i * 3 + 4] = (i + 3) % max;
  45220. ib[i * 3 + 5] = (i + 2) % max;
  45221. }
  45222. this._buildCap(vb, count * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, null, this.startCap, Lines2D._startDir, this.border ? null : startCapContour);
  45223. 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);
  45224. }
  45225. // Need to create WebGL resources for border part?
  45226. if (this.border) {
  45227. var startCapInfo = this._getCapSize(this.startCap, true);
  45228. var endCapInfo = this._getCapSize(this.endCap, true);
  45229. var count = this.points.length;
  45230. var vbSize = (count * 2 * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  45231. this._borderVB = new Float32Array(vbSize);
  45232. var vb = this._borderVB;
  45233. var ht = this.fillThickness / 2;
  45234. var bt = this.borderThickness;
  45235. var total = this.points.length;
  45236. this._buildLine(vb, contour, ht, bt);
  45237. var max = total * 2 * 2;
  45238. var triCount = (count - (this.closed ? 0 : 1)) * 2 * 2;
  45239. this._borderIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  45240. var ib = this._borderIB;
  45241. for (var i = 0; i < triCount; i += 4) {
  45242. ib[i * 3 + 0] = i + 0;
  45243. ib[i * 3 + 1] = i + 2;
  45244. ib[i * 3 + 2] = (i + 6) % max;
  45245. ib[i * 3 + 3] = i + 0;
  45246. ib[i * 3 + 4] = (i + 6) % max;
  45247. ib[i * 3 + 5] = (i + 4) % max;
  45248. ib[i * 3 + 6] = i + 3;
  45249. ib[i * 3 + 7] = i + 1;
  45250. ib[i * 3 + 8] = (i + 5) % max;
  45251. ib[i * 3 + 9] = i + 3;
  45252. ib[i * 3 + 10] = (i + 5) % max;
  45253. ib[i * 3 + 11] = (i + 7) % max;
  45254. }
  45255. this._buildCap(vb, count * 2 * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, this.borderThickness, this.startCap, Lines2D._startDir, startCapContour);
  45256. 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);
  45257. }
  45258. this._contour = contour;
  45259. if (startCapContour.length > 0) {
  45260. var startCapTri = Earcut.earcut(startCapContour, null, 2);
  45261. this._startCapTriIndices = startCapTri;
  45262. this._startCapContour = startCapContour;
  45263. }
  45264. if (endCapContour.length > 0) {
  45265. var endCapTri = Earcut.earcut(endCapContour, null, 2);
  45266. this._endCapContour = endCapContour;
  45267. this._endCapTriIndices = endCapTri;
  45268. }
  45269. var bs = this._boundingMax.subtract(this._boundingMin);
  45270. this._size.width = bs.x;
  45271. this._size.height = bs.y;
  45272. };
  45273. Object.defineProperty(Lines2D.prototype, "size", {
  45274. get: function () {
  45275. if (this._size == null) {
  45276. this._computeLines2D();
  45277. }
  45278. return this._size;
  45279. },
  45280. enumerable: true,
  45281. configurable: true
  45282. });
  45283. Lines2D.prototype.createInstanceDataParts = function () {
  45284. var res = new Array();
  45285. if (this.border) {
  45286. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  45287. }
  45288. if (this.fill) {
  45289. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  45290. }
  45291. return res;
  45292. };
  45293. Lines2D.prototype.refreshInstanceDataPart = function (part) {
  45294. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  45295. return false;
  45296. }
  45297. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  45298. var d = part;
  45299. if (this.border instanceof BABYLON.GradientColorBrush2D) {
  45300. d.boundingMin = this.boundingMin;
  45301. d.boundingMax = this.boundingMax;
  45302. }
  45303. }
  45304. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  45305. var d = part;
  45306. if (this.fill instanceof BABYLON.GradientColorBrush2D) {
  45307. d.boundingMin = this.boundingMin;
  45308. d.boundingMax = this.boundingMax;
  45309. }
  45310. }
  45311. return true;
  45312. };
  45313. Lines2D._prevA = BABYLON.Vector2.Zero();
  45314. Lines2D._prevB = BABYLON.Vector2.Zero();
  45315. Lines2D._curA = BABYLON.Vector2.Zero();
  45316. Lines2D._curB = BABYLON.Vector2.Zero();
  45317. Lines2D._miterTps = BABYLON.Vector2.Zero();
  45318. Lines2D._startDir = BABYLON.Vector2.Zero();
  45319. Lines2D._endDir = BABYLON.Vector2.Zero();
  45320. Lines2D._tpsV = BABYLON.Vector2.Zero();
  45321. Lines2D._noCap = 0;
  45322. Lines2D._roundCap = 1;
  45323. Lines2D._triangleCap = 2;
  45324. Lines2D._squareAnchorCap = 3;
  45325. Lines2D._roundAnchorCap = 4;
  45326. Lines2D._diamondAnchorCap = 5;
  45327. Lines2D._arrowCap = 6;
  45328. Lines2D._roundCapSubDiv = 36;
  45329. __decorate([
  45330. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Lines2D.pointsProperty = pi; })
  45331. ], Lines2D.prototype, "points", null);
  45332. __decorate([
  45333. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Lines2D.fillThicknessProperty = pi; })
  45334. ], Lines2D.prototype, "fillThickness", null);
  45335. __decorate([
  45336. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Lines2D.closedProperty = pi; })
  45337. ], Lines2D.prototype, "closed", null);
  45338. __decorate([
  45339. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 4, function (pi) { return Lines2D.startCapProperty = pi; })
  45340. ], Lines2D.prototype, "startCap", null);
  45341. __decorate([
  45342. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 5, function (pi) { return Lines2D.endCapProperty = pi; })
  45343. ], Lines2D.prototype, "endCap", null);
  45344. Lines2D = __decorate([
  45345. BABYLON.className("Lines2D")
  45346. ], Lines2D);
  45347. return Lines2D;
  45348. }(BABYLON.Shape2D));
  45349. BABYLON.Lines2D = Lines2D;
  45350. })(BABYLON || (BABYLON = {}));
  45351. var BABYLON;
  45352. (function (BABYLON) {
  45353. // This class contains data that lifetime is bounding to the Babylon Engine object
  45354. var Canvas2DEngineBoundData = (function () {
  45355. function Canvas2DEngineBoundData() {
  45356. this._modelCache = new BABYLON.StringDictionary();
  45357. }
  45358. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  45359. return this._modelCache.getOrAddWithFactory(key, factory);
  45360. };
  45361. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  45362. if (!modelRenderCache.isDisposed) {
  45363. return false;
  45364. }
  45365. this._modelCache.remove(modelRenderCache.modelKey);
  45366. return true;
  45367. };
  45368. return Canvas2DEngineBoundData;
  45369. }());
  45370. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  45371. var Canvas2D = (function (_super) {
  45372. __extends(Canvas2D, _super);
  45373. function Canvas2D(scene, settings) {
  45374. var _this = this;
  45375. _super.call(this, settings);
  45376. /**
  45377. * 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.
  45378. * Beware that you have to take under consideration the origin in your calculations! Good luck!
  45379. */
  45380. this.worldSpaceToNodeLocal = function (worldPos) {
  45381. var node = _this._worldSpaceNode;
  45382. if (!node) {
  45383. return;
  45384. }
  45385. var mtx = node.getWorldMatrix().clone();
  45386. mtx.invert();
  45387. var v = BABYLON.Vector3.TransformCoordinates(worldPos, mtx);
  45388. var res = new BABYLON.Vector2(v.x, v.y);
  45389. var size = _this.actualSize;
  45390. res.x += size.width * 0.5; // res is centered, make it relative to bottom/left
  45391. res.y += size.height * 0.5;
  45392. return res;
  45393. };
  45394. /**
  45395. * 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
  45396. */
  45397. this.worldSpaceCacheChanged = function () {
  45398. var plane = _this.worldSpaceCanvasNode;
  45399. var vd = BABYLON.VertexData.ExtractFromMesh(plane); //new VertexData();
  45400. vd.uvs = new Float32Array(8);
  45401. var material = plane.material;
  45402. var tex = _this._renderableData._cacheTexture;
  45403. if (material.diffuseTexture !== tex) {
  45404. material.diffuseTexture = tex;
  45405. tex.hasAlpha = true;
  45406. }
  45407. var nodeuv = _this._renderableData._cacheNodeUVs;
  45408. for (var i = 0; i < 4; i++) {
  45409. vd.uvs[i * 2 + 0] = nodeuv[i].x;
  45410. vd.uvs[i * 2 + 1] = nodeuv[i].y;
  45411. }
  45412. vd.applyToMesh(plane);
  45413. };
  45414. this._notifDebugMode = false;
  45415. this._mapCounter = 0;
  45416. this._drawCallsOpaqueCounter = new BABYLON.PerfCounter();
  45417. this._drawCallsAlphaTestCounter = new BABYLON.PerfCounter();
  45418. this._drawCallsTransparentCounter = new BABYLON.PerfCounter();
  45419. this._groupRenderCounter = new BABYLON.PerfCounter();
  45420. this._updateTransparentDataCounter = new BABYLON.PerfCounter();
  45421. this._cachedGroupRenderCounter = new BABYLON.PerfCounter();
  45422. this._updateCachedStateCounter = new BABYLON.PerfCounter();
  45423. this._updateLayoutCounter = new BABYLON.PerfCounter();
  45424. this._updatePositioningCounter = new BABYLON.PerfCounter();
  45425. this._updateLocalTransformCounter = new BABYLON.PerfCounter();
  45426. this._updateGlobalTransformCounter = new BABYLON.PerfCounter();
  45427. this._boundingInfoRecomputeCounter = new BABYLON.PerfCounter();
  45428. this._profileInfoText = null;
  45429. BABYLON.Prim2DBase._isCanvasInit = false;
  45430. if (!settings) {
  45431. settings = {};
  45432. }
  45433. if (this._cachingStrategy !== Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  45434. this._background = new BABYLON.Rectangle2D({ parent: this, id: "###CANVAS BACKGROUND###", size: settings.size }); //TODO CHECK when size is null
  45435. this._background.zOrder = 1.0;
  45436. this._background.isPickable = false;
  45437. this._background.origin = BABYLON.Vector2.Zero();
  45438. this._background.levelVisible = false;
  45439. if (settings.backgroundRoundRadius != null) {
  45440. this.backgroundRoundRadius = settings.backgroundRoundRadius;
  45441. }
  45442. if (settings.backgroundBorder != null) {
  45443. if (typeof (settings.backgroundBorder) === "string") {
  45444. this.backgroundBorder = Canvas2D.GetBrushFromString(settings.backgroundBorder);
  45445. }
  45446. else {
  45447. this.backgroundBorder = settings.backgroundBorder;
  45448. }
  45449. }
  45450. if (settings.backgroundBorderThickNess != null) {
  45451. this.backgroundBorderThickness = settings.backgroundBorderThickNess;
  45452. }
  45453. if (settings.backgroundFill != null) {
  45454. if (typeof (settings.backgroundFill) === "string") {
  45455. this.backgroundFill = Canvas2D.GetBrushFromString(settings.backgroundFill);
  45456. }
  45457. else {
  45458. this.backgroundFill = settings.backgroundFill;
  45459. }
  45460. }
  45461. this._background._patchHierarchy(this);
  45462. }
  45463. var engine = scene.getEngine();
  45464. this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  45465. this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  45466. this._capturedPointers = new BABYLON.StringDictionary();
  45467. this._pickStartingPosition = BABYLON.Vector2.Zero();
  45468. this._hierarchyLevelMaxSiblingCount = 50;
  45469. this._hierarchyDepth = 0;
  45470. this._zOrder = 0;
  45471. this._zMax = 1;
  45472. this._scene = scene;
  45473. this._engine = engine;
  45474. this._renderingSize = new BABYLON.Size(0, 0);
  45475. this._trackedGroups = new Array();
  45476. this._maxAdaptiveWorldSpaceCanvasSize = null;
  45477. this._groupCacheMaps = new BABYLON.StringDictionary();
  45478. this._patchHierarchy(this);
  45479. var enableInteraction = (settings.enableInteraction == null) ? true : settings.enableInteraction;
  45480. this._fitRenderingDevice = !settings.size;
  45481. if (!settings.size) {
  45482. settings.size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  45483. }
  45484. // Register scene dispose to also dispose the canvas when it'll happens
  45485. scene.onDisposeObservable.add(function (d, s) {
  45486. _this.dispose();
  45487. });
  45488. if (this._isScreenSpace) {
  45489. this._afterRenderObserver = this._scene.onAfterRenderObservable.add(function (d, s) {
  45490. _this._engine.clear(null, false, true);
  45491. _this._render();
  45492. });
  45493. }
  45494. else {
  45495. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function (d, s) {
  45496. _this._render();
  45497. });
  45498. }
  45499. this._supprtInstancedArray = this._engine.getCaps().instancedArrays !== null;
  45500. //this._supprtInstancedArray = false; // TODO REMOVE!!!
  45501. this._setupInteraction(enableInteraction);
  45502. }
  45503. Object.defineProperty(Canvas2D.prototype, "drawCallsOpaqueCounter", {
  45504. get: function () {
  45505. return this._drawCallsOpaqueCounter;
  45506. },
  45507. enumerable: true,
  45508. configurable: true
  45509. });
  45510. Object.defineProperty(Canvas2D.prototype, "drawCallsAlphaTestCounter", {
  45511. get: function () {
  45512. return this._drawCallsAlphaTestCounter;
  45513. },
  45514. enumerable: true,
  45515. configurable: true
  45516. });
  45517. Object.defineProperty(Canvas2D.prototype, "drawCallsTransparentCounter", {
  45518. get: function () {
  45519. return this._drawCallsTransparentCounter;
  45520. },
  45521. enumerable: true,
  45522. configurable: true
  45523. });
  45524. Object.defineProperty(Canvas2D.prototype, "groupRenderCounter", {
  45525. get: function () {
  45526. return this._groupRenderCounter;
  45527. },
  45528. enumerable: true,
  45529. configurable: true
  45530. });
  45531. Object.defineProperty(Canvas2D.prototype, "updateTransparentDataCounter", {
  45532. get: function () {
  45533. return this._updateTransparentDataCounter;
  45534. },
  45535. enumerable: true,
  45536. configurable: true
  45537. });
  45538. Object.defineProperty(Canvas2D.prototype, "cachedGroupRenderCounter", {
  45539. get: function () {
  45540. return this._cachedGroupRenderCounter;
  45541. },
  45542. enumerable: true,
  45543. configurable: true
  45544. });
  45545. Object.defineProperty(Canvas2D.prototype, "updateCachedStateCounter", {
  45546. get: function () {
  45547. return this._updateCachedStateCounter;
  45548. },
  45549. enumerable: true,
  45550. configurable: true
  45551. });
  45552. Object.defineProperty(Canvas2D.prototype, "updateLayoutCounter", {
  45553. get: function () {
  45554. return this._updateLayoutCounter;
  45555. },
  45556. enumerable: true,
  45557. configurable: true
  45558. });
  45559. Object.defineProperty(Canvas2D.prototype, "updatePositioningCounter", {
  45560. get: function () {
  45561. return this._updatePositioningCounter;
  45562. },
  45563. enumerable: true,
  45564. configurable: true
  45565. });
  45566. Object.defineProperty(Canvas2D.prototype, "updateLocalTransformCounter", {
  45567. get: function () {
  45568. return this._updateLocalTransformCounter;
  45569. },
  45570. enumerable: true,
  45571. configurable: true
  45572. });
  45573. Object.defineProperty(Canvas2D.prototype, "updateGlobalTransformCounter", {
  45574. get: function () {
  45575. return this._updateGlobalTransformCounter;
  45576. },
  45577. enumerable: true,
  45578. configurable: true
  45579. });
  45580. Object.defineProperty(Canvas2D.prototype, "boundingInfoRecomputeCounter", {
  45581. get: function () {
  45582. return this._boundingInfoRecomputeCounter;
  45583. },
  45584. enumerable: true,
  45585. configurable: true
  45586. });
  45587. Canvas2D.prototype._canvasPreInit = function (settings) {
  45588. var cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_DONTCACHE : settings.cachingStrategy;
  45589. this._cachingStrategy = cachingStrategy;
  45590. this._isScreenSpace = (settings.isScreenSpace == null) ? true : settings.isScreenSpace;
  45591. };
  45592. Canvas2D.prototype._setupInteraction = function (enable) {
  45593. var _this = this;
  45594. // No change detection
  45595. if (enable === this._interactionEnabled) {
  45596. return;
  45597. }
  45598. // Set the new state
  45599. this._interactionEnabled = enable;
  45600. // ScreenSpace mode
  45601. if (this._isScreenSpace) {
  45602. // Disable interaction
  45603. if (!enable) {
  45604. if (this._scenePrePointerObserver) {
  45605. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  45606. this._scenePrePointerObserver = null;
  45607. }
  45608. return;
  45609. }
  45610. // Enable Interaction
  45611. // Register the observable
  45612. this._scenePrePointerObserver = this.scene.onPrePointerObservable.add(function (e, s) {
  45613. var hs = 1 / _this.engine.getHardwareScalingLevel();
  45614. var localPos = e.localPosition.multiplyByFloats(hs, hs);
  45615. _this._handlePointerEventForInteraction(e, localPos, s);
  45616. });
  45617. }
  45618. else {
  45619. var scene = this.scene;
  45620. if (enable) {
  45621. scene.constantlyUpdateMeshUnderPointer = true;
  45622. this._scenePointerObserver = scene.onPointerObservable.add(function (e, s) {
  45623. if (e.pickInfo.hit && e.pickInfo.pickedMesh === _this._worldSpaceNode && _this.worldSpaceToNodeLocal) {
  45624. var localPos = _this.worldSpaceToNodeLocal(e.pickInfo.pickedPoint);
  45625. _this._handlePointerEventForInteraction(e, localPos, s);
  45626. }
  45627. });
  45628. }
  45629. else {
  45630. if (this._scenePointerObserver) {
  45631. this.scene.onPointerObservable.remove(this._scenePointerObserver);
  45632. this._scenePointerObserver = null;
  45633. }
  45634. }
  45635. }
  45636. };
  45637. /**
  45638. * Internal method, you should use the Prim2DBase version instead
  45639. */
  45640. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  45641. if (this.isPointerCaptured(pointerId)) {
  45642. return false;
  45643. }
  45644. // Try to capture the pointer on the HTML side
  45645. try {
  45646. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  45647. }
  45648. catch (e) {
  45649. }
  45650. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  45651. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  45652. this._capturedPointers.add(pointerId.toString(), primitive);
  45653. return true;
  45654. };
  45655. /**
  45656. * Internal method, you should use the Prim2DBase version instead
  45657. */
  45658. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  45659. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  45660. return false;
  45661. }
  45662. // Try to release the pointer on the HTML side
  45663. try {
  45664. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  45665. }
  45666. catch (e) {
  45667. }
  45668. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  45669. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  45670. this._capturedPointers.remove(pointerId.toString());
  45671. return true;
  45672. };
  45673. /**
  45674. * Determine if the given pointer is captured or not
  45675. * @param pointerId the Id of the pointer
  45676. * @return true if it's captured, false otherwise
  45677. */
  45678. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  45679. return this._capturedPointers.contains(pointerId.toString());
  45680. };
  45681. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  45682. // Avoid unnecessary lookup
  45683. if (this._capturedPointers.count === 0) {
  45684. return null;
  45685. }
  45686. return this._capturedPointers.get(pointerId.toString());
  45687. };
  45688. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, localPosition, eventState) {
  45689. // Dispose check
  45690. if (this.isDisposed) {
  45691. return;
  45692. }
  45693. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  45694. this._updatePointerInfo(eventData, localPosition);
  45695. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  45696. // 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.
  45697. // 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.
  45698. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, capturedPrim !== null);
  45699. // 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
  45700. this._updateOverStatus();
  45701. // Check if we have nothing to raise
  45702. if (!this._actualOverPrimitive && !capturedPrim) {
  45703. return;
  45704. }
  45705. // Update the relatedTarget info with the over primitive or the captured one (if any)
  45706. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  45707. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  45708. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  45709. // Analyze the pointer event type and fire proper events on the primitive
  45710. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  45711. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData.event);
  45712. }
  45713. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  45714. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData.event);
  45715. }
  45716. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  45717. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData.event);
  45718. }
  45719. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  45720. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData.event);
  45721. }
  45722. };
  45723. Canvas2D.prototype._updatePointerInfo = function (eventData, localPosition) {
  45724. var pii = this._primPointerInfo;
  45725. if (!pii.canvasPointerPos) {
  45726. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  45727. }
  45728. var camera = this._scene.cameraToUseForPointers || this._scene.activeCamera;
  45729. var engine = this._scene.getEngine();
  45730. if (this._isScreenSpace) {
  45731. var cameraViewport = camera.viewport;
  45732. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  45733. // Moving coordinates to local viewport world
  45734. var x = localPosition.x - viewport.x;
  45735. var y = localPosition.y - viewport.y;
  45736. pii.canvasPointerPos.x = x - this.actualPosition.x;
  45737. pii.canvasPointerPos.y = engine.getRenderHeight() - y - this.actualPosition.y;
  45738. }
  45739. else {
  45740. pii.canvasPointerPos.x = localPosition.x;
  45741. pii.canvasPointerPos.y = localPosition.y;
  45742. }
  45743. pii.mouseWheelDelta = 0;
  45744. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  45745. var event = eventData.event;
  45746. if (event.wheelDelta) {
  45747. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  45748. }
  45749. else if (event.detail) {
  45750. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  45751. }
  45752. }
  45753. else {
  45754. var pe = eventData.event;
  45755. pii.ctrlKey = pe.ctrlKey;
  45756. pii.altKey = pe.altKey;
  45757. pii.shiftKey = pe.shiftKey;
  45758. pii.metaKey = pe.metaKey;
  45759. pii.button = pe.button;
  45760. pii.buttons = pe.buttons;
  45761. pii.pointerId = pe.pointerId;
  45762. pii.width = pe.width;
  45763. pii.height = pe.height;
  45764. pii.presssure = pe.pressure;
  45765. pii.tilt.x = pe.tiltX;
  45766. pii.tilt.y = pe.tiltY;
  45767. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  45768. }
  45769. };
  45770. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture) {
  45771. if (this.scene.getRenderId() === this._intersectionRenderId) {
  45772. return;
  45773. }
  45774. // 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
  45775. if (!this._globalTransform) {
  45776. this.updateCachedStates(true);
  45777. }
  45778. var ii = Canvas2D._interInfo;
  45779. ii.pickPosition.x = mouseLocalPos.x;
  45780. ii.pickPosition.y = mouseLocalPos.y;
  45781. ii.findFirstOnly = false;
  45782. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  45783. if (!isCapture && !this.boundingInfo.doesIntersect(ii.pickPosition)) {
  45784. this._previousIntersectionList = this._actualIntersectionList;
  45785. this._actualIntersectionList = null;
  45786. this._previousOverPrimitive = this._actualOverPrimitive;
  45787. this._actualOverPrimitive = null;
  45788. return;
  45789. }
  45790. this.intersect(ii);
  45791. this._previousIntersectionList = this._actualIntersectionList;
  45792. this._actualIntersectionList = ii.intersectedPrimitives;
  45793. this._previousOverPrimitive = this._actualOverPrimitive;
  45794. this._actualOverPrimitive = ii.topMostIntersectedPrimitive;
  45795. this._intersectionRenderId = this.scene.getRenderId();
  45796. };
  45797. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  45798. Canvas2D.prototype._updateOverStatus = function () {
  45799. if ((this.scene.getRenderId() === this._hoverStatusRenderId) || !this._previousIntersectionList || !this._actualIntersectionList) {
  45800. return;
  45801. }
  45802. // Detect a change of over
  45803. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  45804. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  45805. if (prevPrim !== actualPrim) {
  45806. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  45807. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  45808. // Notify the previous "over" prim that the pointer is no longer over it
  45809. if ((capturedPrim && capturedPrim === prevPrim) || (!capturedPrim && prevPrim)) {
  45810. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  45811. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  45812. }
  45813. // Notify the new "over" prim that the pointer is over it
  45814. if ((capturedPrim && capturedPrim === actualPrim) || (!capturedPrim && actualPrim)) {
  45815. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  45816. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  45817. }
  45818. }
  45819. this._hoverStatusRenderId = this.scene.getRenderId();
  45820. };
  45821. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  45822. if (this._primPointerInfo.isCaptured) {
  45823. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  45824. }
  45825. else {
  45826. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  45827. var pii = _a[_i];
  45828. if (pii.prim === prim) {
  45829. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  45830. return;
  45831. }
  45832. }
  45833. }
  45834. };
  45835. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  45836. if (!this._notifDebugMode) {
  45837. return;
  45838. }
  45839. var debug = "";
  45840. for (var i = 0; i < prim.hierarchyDepth; i++) {
  45841. debug += " ";
  45842. }
  45843. var pii = this._primPointerInfo;
  45844. 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();
  45845. console.log(debug);
  45846. };
  45847. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  45848. var ppi = this._primPointerInfo;
  45849. // In case of PointerOver/Out we will first notify the parent with PointerEnter/Leave
  45850. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) !== 0) {
  45851. this._notifParents(prim, mask);
  45852. }
  45853. var bubbleCancelled = false;
  45854. var cur = prim;
  45855. while (cur) {
  45856. // Only trigger the observers if the primitive is intersected (except for out)
  45857. if (!bubbleCancelled) {
  45858. this._updatePrimPointerPos(cur);
  45859. // Exec the observers
  45860. this._debugExecObserver(cur, mask);
  45861. cur._pointerEventObservable.notifyObservers(ppi, mask);
  45862. this._triggerActionManager(cur, ppi, mask, eventData);
  45863. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  45864. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  45865. if (ppi.cancelBubble) {
  45866. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) === 0) {
  45867. return;
  45868. }
  45869. // We're dealing with PointerOver/Out, let's keep looping to fire PointerEnter/Leave, but not Over/Out anymore
  45870. bubbleCancelled = true;
  45871. }
  45872. }
  45873. // If bubble is cancel we didn't update the Primitive Pointer Pos yet, let's do it
  45874. if (bubbleCancelled) {
  45875. this._updatePrimPointerPos(cur);
  45876. }
  45877. // Trigger a PointerEnter corresponding to the PointerOver
  45878. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  45879. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerEnter);
  45880. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
  45881. }
  45882. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  45883. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerLeave);
  45884. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
  45885. }
  45886. // Loop to the parent
  45887. cur = cur.parent;
  45888. }
  45889. };
  45890. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  45891. var _this = this;
  45892. // 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
  45893. if (!this._globalTransform) {
  45894. this.updateCachedStates(true);
  45895. }
  45896. // Process Trigger related to PointerDown
  45897. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  45898. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  45899. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  45900. this._pickStartingTime = new Date().getTime();
  45901. this._pickedDownPrim = null;
  45902. if (prim.actionManager) {
  45903. this._pickedDownPrim = prim;
  45904. if (prim.actionManager.hasPickTriggers) {
  45905. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  45906. switch (eventData.button) {
  45907. case 0:
  45908. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  45909. break;
  45910. case 1:
  45911. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  45912. break;
  45913. case 2:
  45914. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  45915. break;
  45916. }
  45917. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  45918. }
  45919. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  45920. window.setTimeout(function () {
  45921. var ppi = _this._primPointerInfo;
  45922. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  45923. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null);
  45924. var ii = new BABYLON.IntersectInfo2D();
  45925. ii.pickPosition = ppi.canvasPointerPos.clone();
  45926. ii.findFirstOnly = false;
  45927. _this.intersect(ii);
  45928. if (ii.isPrimIntersected(prim) !== null) {
  45929. if (prim.actionManager) {
  45930. 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)) {
  45931. _this._pickStartingTime = 0;
  45932. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  45933. }
  45934. }
  45935. }
  45936. }, BABYLON.ActionManager.LongPressDelay);
  45937. }
  45938. }
  45939. }
  45940. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  45941. this._pickStartingTime = 0;
  45942. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  45943. if (prim.actionManager) {
  45944. // OnPickUpTrigger
  45945. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  45946. // OnPickTrigger
  45947. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  45948. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  45949. }
  45950. }
  45951. // OnPickOutTrigger
  45952. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  45953. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  45954. }
  45955. }
  45956. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  45957. if (prim.actionManager) {
  45958. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  45959. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  45960. }
  45961. }
  45962. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  45963. if (prim.actionManager) {
  45964. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  45965. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  45966. }
  45967. }
  45968. };
  45969. Canvas2D.prototype._notifParents = function (prim, mask) {
  45970. var pii = this._primPointerInfo;
  45971. var curPrim = this;
  45972. while (curPrim) {
  45973. this._updatePrimPointerPos(curPrim);
  45974. // Fire the proper notification
  45975. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  45976. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerEnter);
  45977. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerEnter);
  45978. }
  45979. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  45980. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerLeave);
  45981. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerLeave);
  45982. }
  45983. curPrim = curPrim.parent;
  45984. }
  45985. };
  45986. /**
  45987. * Don't forget to call the dispose method when you're done with the Canvas instance.
  45988. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  45989. */
  45990. Canvas2D.prototype.dispose = function () {
  45991. if (!_super.prototype.dispose.call(this)) {
  45992. return false;
  45993. }
  45994. if (this._profilingCanvas) {
  45995. this._profilingCanvas.dispose();
  45996. this._profilingCanvas = null;
  45997. }
  45998. if (this.interactionEnabled) {
  45999. this._setupInteraction(false);
  46000. }
  46001. if (this._beforeRenderObserver) {
  46002. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  46003. this._beforeRenderObserver = null;
  46004. }
  46005. if (this._afterRenderObserver) {
  46006. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  46007. this._afterRenderObserver = null;
  46008. }
  46009. if (this._groupCacheMaps) {
  46010. this._groupCacheMaps.forEach(function (k, m) { return m.forEach(function (e) { return e.dispose(); }); });
  46011. this._groupCacheMaps = null;
  46012. }
  46013. };
  46014. Object.defineProperty(Canvas2D.prototype, "scene", {
  46015. /**
  46016. * Accessor to the Scene that owns the Canvas
  46017. * @returns The instance of the Scene object
  46018. */
  46019. get: function () {
  46020. return this._scene;
  46021. },
  46022. enumerable: true,
  46023. configurable: true
  46024. });
  46025. Object.defineProperty(Canvas2D.prototype, "engine", {
  46026. /**
  46027. * Accessor to the Engine that drives the Scene used by this Canvas
  46028. * @returns The instance of the Engine object
  46029. */
  46030. get: function () {
  46031. return this._engine;
  46032. },
  46033. enumerable: true,
  46034. configurable: true
  46035. });
  46036. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  46037. /**
  46038. * Accessor of the Caching Strategy used by this Canvas.
  46039. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  46040. * @returns the value corresponding to the used strategy.
  46041. */
  46042. get: function () {
  46043. return this._cachingStrategy;
  46044. },
  46045. enumerable: true,
  46046. configurable: true
  46047. });
  46048. Object.defineProperty(Canvas2D.prototype, "isScreenSpace", {
  46049. /**
  46050. * Return true if the Canvas is a Screen Space one, false if it's a World Space one.
  46051. * @returns {}
  46052. */
  46053. get: function () {
  46054. return this._isScreenSpace;
  46055. },
  46056. enumerable: true,
  46057. configurable: true
  46058. });
  46059. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  46060. /**
  46061. * Only valid for World Space Canvas, returns the scene node that displays the canvas
  46062. */
  46063. get: function () {
  46064. return this._worldSpaceNode;
  46065. },
  46066. set: function (val) {
  46067. this._worldSpaceNode = val;
  46068. },
  46069. enumerable: true,
  46070. configurable: true
  46071. });
  46072. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  46073. /**
  46074. * Check if the WebGL Instanced Array extension is supported or not
  46075. */
  46076. get: function () {
  46077. return this._supprtInstancedArray;
  46078. },
  46079. enumerable: true,
  46080. configurable: true
  46081. });
  46082. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  46083. /**
  46084. * Property that defines the fill object used to draw the background of the Canvas.
  46085. * Note that Canvas with a Caching Strategy of
  46086. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  46087. */
  46088. get: function () {
  46089. if (!this._background || !this._background.isVisible) {
  46090. return null;
  46091. }
  46092. return this._background.fill;
  46093. },
  46094. set: function (value) {
  46095. this.checkBackgroundAvailability();
  46096. if (value === this._background.fill) {
  46097. return;
  46098. }
  46099. this._background.fill = value;
  46100. this._background.levelVisible = true;
  46101. },
  46102. enumerable: true,
  46103. configurable: true
  46104. });
  46105. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  46106. /**
  46107. * Property that defines the border object used to draw the background of the Canvas.
  46108. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  46109. */
  46110. get: function () {
  46111. if (!this._background || !this._background.isVisible) {
  46112. return null;
  46113. }
  46114. return this._background.border;
  46115. },
  46116. set: function (value) {
  46117. this.checkBackgroundAvailability();
  46118. if (value === this._background.border) {
  46119. return;
  46120. }
  46121. this._background.border = value;
  46122. this._background.levelVisible = true;
  46123. },
  46124. enumerable: true,
  46125. configurable: true
  46126. });
  46127. Object.defineProperty(Canvas2D.prototype, "backgroundBorderThickness", {
  46128. /**
  46129. * Property that defines the thickness of the border object used to draw the background of the Canvas.
  46130. * @returns If the background is not set, null will be returned, otherwise a valid number matching the thickness is returned.
  46131. */
  46132. get: function () {
  46133. if (!this._background || !this._background.isVisible) {
  46134. return null;
  46135. }
  46136. return this._background.borderThickness;
  46137. },
  46138. set: function (value) {
  46139. this.checkBackgroundAvailability();
  46140. if (value === this._background.borderThickness) {
  46141. return;
  46142. }
  46143. this._background.borderThickness = value;
  46144. },
  46145. enumerable: true,
  46146. configurable: true
  46147. });
  46148. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  46149. /**
  46150. * You can set the roundRadius of the background
  46151. * @returns The current roundRadius
  46152. */
  46153. get: function () {
  46154. if (!this._background || !this._background.isVisible) {
  46155. return null;
  46156. }
  46157. return this._background.roundRadius;
  46158. },
  46159. set: function (value) {
  46160. this.checkBackgroundAvailability();
  46161. if (value === this._background.roundRadius) {
  46162. return;
  46163. }
  46164. this._background.roundRadius = value;
  46165. this._background.levelVisible = true;
  46166. },
  46167. enumerable: true,
  46168. configurable: true
  46169. });
  46170. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  46171. /**
  46172. * Enable/Disable interaction for this Canvas
  46173. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  46174. */
  46175. get: function () {
  46176. return this._interactionEnabled;
  46177. },
  46178. set: function (enable) {
  46179. this._setupInteraction(enable);
  46180. },
  46181. enumerable: true,
  46182. configurable: true
  46183. });
  46184. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  46185. /**
  46186. * Access the babylon.js' engine bound data, do not invoke this method, it's for internal purpose only
  46187. * @returns {}
  46188. */
  46189. get: function () {
  46190. return this.__engineData;
  46191. },
  46192. enumerable: true,
  46193. configurable: true
  46194. });
  46195. Canvas2D.prototype.createCanvasProfileInfoCanvas = function () {
  46196. if (this._profilingCanvas) {
  46197. return this._profilingCanvas;
  46198. }
  46199. var canvas = new ScreenSpaceCanvas2D(this.scene, {
  46200. id: "ProfileInfoCanvas", cachingStrategy: Canvas2D.CACHESTRATEGY_DONTCACHE, children: [
  46201. new BABYLON.Rectangle2D({
  46202. id: "ProfileBorder", border: "#FFFFFFFF", borderThickness: 2, roundRadius: 5, fill: "#C04040C0", marginAlignment: "h: left, v: top", margin: "10", padding: "10", children: [
  46203. new BABYLON.Text2D("Stats", { id: "ProfileInfoText", marginAlignment: "h: left, v: top", fontName: "10pt Lucida Console" })
  46204. ]
  46205. })
  46206. ]
  46207. });
  46208. this._profileInfoText = canvas.findById("ProfileInfoText");
  46209. this._profilingCanvas = canvas;
  46210. return canvas;
  46211. };
  46212. Canvas2D.prototype.checkBackgroundAvailability = function () {
  46213. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  46214. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  46215. }
  46216. };
  46217. Canvas2D.prototype._initPerfMetrics = function () {
  46218. this._drawCallsOpaqueCounter.fetchNewFrame();
  46219. this._drawCallsAlphaTestCounter.fetchNewFrame();
  46220. this._drawCallsTransparentCounter.fetchNewFrame();
  46221. this._groupRenderCounter.fetchNewFrame();
  46222. this._updateTransparentDataCounter.fetchNewFrame();
  46223. this._cachedGroupRenderCounter.fetchNewFrame();
  46224. this._updateCachedStateCounter.fetchNewFrame();
  46225. this._updateLayoutCounter.fetchNewFrame();
  46226. this._updatePositioningCounter.fetchNewFrame();
  46227. this._updateLocalTransformCounter.fetchNewFrame();
  46228. this._updateGlobalTransformCounter.fetchNewFrame();
  46229. this._boundingInfoRecomputeCounter.fetchNewFrame();
  46230. };
  46231. Canvas2D.prototype._fetchPerfMetrics = function () {
  46232. this._drawCallsOpaqueCounter.addCount(0, true);
  46233. this._drawCallsAlphaTestCounter.addCount(0, true);
  46234. this._drawCallsTransparentCounter.addCount(0, true);
  46235. this._groupRenderCounter.addCount(0, true);
  46236. this._updateTransparentDataCounter.addCount(0, true);
  46237. this._cachedGroupRenderCounter.addCount(0, true);
  46238. this._updateCachedStateCounter.addCount(0, true);
  46239. this._updateLayoutCounter.addCount(0, true);
  46240. this._updatePositioningCounter.addCount(0, true);
  46241. this._updateLocalTransformCounter.addCount(0, true);
  46242. this._updateGlobalTransformCounter.addCount(0, true);
  46243. this._boundingInfoRecomputeCounter.addCount(0, true);
  46244. };
  46245. Canvas2D.prototype._updateProfileCanvas = function () {
  46246. if (this._profileInfoText == null) {
  46247. return;
  46248. }
  46249. var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
  46250. var p = "Draw Calls:\n" +
  46251. (" - Opaque: " + format(this.drawCallsOpaqueCounter.current) + ", (avg:" + format(this.drawCallsOpaqueCounter.lastSecAverage) + ", t:" + format(this.drawCallsOpaqueCounter.total) + ")\n") +
  46252. (" - AlphaTest: " + format(this.drawCallsAlphaTestCounter.current) + ", (avg:" + format(this.drawCallsAlphaTestCounter.lastSecAverage) + ", t:" + format(this.drawCallsAlphaTestCounter.total) + ")\n") +
  46253. (" - Transparent: " + format(this.drawCallsTransparentCounter.current) + ", (avg:" + format(this.drawCallsTransparentCounter.lastSecAverage) + ", t:" + format(this.drawCallsTransparentCounter.total) + ")\n") +
  46254. ("Group Render: " + this.groupRenderCounter.current + ", (avg:" + format(this.groupRenderCounter.lastSecAverage) + ", t:" + format(this.groupRenderCounter.total) + ")\n") +
  46255. ("Update Transparent Data: " + this.updateTransparentDataCounter.current + ", (avg:" + format(this.updateTransparentDataCounter.lastSecAverage) + ", t:" + format(this.updateTransparentDataCounter.total) + ")\n") +
  46256. ("Cached Group Render: " + this.cachedGroupRenderCounter.current + ", (avg:" + format(this.cachedGroupRenderCounter.lastSecAverage) + ", t:" + format(this.cachedGroupRenderCounter.total) + ")\n") +
  46257. ("Update Cached States: " + this.updateCachedStateCounter.current + ", (avg:" + format(this.updateCachedStateCounter.lastSecAverage) + ", t:" + format(this.updateCachedStateCounter.total) + ")\n") +
  46258. (" - Update Layout: " + this.updateLayoutCounter.current + ", (avg:" + format(this.updateLayoutCounter.lastSecAverage) + ", t:" + format(this.updateLayoutCounter.total) + ")\n") +
  46259. (" - Update Positioning: " + this.updatePositioningCounter.current + ", (avg:" + format(this.updatePositioningCounter.lastSecAverage) + ", t:" + format(this.updatePositioningCounter.total) + ")\n") +
  46260. (" - Update Local Trans: " + this.updateLocalTransformCounter.current + ", (avg:" + format(this.updateLocalTransformCounter.lastSecAverage) + ", t:" + format(this.updateLocalTransformCounter.total) + ")\n") +
  46261. (" - Update Global Trans: " + this.updateGlobalTransformCounter.current + ", (avg:" + format(this.updateGlobalTransformCounter.lastSecAverage) + ", t:" + format(this.updateGlobalTransformCounter.total) + ")\n") +
  46262. (" - BoundingInfo Recompute: " + this.boundingInfoRecomputeCounter.current + ", (avg:" + format(this.boundingInfoRecomputeCounter.lastSecAverage) + ", t:" + format(this.boundingInfoRecomputeCounter.total) + ")\n");
  46263. this._profileInfoText.text = p;
  46264. };
  46265. Canvas2D.prototype._addDrawCallCount = function (count, renderMode) {
  46266. switch (renderMode) {
  46267. case BABYLON.Render2DContext.RenderModeOpaque:
  46268. this._drawCallsOpaqueCounter.addCount(count, false);
  46269. return;
  46270. case BABYLON.Render2DContext.RenderModeAlphaTest:
  46271. this._drawCallsAlphaTestCounter.addCount(count, false);
  46272. return;
  46273. case BABYLON.Render2DContext.RenderModeTransparent:
  46274. this._drawCallsTransparentCounter.addCount(count, false);
  46275. return;
  46276. }
  46277. };
  46278. Canvas2D.prototype._addGroupRenderCount = function (count) {
  46279. this._groupRenderCounter.addCount(count, false);
  46280. };
  46281. Canvas2D.prototype._addUpdateTransparentDataCount = function (count) {
  46282. this._updateTransparentDataCounter.addCount(count, false);
  46283. };
  46284. Canvas2D.prototype.addCachedGroupRenderCounter = function (count) {
  46285. this._cachedGroupRenderCounter.addCount(count, false);
  46286. };
  46287. Canvas2D.prototype.addUpdateCachedStateCounter = function (count) {
  46288. this._updateCachedStateCounter.addCount(count, false);
  46289. };
  46290. Canvas2D.prototype.addUpdateLayoutCounter = function (count) {
  46291. this._updateLayoutCounter.addCount(count, false);
  46292. };
  46293. Canvas2D.prototype.addUpdatePositioningCounter = function (count) {
  46294. this._updatePositioningCounter.addCount(count, false);
  46295. };
  46296. Canvas2D.prototype.addupdateLocalTransformCounter = function (count) {
  46297. this._updateLocalTransformCounter.addCount(count, false);
  46298. };
  46299. Canvas2D.prototype.addUpdateGlobalTransformCounter = function (count) {
  46300. this._updateGlobalTransformCounter.addCount(count, false);
  46301. };
  46302. Canvas2D.prototype.onPrimBecomesDirty = function () {
  46303. this._addPrimToDirtyList(this);
  46304. };
  46305. Canvas2D.prototype._updateTrackedNodes = function () {
  46306. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  46307. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  46308. var rh = this.engine.getRenderHeight();
  46309. var v = cam.viewport.toGlobal(this.engine.getRenderWidth(), rh);
  46310. for (var _i = 0, _a = this._trackedGroups; _i < _a.length; _i++) {
  46311. var group = _a[_i];
  46312. if (group.isDisposed || !group.isVisible) {
  46313. continue;
  46314. }
  46315. var node = group.trackedNode;
  46316. var worldMtx = node.getWorldMatrix();
  46317. var proj = BABYLON.Vector3.Project(Canvas2D._v, worldMtx, Canvas2D._m, v);
  46318. group.x = Math.round(proj.x);
  46319. group.y = Math.round(rh - proj.y);
  46320. }
  46321. };
  46322. /**
  46323. * Call this method change you want to have layout related data computed and up to date (layout area, primitive area, local/global transformation matrices)
  46324. */
  46325. Canvas2D.prototype.updateCanvasLayout = function (forceRecompute) {
  46326. this._updateCanvasState(forceRecompute);
  46327. };
  46328. Canvas2D.prototype._updateAdaptiveSizeWorldCanvas = function () {
  46329. if (this._globalTransformStep < 2) {
  46330. return;
  46331. }
  46332. var n = this.worldSpaceCanvasNode;
  46333. var bi = n.getBoundingInfo().boundingBox;
  46334. var v = bi.vectorsWorld;
  46335. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  46336. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  46337. var vp = cam.viewport.toGlobal(this.engine.getRenderWidth(), this.engine.getRenderHeight());
  46338. var projPoints = new Array(4);
  46339. for (var i = 0; i < 4; i++) {
  46340. projPoints[i] = BABYLON.Vector3.Project(v[i], Canvas2D._mI, Canvas2D._m, vp);
  46341. }
  46342. var left = projPoints[3].subtract(projPoints[0]).length();
  46343. var top = projPoints[3].subtract(projPoints[1]).length();
  46344. var right = projPoints[1].subtract(projPoints[2]).length();
  46345. var bottom = projPoints[2].subtract(projPoints[0]).length();
  46346. var w = Math.round(Math.max(top, bottom));
  46347. var h = Math.round(Math.max(right, left));
  46348. var isW = w > h;
  46349. // Basically if it's under 256 we use 256, otherwise we take the biggest power of 2
  46350. var edge = Math.max(w, h);
  46351. if (edge < 256) {
  46352. edge = 256;
  46353. }
  46354. else {
  46355. edge = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  46356. }
  46357. // Clip values if needed
  46358. edge = Math.min(edge, this._maxAdaptiveWorldSpaceCanvasSize);
  46359. var newScale = edge / ((isW) ? this.size.width : this.size.height);
  46360. if (newScale !== this.scale) {
  46361. var scale = newScale;
  46362. // console.log(`New adaptive scale for Canvas ${this.id}, w: ${w}, h: ${h}, scale: ${scale}, edge: ${edge}, isW: ${isW}`);
  46363. this._setRenderingScale(scale);
  46364. }
  46365. };
  46366. Canvas2D.prototype._updateCanvasState = function (forceRecompute) {
  46367. // Check if the update has already been made for this render Frame
  46368. if (!forceRecompute && this.scene.getRenderId() === this._updateRenderId) {
  46369. return;
  46370. }
  46371. // Detect a change of rendering size
  46372. var renderingSizeChanged = false;
  46373. var newWidth = this.engine.getRenderWidth();
  46374. if (newWidth !== this._renderingSize.width) {
  46375. renderingSizeChanged = true;
  46376. }
  46377. this._renderingSize.width = newWidth;
  46378. var newHeight = this.engine.getRenderHeight();
  46379. if (newHeight !== this._renderingSize.height) {
  46380. renderingSizeChanged = true;
  46381. }
  46382. this._renderingSize.height = newHeight;
  46383. // If the canvas fit the rendering size and it changed, update
  46384. if (renderingSizeChanged && this._fitRenderingDevice) {
  46385. this.size = this._renderingSize;
  46386. if (this._background) {
  46387. this._background.size = this.size;
  46388. }
  46389. // Dirty the Layout at the Canvas level to recompute as the size changed
  46390. this._setLayoutDirty();
  46391. }
  46392. var context = new BABYLON.PrepareRender2DContext();
  46393. ++this._globalTransformProcessStep;
  46394. this.updateCachedStates(false);
  46395. this._prepareGroupRender(context);
  46396. this._updateRenderId = this.scene.getRenderId();
  46397. };
  46398. /**
  46399. * Method that renders the Canvas, you should not invoke
  46400. */
  46401. Canvas2D.prototype._render = function () {
  46402. this._initPerfMetrics();
  46403. this._updateTrackedNodes();
  46404. this._updateCanvasState(false);
  46405. if (!this._isScreenSpace) {
  46406. this._updateAdaptiveSizeWorldCanvas();
  46407. }
  46408. this._updateCanvasState(false);
  46409. if (this._primPointerInfo.canvasPointerPos) {
  46410. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false);
  46411. this._updateOverStatus(); // TODO this._primPointerInfo may not be up to date!
  46412. }
  46413. this.engine.setState(false);
  46414. this._groupRender();
  46415. if (!this._isScreenSpace) {
  46416. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagWorldCacheChanged)) {
  46417. this.worldSpaceCacheChanged();
  46418. this._clearFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  46419. }
  46420. }
  46421. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  46422. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  46423. this._cachedCanvasGroup._renderCachedCanvas();
  46424. }
  46425. this._fetchPerfMetrics();
  46426. this._updateProfileCanvas();
  46427. };
  46428. /**
  46429. * Internal method that allocate a cache for the given group.
  46430. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  46431. * @param group The group to allocate the cache of.
  46432. * @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.
  46433. */
  46434. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize, useMipMap, anisotropicLevel) {
  46435. if (useMipMap === void 0) { useMipMap = false; }
  46436. if (anisotropicLevel === void 0) { anisotropicLevel = 1; }
  46437. var key = (useMipMap ? "MipMap" : "NoMipMap") + "_" + anisotropicLevel;
  46438. // Determine size
  46439. var size = group.actualSize;
  46440. size = new BABYLON.Size(Math.ceil(size.width), Math.ceil(size.height));
  46441. if (minSize) {
  46442. size.width = Math.max(minSize.width, size.width);
  46443. size.height = Math.max(minSize.height, size.height);
  46444. }
  46445. var mapArray = this._groupCacheMaps.getOrAddWithFactory(key, function () { return new Array(); });
  46446. // Try to find a spot in one of the cached texture
  46447. var res = null;
  46448. var map;
  46449. for (var _i = 0, mapArray_1 = mapArray; _i < mapArray_1.length; _i++) {
  46450. var _map = mapArray_1[_i];
  46451. map = _map;
  46452. var node = map.allocateRect(size);
  46453. if (node) {
  46454. res = { node: node, texture: map };
  46455. break;
  46456. }
  46457. }
  46458. // Couldn't find a map that could fit the rect, create a new map for it
  46459. if (!res) {
  46460. var mapSize = new BABYLON.Size(Canvas2D._groupTextureCacheSize, Canvas2D._groupTextureCacheSize);
  46461. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  46462. if (size.width > mapSize.width || size.height > mapSize.height) {
  46463. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  46464. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  46465. }
  46466. var id = "groupsMapChache" + this._mapCounter + "forCanvas" + this.id;
  46467. map = new BABYLON.MapTexture(id, this._scene, mapSize, useMipMap ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE, useMipMap);
  46468. map.anisotropicFilteringLevel = 4;
  46469. mapArray.splice(0, 0, map);
  46470. var node = map.allocateRect(size);
  46471. res = { node: node, texture: map };
  46472. }
  46473. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  46474. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  46475. if (group !== this || this._isScreenSpace) {
  46476. var node = res.node;
  46477. // 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
  46478. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS) {
  46479. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  46480. var sprite = new BABYLON.Sprite2D(map, { parent: this._cachedCanvasGroup, id: "__cachedCanvasSprite__", spriteSize: node.contentSize, spriteLocation: node.pos });
  46481. sprite.zOrder = 1;
  46482. sprite.origin = BABYLON.Vector2.Zero();
  46483. }
  46484. else {
  46485. 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 });
  46486. sprite.origin = group.origin.clone();
  46487. res.sprite = sprite;
  46488. }
  46489. }
  46490. return res;
  46491. };
  46492. /**
  46493. * Internal method used to register a Scene Node to track position for the given group
  46494. * Do not invoke this method, for internal purpose only.
  46495. * @param group the group to track its associated Scene Node
  46496. */
  46497. Canvas2D.prototype._registerTrackedNode = function (group) {
  46498. if (group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  46499. return;
  46500. }
  46501. this._trackedGroups.push(group);
  46502. group._setFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  46503. };
  46504. /**
  46505. * Internal method used to unregister a tracked Scene Node
  46506. * Do not invoke this method, it's for internal purpose only.
  46507. * @param group the group to unregister its tracked Scene Node from.
  46508. */
  46509. Canvas2D.prototype._unregisterTrackedNode = function (group) {
  46510. if (!group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  46511. return;
  46512. }
  46513. var i = this._trackedGroups.indexOf(group);
  46514. if (i !== -1) {
  46515. this._trackedGroups.splice(i, 1);
  46516. }
  46517. group._clearFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  46518. };
  46519. /**
  46520. * Get a Solid Color Brush instance matching the given color.
  46521. * @param color The color to retrieve
  46522. * @return A shared instance of the SolidColorBrush2D class that use the given color
  46523. */
  46524. Canvas2D.GetSolidColorBrush = function (color) {
  46525. return Canvas2D._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  46526. };
  46527. /**
  46528. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  46529. * @param color The color to retrieve
  46530. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  46531. */
  46532. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  46533. return Canvas2D._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  46534. };
  46535. /**
  46536. * Get a Gradient Color Brush
  46537. * @param color1 starting color
  46538. * @param color2 engine color
  46539. * @param translation translation vector to apply. default is [0;0]
  46540. * @param rotation rotation in radian to apply to the brush, initial direction is top to bottom. rotation is counter clockwise. default is 0.
  46541. * @param scale scaling factor to apply. default is 1.
  46542. */
  46543. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  46544. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  46545. if (rotation === void 0) { rotation = 0; }
  46546. if (scale === void 0) { scale = 1; }
  46547. return Canvas2D._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  46548. };
  46549. /**
  46550. * Create a solid or gradient brush from a string value.
  46551. * @param brushString should be either
  46552. * - "solid: #RRGGBBAA" or "#RRGGBBAA"
  46553. * - "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.
  46554. */
  46555. Canvas2D.GetBrushFromString = function (brushString) {
  46556. // Note: yes, I hate/don't know RegEx.. Feel free to add your contribution to the cause!
  46557. brushString = brushString.trim();
  46558. var split = brushString.split(",");
  46559. // Solid, formatted as: "[solid:]#FF808080"
  46560. if (split.length === 1) {
  46561. var value = null;
  46562. if (brushString.indexOf("solid:") === 0) {
  46563. value = brushString.substr(6).trim();
  46564. }
  46565. else if (brushString.indexOf("#") === 0) {
  46566. value = brushString;
  46567. }
  46568. else {
  46569. return null;
  46570. }
  46571. return Canvas2D.GetSolidColorBrushFromHex(value);
  46572. }
  46573. else {
  46574. if (split[0].indexOf("gradient:") === 0) {
  46575. split[0] = split[0].substr(9).trim();
  46576. }
  46577. try {
  46578. var start = BABYLON.Color4.FromHexString(split[0].trim());
  46579. var end = BABYLON.Color4.FromHexString(split[1].trim());
  46580. var t = BABYLON.Vector2.Zero();
  46581. if (split.length > 2) {
  46582. var v = split[2].trim();
  46583. if (v.charAt(0) !== "[" || v.charAt(v.length - 1) !== "]") {
  46584. return null;
  46585. }
  46586. var sep = v.indexOf(":");
  46587. var x = parseFloat(v.substr(1, sep));
  46588. var y = parseFloat(v.substr(sep + 1, v.length - (sep + 1)));
  46589. t = new BABYLON.Vector2(x, y);
  46590. }
  46591. var r = 0;
  46592. if (split.length > 3) {
  46593. r = BABYLON.Tools.ToRadians(parseFloat(split[3].trim()));
  46594. }
  46595. var s = 1;
  46596. if (split.length > 4) {
  46597. s = parseFloat(split[4].trim());
  46598. }
  46599. return Canvas2D.GetGradientColorBrush(start, end, t, r, s);
  46600. }
  46601. catch (e) {
  46602. return null;
  46603. }
  46604. }
  46605. };
  46606. /**
  46607. * 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.
  46608. * This strategy doesn't allow primitives added directly as children of the Canvas.
  46609. * 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.
  46610. */
  46611. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  46612. /**
  46613. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  46614. * 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.
  46615. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  46616. * 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.
  46617. */
  46618. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  46619. /**
  46620. * 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).
  46621. */
  46622. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  46623. /**
  46624. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  46625. * 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).
  46626. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  46627. */
  46628. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  46629. Canvas2D._zMinDelta = 1 / (Math.pow(2, 24) - 1);
  46630. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  46631. Canvas2D._v = BABYLON.Vector3.Zero(); // Must stay zero
  46632. Canvas2D._m = BABYLON.Matrix.Identity();
  46633. Canvas2D._mI = BABYLON.Matrix.Identity(); // Must stay identity
  46634. /**
  46635. * Define the default size used for both the width and height of a MapTexture to allocate.
  46636. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  46637. */
  46638. Canvas2D._groupTextureCacheSize = 1024;
  46639. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  46640. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  46641. Canvas2D = __decorate([
  46642. BABYLON.className("Canvas2D")
  46643. ], Canvas2D);
  46644. return Canvas2D;
  46645. }(BABYLON.Group2D));
  46646. BABYLON.Canvas2D = Canvas2D;
  46647. var WorldSpaceCanvas2D = (function (_super) {
  46648. __extends(WorldSpaceCanvas2D, _super);
  46649. /**
  46650. * 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.
  46651. * 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.
  46652. * @param scene the Scene that owns the Canvas
  46653. * @param size the dimension of the Canvas in World Space
  46654. * @param settings a combination of settings, possible ones are
  46655. * - children: an array of direct children primitives
  46656. * - id: a text identifier, for information purpose only, default is null.
  46657. * - worldPosition the position of the Canvas in World Space, default is [0,0,0]
  46658. * - worldRotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
  46659. * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
  46660. * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
  46661. * - 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).
  46662. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  46663. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  46664. * - 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.
  46665. * - 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.
  46666. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  46667. * - 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.
  46668. * - 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.
  46669. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46670. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46671. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46672. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46673. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  46674. */
  46675. function WorldSpaceCanvas2D(scene, size, settings) {
  46676. BABYLON.Prim2DBase._isCanvasInit = true;
  46677. var s = settings;
  46678. s.isScreenSpace = false;
  46679. s.size = size.clone();
  46680. settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;
  46681. if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
  46682. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  46683. }
  46684. _super.call(this, scene, settings);
  46685. BABYLON.Prim2DBase._isCanvasInit = false;
  46686. this._renderableData._useMipMap = true;
  46687. this._renderableData._anisotropicLevel = 8;
  46688. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  46689. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  46690. //}
  46691. var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);
  46692. var id = settings ? settings.id || null : null;
  46693. // Set the max size of texture allowed for the adaptive render of the world space canvas cached bitmap
  46694. var capMaxTextSize = this.engine.getCaps().maxRenderTextureSize;
  46695. var defaultTextSize = (Math.min(capMaxTextSize, 1024)); // Default is 4K if allowed otherwise the max allowed
  46696. if (settings.maxAdaptiveCanvasSize == null) {
  46697. this._maxAdaptiveWorldSpaceCanvasSize = defaultTextSize;
  46698. }
  46699. else {
  46700. // We still clip the given value with the max allowed, the user may not be aware of these limitations
  46701. this._maxAdaptiveWorldSpaceCanvasSize = Math.min(settings.maxAdaptiveCanvasSize, capMaxTextSize);
  46702. }
  46703. if (createWorldSpaceNode) {
  46704. var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, this);
  46705. var vertexData = BABYLON.VertexData.CreatePlane({
  46706. width: size.width,
  46707. height: size.height,
  46708. sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
  46709. });
  46710. var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
  46711. this.applyCachedTexture(vertexData, mtl);
  46712. vertexData.applyToMesh(plane, true);
  46713. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  46714. mtl.disableLighting = true;
  46715. mtl.useAlphaFromDiffuseTexture = true;
  46716. plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();
  46717. plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();
  46718. plane.material = mtl;
  46719. this._worldSpaceNode = plane;
  46720. }
  46721. else {
  46722. this._worldSpaceNode = settings.customWorldSpaceNode;
  46723. this.applyCachedTexture(null, null);
  46724. }
  46725. }
  46726. WorldSpaceCanvas2D = __decorate([
  46727. BABYLON.className("WorldSpaceCanvas2D")
  46728. ], WorldSpaceCanvas2D);
  46729. return WorldSpaceCanvas2D;
  46730. }(Canvas2D));
  46731. BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
  46732. var ScreenSpaceCanvas2D = (function (_super) {
  46733. __extends(ScreenSpaceCanvas2D, _super);
  46734. /**
  46735. * 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.
  46736. * 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.
  46737. * All caching strategies will be available.
  46738. * 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]
  46739. * @param scene the Scene that owns the Canvas
  46740. * @param settings a combination of settings, possible ones are
  46741. * - children: an array of direct children primitives
  46742. * - id: a text identifier, for information purpose only
  46743. * - x: the position along the x axis (horizontal), relative to the left edge of the viewport. you can alternatively use the position setting.
  46744. * - y: the position along the y axis (vertically), relative to the bottom edge of the viewport. you can alternatively use the position setting.
  46745. * - 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]
  46746. * - width: the width of the Canvas. you can alternatively use the size setting.
  46747. * - height: the height of the Canvas. you can alternatively use the size setting.
  46748. * - 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
  46749. * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_DONTCACHE
  46750. * - 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.
  46751. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  46752. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  46753. * - 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.
  46754. * - 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.
  46755. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  46756. * - 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.
  46757. * - paddingTop: top padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  46758. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  46759. * - paddingRight: right padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  46760. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  46761. * - padding: top, left, right and bottom padding formatted as a single string (see BABYLON.PrimitiveThickness.fromString)
  46762. */
  46763. function ScreenSpaceCanvas2D(scene, settings) {
  46764. BABYLON.Prim2DBase._isCanvasInit = true;
  46765. _super.call(this, scene, settings);
  46766. }
  46767. ScreenSpaceCanvas2D = __decorate([
  46768. BABYLON.className("ScreenSpaceCanvas2D")
  46769. ], ScreenSpaceCanvas2D);
  46770. return ScreenSpaceCanvas2D;
  46771. }(Canvas2D));
  46772. BABYLON.ScreenSpaceCanvas2D = ScreenSpaceCanvas2D;
  46773. })(BABYLON || (BABYLON = {}));
  46774. var BABYLON;
  46775. (function (BABYLON) {
  46776. /**
  46777. * This is the class that is used to display a World Space Canvas into a 3D scene
  46778. */
  46779. var WorldSpaceCanvas2DNode = (function (_super) {
  46780. __extends(WorldSpaceCanvas2DNode, _super);
  46781. function WorldSpaceCanvas2DNode(name, scene, canvas) {
  46782. _super.call(this, name, scene);
  46783. this._canvas = canvas;
  46784. }
  46785. WorldSpaceCanvas2DNode.prototype.dispose = function () {
  46786. _super.prototype.dispose.call(this);
  46787. if (this._canvas) {
  46788. this._canvas.dispose();
  46789. this._canvas = null;
  46790. }
  46791. };
  46792. return WorldSpaceCanvas2DNode;
  46793. }(BABYLON.Mesh));
  46794. BABYLON.WorldSpaceCanvas2DNode = WorldSpaceCanvas2DNode;
  46795. })(BABYLON || (BABYLON = {}));
  46796. var BABYLON;
  46797. (function (BABYLON) {
  46798. var LayoutEngineBase = (function () {
  46799. function LayoutEngineBase() {
  46800. this.layoutDirtyOnPropertyChangedMask = 0;
  46801. }
  46802. LayoutEngineBase.prototype.updateLayout = function (prim) {
  46803. };
  46804. Object.defineProperty(LayoutEngineBase.prototype, "isChildPositionAllowed", {
  46805. get: function () {
  46806. return false;
  46807. },
  46808. enumerable: true,
  46809. configurable: true
  46810. });
  46811. LayoutEngineBase.prototype.isLocked = function () {
  46812. return this._isLocked;
  46813. };
  46814. LayoutEngineBase.prototype.lock = function () {
  46815. if (this._isLocked) {
  46816. return false;
  46817. }
  46818. this._isLocked = true;
  46819. return true;
  46820. };
  46821. LayoutEngineBase = __decorate([
  46822. BABYLON.className("LayoutEngineBase")
  46823. ], LayoutEngineBase);
  46824. return LayoutEngineBase;
  46825. }());
  46826. BABYLON.LayoutEngineBase = LayoutEngineBase;
  46827. var CanvasLayoutEngine = (function (_super) {
  46828. __extends(CanvasLayoutEngine, _super);
  46829. function CanvasLayoutEngine() {
  46830. _super.apply(this, arguments);
  46831. }
  46832. // A very simple (no) layout computing...
  46833. // The Canvas and its direct children gets the Canvas' size as Layout Area
  46834. // Indirect children have their Layout Area to the actualSize (margin area) of their parent
  46835. CanvasLayoutEngine.prototype.updateLayout = function (prim) {
  46836. // If this prim is layoutDiry we update its layoutArea and also the one of its direct children
  46837. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  46838. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  46839. var child = _a[_i];
  46840. this._doUpdate(child);
  46841. }
  46842. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  46843. }
  46844. };
  46845. CanvasLayoutEngine.prototype._doUpdate = function (prim) {
  46846. // Canvas ?
  46847. if (prim instanceof BABYLON.Canvas2D) {
  46848. prim.layoutArea = prim.actualSize;
  46849. }
  46850. else if (prim.parent instanceof BABYLON.Canvas2D) {
  46851. prim.layoutArea = prim.owner.actualSize;
  46852. }
  46853. else {
  46854. prim.layoutArea = prim.parent.contentArea;
  46855. }
  46856. };
  46857. Object.defineProperty(CanvasLayoutEngine.prototype, "isChildPositionAllowed", {
  46858. get: function () {
  46859. return true;
  46860. },
  46861. enumerable: true,
  46862. configurable: true
  46863. });
  46864. CanvasLayoutEngine.Singleton = new CanvasLayoutEngine();
  46865. CanvasLayoutEngine = __decorate([
  46866. BABYLON.className("CanvasLayoutEngine")
  46867. ], CanvasLayoutEngine);
  46868. return CanvasLayoutEngine;
  46869. }(LayoutEngineBase));
  46870. BABYLON.CanvasLayoutEngine = CanvasLayoutEngine;
  46871. var StackPanelLayoutEngine = (function (_super) {
  46872. __extends(StackPanelLayoutEngine, _super);
  46873. function StackPanelLayoutEngine() {
  46874. _super.call(this);
  46875. this._isHorizontal = true;
  46876. this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId;
  46877. }
  46878. Object.defineProperty(StackPanelLayoutEngine, "Horizontal", {
  46879. get: function () {
  46880. if (!StackPanelLayoutEngine._horizontal) {
  46881. StackPanelLayoutEngine._horizontal = new StackPanelLayoutEngine();
  46882. StackPanelLayoutEngine._horizontal.isHorizontal = true;
  46883. StackPanelLayoutEngine._horizontal.lock();
  46884. }
  46885. return StackPanelLayoutEngine._horizontal;
  46886. },
  46887. enumerable: true,
  46888. configurable: true
  46889. });
  46890. Object.defineProperty(StackPanelLayoutEngine, "Vertical", {
  46891. get: function () {
  46892. if (!StackPanelLayoutEngine._vertical) {
  46893. StackPanelLayoutEngine._vertical = new StackPanelLayoutEngine();
  46894. StackPanelLayoutEngine._vertical.isHorizontal = false;
  46895. StackPanelLayoutEngine._vertical.lock();
  46896. }
  46897. return StackPanelLayoutEngine._vertical;
  46898. },
  46899. enumerable: true,
  46900. configurable: true
  46901. });
  46902. Object.defineProperty(StackPanelLayoutEngine.prototype, "isHorizontal", {
  46903. get: function () {
  46904. return this._isHorizontal;
  46905. },
  46906. set: function (val) {
  46907. if (this.isLocked()) {
  46908. return;
  46909. }
  46910. this._isHorizontal = val;
  46911. },
  46912. enumerable: true,
  46913. configurable: true
  46914. });
  46915. StackPanelLayoutEngine.prototype.updateLayout = function (prim) {
  46916. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  46917. var x = 0;
  46918. var y = 0;
  46919. var h = this.isHorizontal;
  46920. var max = 0;
  46921. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  46922. var child = _a[_i];
  46923. var layoutArea = child.layoutArea;
  46924. child.margin.computeArea(child.actualSize, layoutArea);
  46925. max = Math.max(max, h ? layoutArea.height : layoutArea.width);
  46926. }
  46927. for (var _b = 0, _c = prim.children; _b < _c.length; _b++) {
  46928. var child = _c[_b];
  46929. child.layoutAreaPos = new BABYLON.Vector2(x, y);
  46930. var layoutArea = child.layoutArea;
  46931. if (h) {
  46932. x += layoutArea.width;
  46933. child.layoutArea = new BABYLON.Size(layoutArea.width, max);
  46934. }
  46935. else {
  46936. y += layoutArea.height;
  46937. child.layoutArea = new BABYLON.Size(max, layoutArea.height);
  46938. }
  46939. }
  46940. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  46941. }
  46942. };
  46943. Object.defineProperty(StackPanelLayoutEngine.prototype, "isChildPositionAllowed", {
  46944. get: function () {
  46945. return false;
  46946. },
  46947. enumerable: true,
  46948. configurable: true
  46949. });
  46950. StackPanelLayoutEngine._horizontal = null;
  46951. StackPanelLayoutEngine._vertical = null;
  46952. StackPanelLayoutEngine = __decorate([
  46953. BABYLON.className("StackPanelLayoutEngine")
  46954. ], StackPanelLayoutEngine);
  46955. return StackPanelLayoutEngine;
  46956. }(LayoutEngineBase));
  46957. BABYLON.StackPanelLayoutEngine = StackPanelLayoutEngine;
  46958. })(BABYLON || (BABYLON = {}));
  46959. var BABYLON;
  46960. (function (BABYLON) {
  46961. var ShaderMaterial = (function (_super) {
  46962. __extends(ShaderMaterial, _super);
  46963. function ShaderMaterial(name, scene, shaderPath, options) {
  46964. _super.call(this, name, scene);
  46965. this._textures = {};
  46966. this._textureArrays = {};
  46967. this._floats = {};
  46968. this._floatsArrays = {};
  46969. this._colors3 = {};
  46970. this._colors4 = {};
  46971. this._vectors2 = {};
  46972. this._vectors3 = {};
  46973. this._vectors4 = {};
  46974. this._matrices = {};
  46975. this._matrices3x3 = {};
  46976. this._matrices2x2 = {};
  46977. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  46978. this._shaderPath = shaderPath;
  46979. options.needAlphaBlending = options.needAlphaBlending || false;
  46980. options.needAlphaTesting = options.needAlphaTesting || false;
  46981. options.attributes = options.attributes || ["position", "normal", "uv"];
  46982. options.uniforms = options.uniforms || ["worldViewProjection"];
  46983. options.samplers = options.samplers || [];
  46984. options.defines = options.defines || [];
  46985. this._options = options;
  46986. }
  46987. ShaderMaterial.prototype.needAlphaBlending = function () {
  46988. return this._options.needAlphaBlending;
  46989. };
  46990. ShaderMaterial.prototype.needAlphaTesting = function () {
  46991. return this._options.needAlphaTesting;
  46992. };
  46993. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  46994. if (this._options.uniforms.indexOf(uniformName) === -1) {
  46995. this._options.uniforms.push(uniformName);
  46996. }
  46997. };
  46998. ShaderMaterial.prototype.setTexture = function (name, texture) {
  46999. if (this._options.samplers.indexOf(name) === -1) {
  47000. this._options.samplers.push(name);
  47001. }
  47002. this._textures[name] = texture;
  47003. return this;
  47004. };
  47005. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  47006. if (this._options.samplers.indexOf(name) === -1) {
  47007. this._options.samplers.push(name);
  47008. }
  47009. this._checkUniform(name);
  47010. this._textureArrays[name] = textures;
  47011. return this;
  47012. };
  47013. ShaderMaterial.prototype.setFloat = function (name, value) {
  47014. this._checkUniform(name);
  47015. this._floats[name] = value;
  47016. return this;
  47017. };
  47018. ShaderMaterial.prototype.setFloats = function (name, value) {
  47019. this._checkUniform(name);
  47020. this._floatsArrays[name] = value;
  47021. return this;
  47022. };
  47023. ShaderMaterial.prototype.setColor3 = function (name, value) {
  47024. this._checkUniform(name);
  47025. this._colors3[name] = value;
  47026. return this;
  47027. };
  47028. ShaderMaterial.prototype.setColor4 = function (name, value) {
  47029. this._checkUniform(name);
  47030. this._colors4[name] = value;
  47031. return this;
  47032. };
  47033. ShaderMaterial.prototype.setVector2 = function (name, value) {
  47034. this._checkUniform(name);
  47035. this._vectors2[name] = value;
  47036. return this;
  47037. };
  47038. ShaderMaterial.prototype.setVector3 = function (name, value) {
  47039. this._checkUniform(name);
  47040. this._vectors3[name] = value;
  47041. return this;
  47042. };
  47043. ShaderMaterial.prototype.setVector4 = function (name, value) {
  47044. this._checkUniform(name);
  47045. this._vectors4[name] = value;
  47046. return this;
  47047. };
  47048. ShaderMaterial.prototype.setMatrix = function (name, value) {
  47049. this._checkUniform(name);
  47050. this._matrices[name] = value;
  47051. return this;
  47052. };
  47053. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  47054. this._checkUniform(name);
  47055. this._matrices3x3[name] = value;
  47056. return this;
  47057. };
  47058. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  47059. this._checkUniform(name);
  47060. this._matrices2x2[name] = value;
  47061. return this;
  47062. };
  47063. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  47064. var scene = this.getScene();
  47065. var engine = scene.getEngine();
  47066. if (!this.checkReadyOnEveryCall) {
  47067. if (this._renderId === scene.getRenderId()) {
  47068. return true;
  47069. }
  47070. }
  47071. // Instances
  47072. var defines = [];
  47073. var fallbacks = new BABYLON.EffectFallbacks();
  47074. if (useInstances) {
  47075. defines.push("#define INSTANCES");
  47076. }
  47077. for (var index = 0; index < this._options.defines.length; index++) {
  47078. defines.push(this._options.defines[index]);
  47079. }
  47080. // Bones
  47081. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  47082. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47083. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47084. fallbacks.addCPUSkinningFallback(0, mesh);
  47085. }
  47086. // Alpha test
  47087. if (engine.getAlphaTesting()) {
  47088. defines.push("#define ALPHATEST");
  47089. }
  47090. var previousEffect = this._effect;
  47091. var join = defines.join("\n");
  47092. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  47093. if (!this._effect.isReady()) {
  47094. return false;
  47095. }
  47096. if (previousEffect !== this._effect) {
  47097. scene.resetCachedMaterial();
  47098. }
  47099. this._renderId = scene.getRenderId();
  47100. return true;
  47101. };
  47102. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  47103. var scene = this.getScene();
  47104. if (this._options.uniforms.indexOf("world") !== -1) {
  47105. this._effect.setMatrix("world", world);
  47106. }
  47107. if (this._options.uniforms.indexOf("worldView") !== -1) {
  47108. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  47109. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  47110. }
  47111. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  47112. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  47113. }
  47114. };
  47115. ShaderMaterial.prototype.bind = function (world, mesh) {
  47116. // Std values
  47117. this.bindOnlyWorldMatrix(world);
  47118. if (this.getScene().getCachedMaterial() !== this) {
  47119. if (this._options.uniforms.indexOf("view") !== -1) {
  47120. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  47121. }
  47122. if (this._options.uniforms.indexOf("projection") !== -1) {
  47123. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  47124. }
  47125. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  47126. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  47127. }
  47128. // Bones
  47129. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  47130. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47131. }
  47132. var name;
  47133. // Texture
  47134. for (name in this._textures) {
  47135. this._effect.setTexture(name, this._textures[name]);
  47136. }
  47137. // Texture arrays
  47138. for (name in this._textureArrays) {
  47139. this._effect.setTextureArray(name, this._textureArrays[name]);
  47140. }
  47141. // Float
  47142. for (name in this._floats) {
  47143. this._effect.setFloat(name, this._floats[name]);
  47144. }
  47145. // Float s
  47146. for (name in this._floatsArrays) {
  47147. this._effect.setArray(name, this._floatsArrays[name]);
  47148. }
  47149. // Color3
  47150. for (name in this._colors3) {
  47151. this._effect.setColor3(name, this._colors3[name]);
  47152. }
  47153. // Color4
  47154. for (name in this._colors4) {
  47155. var color = this._colors4[name];
  47156. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  47157. }
  47158. // Vector2
  47159. for (name in this._vectors2) {
  47160. this._effect.setVector2(name, this._vectors2[name]);
  47161. }
  47162. // Vector3
  47163. for (name in this._vectors3) {
  47164. this._effect.setVector3(name, this._vectors3[name]);
  47165. }
  47166. // Vector4
  47167. for (name in this._vectors4) {
  47168. this._effect.setVector4(name, this._vectors4[name]);
  47169. }
  47170. // Matrix
  47171. for (name in this._matrices) {
  47172. this._effect.setMatrix(name, this._matrices[name]);
  47173. }
  47174. // Matrix 3x3
  47175. for (name in this._matrices3x3) {
  47176. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  47177. }
  47178. // Matrix 2x2
  47179. for (name in this._matrices2x2) {
  47180. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  47181. }
  47182. }
  47183. _super.prototype.bind.call(this, world, mesh);
  47184. };
  47185. ShaderMaterial.prototype.clone = function (name) {
  47186. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  47187. return newShaderMaterial;
  47188. };
  47189. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  47190. if (forceDisposeTextures) {
  47191. var name;
  47192. for (name in this._textures) {
  47193. this._textures[name].dispose();
  47194. }
  47195. for (name in this._textureArrays) {
  47196. var array = this._textureArrays[name];
  47197. for (var index = 0; index < array.length; index++) {
  47198. array[index].dispose();
  47199. }
  47200. }
  47201. }
  47202. this._textures = {};
  47203. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  47204. };
  47205. ShaderMaterial.prototype.serialize = function () {
  47206. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47207. serializationObject.customType = "BABYLON.ShaderMaterial";
  47208. serializationObject.options = this._options;
  47209. serializationObject.shaderPath = this._shaderPath;
  47210. var name;
  47211. // Texture
  47212. serializationObject.textures = {};
  47213. for (name in this._textures) {
  47214. serializationObject.textures[name] = this._textures[name].serialize();
  47215. }
  47216. // Texture arrays
  47217. serializationObject.textureArrays = {};
  47218. for (name in this._textureArrays) {
  47219. serializationObject.textureArrays[name] = [];
  47220. var array = this._textureArrays[name];
  47221. for (var index = 0; index < array.length; index++) {
  47222. serializationObject.textureArrays[name].push(array[index].serialize());
  47223. }
  47224. }
  47225. // Float
  47226. serializationObject.floats = {};
  47227. for (name in this._floats) {
  47228. serializationObject.floats[name] = this._floats[name];
  47229. }
  47230. // Float s
  47231. serializationObject.floatArrays = {};
  47232. for (name in this._floatsArrays) {
  47233. serializationObject.floatArrays[name] = this._floatsArrays[name];
  47234. }
  47235. // Color3
  47236. serializationObject.colors3 = {};
  47237. for (name in this._colors3) {
  47238. serializationObject.colors3[name] = this._colors3[name].asArray();
  47239. }
  47240. // Color4
  47241. serializationObject.colors4 = {};
  47242. for (name in this._colors4) {
  47243. serializationObject.colors4[name] = this._colors4[name].asArray();
  47244. }
  47245. // Vector2
  47246. serializationObject.vectors2 = {};
  47247. for (name in this._vectors2) {
  47248. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  47249. }
  47250. // Vector3
  47251. serializationObject.vectors3 = {};
  47252. for (name in this._vectors3) {
  47253. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  47254. }
  47255. // Vector4
  47256. serializationObject.vectors4 = {};
  47257. for (name in this._vectors4) {
  47258. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  47259. }
  47260. // Matrix
  47261. serializationObject.matrices = {};
  47262. for (name in this._matrices) {
  47263. serializationObject.matrices[name] = this._matrices[name].asArray();
  47264. }
  47265. // Matrix 3x3
  47266. serializationObject.matrices3x3 = {};
  47267. for (name in this._matrices3x3) {
  47268. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  47269. }
  47270. // Matrix 2x2
  47271. serializationObject.matrices2x2 = {};
  47272. for (name in this._matrices2x2) {
  47273. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  47274. }
  47275. return serializationObject;
  47276. };
  47277. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  47278. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  47279. var name;
  47280. // Texture
  47281. for (name in source.textures) {
  47282. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  47283. }
  47284. // Texture arrays
  47285. for (name in source.textureArrays) {
  47286. var array = source.textureArrays[name];
  47287. var textureArray = new Array();
  47288. for (var index = 0; index < array.length; index++) {
  47289. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  47290. }
  47291. material.setTextureArray(name, textureArray);
  47292. }
  47293. // Float
  47294. for (name in source.floats) {
  47295. material.setFloat(name, source.floats[name]);
  47296. }
  47297. // Float s
  47298. for (name in source.floatsArrays) {
  47299. material.setFloats(name, source.floatsArrays[name]);
  47300. }
  47301. // Color3
  47302. for (name in source.colors3) {
  47303. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  47304. }
  47305. // Color4
  47306. for (name in source.colors4) {
  47307. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  47308. }
  47309. // Vector2
  47310. for (name in source.vectors2) {
  47311. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  47312. }
  47313. // Vector3
  47314. for (name in source.vectors3) {
  47315. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  47316. }
  47317. // Vector4
  47318. for (name in source.vectors4) {
  47319. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  47320. }
  47321. // Matrix
  47322. for (name in source.matrices) {
  47323. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  47324. }
  47325. // Matrix 3x3
  47326. for (name in source.matrices3x3) {
  47327. material.setMatrix3x3(name, source.matrices3x3[name]);
  47328. }
  47329. // Matrix 2x2
  47330. for (name in source.matrices2x2) {
  47331. material.setMatrix2x2(name, source.matrices2x2[name]);
  47332. }
  47333. return material;
  47334. };
  47335. return ShaderMaterial;
  47336. }(BABYLON.Material));
  47337. BABYLON.ShaderMaterial = ShaderMaterial;
  47338. })(BABYLON || (BABYLON = {}));
  47339. var BABYLON;
  47340. (function (BABYLON) {
  47341. var Internals;
  47342. (function (Internals) {
  47343. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  47344. // All values and structures referenced from:
  47345. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  47346. var DDS_MAGIC = 0x20534444;
  47347. 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;
  47348. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  47349. 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;
  47350. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  47351. function FourCCToInt32(value) {
  47352. return value.charCodeAt(0) +
  47353. (value.charCodeAt(1) << 8) +
  47354. (value.charCodeAt(2) << 16) +
  47355. (value.charCodeAt(3) << 24);
  47356. }
  47357. function Int32ToFourCC(value) {
  47358. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  47359. }
  47360. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  47361. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  47362. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  47363. var headerLengthInt = 31; // The header length in 32 bit ints
  47364. // Offsets into the header array
  47365. var off_magic = 0;
  47366. var off_size = 1;
  47367. var off_flags = 2;
  47368. var off_height = 3;
  47369. var off_width = 4;
  47370. var off_mipmapCount = 7;
  47371. var off_pfFlags = 20;
  47372. var off_pfFourCC = 21;
  47373. var off_RGBbpp = 22;
  47374. var off_RMask = 23;
  47375. var off_GMask = 24;
  47376. var off_BMask = 25;
  47377. var off_AMask = 26;
  47378. var off_caps1 = 27;
  47379. var off_caps2 = 28;
  47380. ;
  47381. var DDSTools = (function () {
  47382. function DDSTools() {
  47383. }
  47384. DDSTools.GetDDSInfo = function (arrayBuffer) {
  47385. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  47386. var mipmapCount = 1;
  47387. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  47388. mipmapCount = Math.max(1, header[off_mipmapCount]);
  47389. }
  47390. return {
  47391. width: header[off_width],
  47392. height: header[off_height],
  47393. mipmapCount: mipmapCount,
  47394. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  47395. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  47396. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  47397. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  47398. };
  47399. };
  47400. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  47401. var byteArray = new Uint8Array(dataLength);
  47402. var srcData = new Uint8Array(arrayBuffer);
  47403. var index = 0;
  47404. for (var y = height - 1; y >= 0; y--) {
  47405. for (var x = 0; x < width; x++) {
  47406. var srcPos = dataOffset + (x + y * width) * 4;
  47407. byteArray[index + 2] = srcData[srcPos];
  47408. byteArray[index + 1] = srcData[srcPos + 1];
  47409. byteArray[index] = srcData[srcPos + 2];
  47410. byteArray[index + 3] = srcData[srcPos + 3];
  47411. index += 4;
  47412. }
  47413. }
  47414. return byteArray;
  47415. };
  47416. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  47417. var byteArray = new Uint8Array(dataLength);
  47418. var srcData = new Uint8Array(arrayBuffer);
  47419. var index = 0;
  47420. for (var y = height - 1; y >= 0; y--) {
  47421. for (var x = 0; x < width; x++) {
  47422. var srcPos = dataOffset + (x + y * width) * 3;
  47423. byteArray[index + 2] = srcData[srcPos];
  47424. byteArray[index + 1] = srcData[srcPos + 1];
  47425. byteArray[index] = srcData[srcPos + 2];
  47426. index += 3;
  47427. }
  47428. }
  47429. return byteArray;
  47430. };
  47431. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  47432. var byteArray = new Uint8Array(dataLength);
  47433. var srcData = new Uint8Array(arrayBuffer);
  47434. var index = 0;
  47435. for (var y = height - 1; y >= 0; y--) {
  47436. for (var x = 0; x < width; x++) {
  47437. var srcPos = dataOffset + (x + y * width);
  47438. byteArray[index] = srcData[srcPos];
  47439. index++;
  47440. }
  47441. }
  47442. return byteArray;
  47443. };
  47444. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  47445. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  47446. if (header[off_magic] != DDS_MAGIC) {
  47447. BABYLON.Tools.Error("Invalid magic number in DDS header");
  47448. return;
  47449. }
  47450. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  47451. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  47452. return;
  47453. }
  47454. if (info.isFourCC) {
  47455. fourCC = header[off_pfFourCC];
  47456. switch (fourCC) {
  47457. case FOURCC_DXT1:
  47458. blockBytes = 8;
  47459. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  47460. break;
  47461. case FOURCC_DXT3:
  47462. blockBytes = 16;
  47463. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  47464. break;
  47465. case FOURCC_DXT5:
  47466. blockBytes = 16;
  47467. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  47468. break;
  47469. default:
  47470. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  47471. return;
  47472. }
  47473. }
  47474. mipmapCount = 1;
  47475. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  47476. mipmapCount = Math.max(1, header[off_mipmapCount]);
  47477. }
  47478. var bpp = header[off_RGBbpp];
  47479. for (var face = 0; face < faces; face++) {
  47480. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  47481. width = header[off_width];
  47482. height = header[off_height];
  47483. dataOffset = header[off_size] + 4;
  47484. for (i = 0; i < mipmapCount; ++i) {
  47485. if (info.isRGB) {
  47486. if (bpp === 24) {
  47487. dataLength = width * height * 3;
  47488. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  47489. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  47490. }
  47491. else {
  47492. dataLength = width * height * 4;
  47493. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  47494. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  47495. }
  47496. }
  47497. else if (info.isLuminance) {
  47498. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  47499. var unpaddedRowSize = width;
  47500. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  47501. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  47502. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  47503. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  47504. }
  47505. else {
  47506. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  47507. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  47508. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  47509. }
  47510. dataOffset += dataLength;
  47511. width *= 0.5;
  47512. height *= 0.5;
  47513. width = Math.max(1.0, width);
  47514. height = Math.max(1.0, height);
  47515. }
  47516. }
  47517. };
  47518. return DDSTools;
  47519. }());
  47520. Internals.DDSTools = DDSTools;
  47521. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  47522. })(BABYLON || (BABYLON = {}));
  47523. var BABYLON;
  47524. (function (BABYLON) {
  47525. var CannonJSPlugin = (function () {
  47526. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  47527. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  47528. if (iterations === void 0) { iterations = 10; }
  47529. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  47530. this.name = "CannonJSPlugin";
  47531. this._physicsMaterials = [];
  47532. this._fixedTimeStep = 1 / 60;
  47533. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  47534. this._currentCollisionGroup = 2;
  47535. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  47536. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  47537. this._tmpPosition = BABYLON.Vector3.Zero();
  47538. this._tmpQuaternion = new BABYLON.Quaternion();
  47539. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  47540. this._tmpDeltaRotation = new BABYLON.Quaternion();
  47541. this._tmpUnityRotation = new BABYLON.Quaternion();
  47542. if (!this.isSupported()) {
  47543. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  47544. return;
  47545. }
  47546. this.world = new CANNON.World();
  47547. this.world.broadphase = new CANNON.NaiveBroadphase();
  47548. this.world.solver.iterations = iterations;
  47549. }
  47550. CannonJSPlugin.prototype.setGravity = function (gravity) {
  47551. this.world.gravity.copy(gravity);
  47552. };
  47553. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  47554. this._fixedTimeStep = timeStep;
  47555. };
  47556. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  47557. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  47558. };
  47559. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  47560. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  47561. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  47562. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  47563. };
  47564. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  47565. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  47566. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  47567. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  47568. };
  47569. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  47570. //parent-child relationship. Does this impostor has a parent impostor?
  47571. if (impostor.parent) {
  47572. if (impostor.physicsBody) {
  47573. this.removePhysicsBody(impostor);
  47574. //TODO is that needed?
  47575. impostor.forceUpdate();
  47576. }
  47577. return;
  47578. }
  47579. //should a new body be created for this impostor?
  47580. if (impostor.isBodyInitRequired()) {
  47581. var shape = this._createShape(impostor);
  47582. //unregister events, if body is being changed
  47583. var oldBody = impostor.physicsBody;
  47584. if (oldBody) {
  47585. this.removePhysicsBody(impostor);
  47586. }
  47587. //create the body and material
  47588. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  47589. var bodyCreationObject = {
  47590. mass: impostor.getParam("mass"),
  47591. material: material
  47592. };
  47593. // A simple extend, in case native options were used.
  47594. var nativeOptions = impostor.getParam("nativeOptions");
  47595. for (var key in nativeOptions) {
  47596. if (nativeOptions.hasOwnProperty(key)) {
  47597. bodyCreationObject[key] = nativeOptions[key];
  47598. }
  47599. }
  47600. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  47601. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  47602. this.world.addEventListener("preStep", impostor.beforeStep);
  47603. this.world.addEventListener("postStep", impostor.afterStep);
  47604. impostor.physicsBody.addShape(shape);
  47605. this.world.add(impostor.physicsBody);
  47606. //try to keep the body moving in the right direction by taking old properties.
  47607. //Should be tested!
  47608. if (oldBody) {
  47609. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  47610. impostor.physicsBody[param].copy(oldBody[param]);
  47611. });
  47612. }
  47613. this._processChildMeshes(impostor);
  47614. }
  47615. //now update the body's transformation
  47616. this._updatePhysicsBodyTransformation(impostor);
  47617. };
  47618. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  47619. var _this = this;
  47620. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  47621. if (meshChildren.length) {
  47622. var processMesh = function (localPosition, mesh) {
  47623. var childImpostor = mesh.getPhysicsImpostor();
  47624. if (childImpostor) {
  47625. var parent = childImpostor.parent;
  47626. if (parent !== mainImpostor) {
  47627. var localPosition = mesh.position;
  47628. if (childImpostor.physicsBody) {
  47629. _this.removePhysicsBody(childImpostor);
  47630. childImpostor.physicsBody = null;
  47631. }
  47632. childImpostor.parent = mainImpostor;
  47633. childImpostor.resetUpdateFlags();
  47634. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  47635. //Add the mass of the children.
  47636. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  47637. }
  47638. }
  47639. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  47640. };
  47641. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  47642. }
  47643. };
  47644. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  47645. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  47646. this.world.removeEventListener("preStep", impostor.beforeStep);
  47647. this.world.removeEventListener("postStep", impostor.afterStep);
  47648. this.world.remove(impostor.physicsBody);
  47649. };
  47650. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  47651. var mainBody = impostorJoint.mainImpostor.physicsBody;
  47652. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  47653. if (!mainBody || !connectedBody) {
  47654. return;
  47655. }
  47656. var constraint;
  47657. var jointData = impostorJoint.joint.jointData;
  47658. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  47659. var constraintData = {
  47660. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  47661. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  47662. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  47663. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  47664. maxForce: jointData.nativeParams.maxForce,
  47665. collideConnected: !!jointData.collision
  47666. };
  47667. //Not needed, Cannon has a collideConnected flag
  47668. /*if (!jointData.collision) {
  47669. //add 1st body to a collision group of its own, if it is not in 1
  47670. if (mainBody.collisionFilterGroup === 1) {
  47671. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  47672. this._currentCollisionGroup <<= 1;
  47673. }
  47674. if (connectedBody.collisionFilterGroup === 1) {
  47675. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  47676. this._currentCollisionGroup <<= 1;
  47677. }
  47678. //add their mask to the collisionFilterMask of each other:
  47679. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  47680. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  47681. }*/
  47682. switch (impostorJoint.joint.type) {
  47683. case BABYLON.PhysicsJoint.HingeJoint:
  47684. case BABYLON.PhysicsJoint.Hinge2Joint:
  47685. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  47686. break;
  47687. case BABYLON.PhysicsJoint.DistanceJoint:
  47688. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  47689. break;
  47690. case BABYLON.PhysicsJoint.SpringJoint:
  47691. var springData = jointData;
  47692. constraint = new CANNON.Spring(mainBody, connectedBody, {
  47693. restLength: springData.length,
  47694. stiffness: springData.stiffness,
  47695. damping: springData.damping,
  47696. localAnchorA: constraintData.pivotA,
  47697. localAnchorB: constraintData.pivotB
  47698. });
  47699. break;
  47700. case BABYLON.PhysicsJoint.LockJoint:
  47701. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  47702. break;
  47703. case BABYLON.PhysicsJoint.PointToPointJoint:
  47704. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  47705. default:
  47706. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  47707. break;
  47708. }
  47709. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  47710. constraint.collideConnected = !!jointData.collision;
  47711. impostorJoint.joint.physicsJoint = constraint;
  47712. //don't add spring as constraint, as it is not one.
  47713. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  47714. this.world.addConstraint(constraint);
  47715. }
  47716. else {
  47717. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  47718. constraint.applyForce();
  47719. });
  47720. }
  47721. };
  47722. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  47723. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  47724. };
  47725. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  47726. var index;
  47727. var mat;
  47728. for (index = 0; index < this._physicsMaterials.length; index++) {
  47729. mat = this._physicsMaterials[index];
  47730. if (mat.friction === friction && mat.restitution === restitution) {
  47731. return mat;
  47732. }
  47733. }
  47734. var currentMat = new CANNON.Material(name);
  47735. currentMat.friction = friction;
  47736. currentMat.restitution = restitution;
  47737. this._physicsMaterials.push(currentMat);
  47738. return currentMat;
  47739. };
  47740. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  47741. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  47742. };
  47743. CannonJSPlugin.prototype._createShape = function (impostor) {
  47744. var object = impostor.object;
  47745. var returnValue;
  47746. var extendSize = impostor.getObjectExtendSize();
  47747. switch (impostor.type) {
  47748. case BABYLON.PhysicsEngine.SphereImpostor:
  47749. var radiusX = extendSize.x;
  47750. var radiusY = extendSize.y;
  47751. var radiusZ = extendSize.z;
  47752. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  47753. break;
  47754. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  47755. case BABYLON.PhysicsImpostor.CylinderImpostor:
  47756. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  47757. break;
  47758. case BABYLON.PhysicsImpostor.BoxImpostor:
  47759. var box = extendSize.scale(0.5);
  47760. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  47761. break;
  47762. case BABYLON.PhysicsImpostor.PlaneImpostor:
  47763. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  47764. returnValue = new CANNON.Plane();
  47765. break;
  47766. case BABYLON.PhysicsImpostor.MeshImpostor:
  47767. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  47768. var rawFaces = object.getIndices ? object.getIndices() : [];
  47769. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  47770. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  47771. break;
  47772. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  47773. returnValue = this._createHeightmap(object);
  47774. break;
  47775. case BABYLON.PhysicsImpostor.ParticleImpostor:
  47776. returnValue = new CANNON.Particle();
  47777. break;
  47778. }
  47779. return returnValue;
  47780. };
  47781. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  47782. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47783. var matrix = [];
  47784. //For now pointDepth will not be used and will be automatically calculated.
  47785. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  47786. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  47787. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  47788. var elementSize = dim * 2 / arraySize;
  47789. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  47790. for (var i = 0; i < pos.length; i = i + 3) {
  47791. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  47792. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  47793. var y = pos[i + 1] + minY;
  47794. if (!matrix[x]) {
  47795. matrix[x] = [];
  47796. }
  47797. if (!matrix[x][z]) {
  47798. matrix[x][z] = y;
  47799. }
  47800. matrix[x][z] = Math.max(y, matrix[x][z]);
  47801. }
  47802. for (var x = 0; x <= arraySize; ++x) {
  47803. if (!matrix[x]) {
  47804. var loc = 1;
  47805. while (!matrix[(x + loc) % arraySize]) {
  47806. loc++;
  47807. }
  47808. matrix[x] = matrix[(x + loc) % arraySize].slice();
  47809. }
  47810. for (var z = 0; z <= arraySize; ++z) {
  47811. if (!matrix[x][z]) {
  47812. var loc = 1;
  47813. var newValue;
  47814. while (newValue === undefined) {
  47815. newValue = matrix[x][(z + loc++) % arraySize];
  47816. }
  47817. matrix[x][z] = newValue;
  47818. }
  47819. }
  47820. }
  47821. var shape = new CANNON.Heightfield(matrix, {
  47822. elementSize: elementSize
  47823. });
  47824. //For future reference, needed for body transformation
  47825. shape.minY = minY;
  47826. return shape;
  47827. };
  47828. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  47829. var object = impostor.object;
  47830. //make sure it is updated...
  47831. object.computeWorldMatrix && object.computeWorldMatrix(true);
  47832. // The delta between the mesh position and the mesh bounding box center
  47833. var center = impostor.getObjectCenter();
  47834. var extendSize = impostor.getObjectExtendSize();
  47835. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  47836. this._tmpPosition.copyFrom(center);
  47837. var quaternion = object.rotationQuaternion;
  47838. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  47839. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  47840. //-90 DEG in X, precalculated
  47841. quaternion = quaternion.multiply(this._minus90X);
  47842. //Invert! (Precalculated, 90 deg in X)
  47843. //No need to clone. this will never change.
  47844. impostor.setDeltaRotation(this._plus90X);
  47845. }
  47846. //If it is a heightfield, if should be centered.
  47847. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  47848. var mesh = object;
  47849. //calculate the correct body position:
  47850. var rotationQuaternion = mesh.rotationQuaternion;
  47851. mesh.rotationQuaternion = this._tmpUnityRotation;
  47852. mesh.computeWorldMatrix(true);
  47853. //get original center with no rotation
  47854. var c = center.clone();
  47855. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  47856. //rotation is back
  47857. mesh.rotationQuaternion = rotationQuaternion;
  47858. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  47859. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  47860. mesh.setPivotMatrix(p);
  47861. mesh.computeWorldMatrix(true);
  47862. //calculate the translation
  47863. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  47864. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  47865. //add it inverted to the delta
  47866. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  47867. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  47868. mesh.setPivotMatrix(oldPivot);
  47869. mesh.computeWorldMatrix(true);
  47870. }
  47871. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  47872. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  47873. this._tmpPosition.copyFrom(object.position);
  47874. }
  47875. impostor.setDeltaPosition(this._tmpDeltaPosition);
  47876. //Now update the impostor object
  47877. impostor.physicsBody.position.copy(this._tmpPosition);
  47878. impostor.physicsBody.quaternion.copy(quaternion);
  47879. };
  47880. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  47881. impostor.object.position.copyFrom(impostor.physicsBody.position);
  47882. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  47883. };
  47884. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  47885. impostor.physicsBody.position.copy(newPosition);
  47886. impostor.physicsBody.quaternion.copy(newRotation);
  47887. };
  47888. CannonJSPlugin.prototype.isSupported = function () {
  47889. return window.CANNON !== undefined;
  47890. };
  47891. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  47892. impostor.physicsBody.velocity.copy(velocity);
  47893. };
  47894. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  47895. impostor.physicsBody.angularVelocity.copy(velocity);
  47896. };
  47897. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  47898. var v = impostor.physicsBody.velocity;
  47899. if (!v)
  47900. return null;
  47901. return new BABYLON.Vector3(v.x, v.y, v.z);
  47902. };
  47903. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  47904. var v = impostor.physicsBody.angularVelocity;
  47905. if (!v)
  47906. return null;
  47907. return new BABYLON.Vector3(v.x, v.y, v.z);
  47908. };
  47909. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  47910. impostor.physicsBody.mass = mass;
  47911. impostor.physicsBody.updateMassProperties();
  47912. };
  47913. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  47914. impostor.physicsBody.sleep();
  47915. };
  47916. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  47917. impostor.physicsBody.wakeUp();
  47918. };
  47919. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  47920. joint.physicsJoint.distance = maxDistance;
  47921. };
  47922. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  47923. if (!motorIndex) {
  47924. joint.physicsJoint.enableMotor();
  47925. }
  47926. };
  47927. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  47928. if (!motorIndex) {
  47929. joint.physicsJoint.disableMotor();
  47930. }
  47931. };
  47932. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  47933. if (!motorIndex) {
  47934. joint.physicsJoint.enableMotor();
  47935. joint.physicsJoint.setMotorSpeed(speed);
  47936. if (maxForce) {
  47937. this.setLimit(joint, maxForce);
  47938. }
  47939. }
  47940. };
  47941. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  47942. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  47943. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  47944. };
  47945. CannonJSPlugin.prototype.dispose = function () {
  47946. //nothing to do, actually.
  47947. };
  47948. return CannonJSPlugin;
  47949. }());
  47950. BABYLON.CannonJSPlugin = CannonJSPlugin;
  47951. })(BABYLON || (BABYLON = {}));
  47952. var BABYLON;
  47953. (function (BABYLON) {
  47954. var OimoJSPlugin = (function () {
  47955. function OimoJSPlugin(iterations) {
  47956. this.name = "OimoJSPlugin";
  47957. this._tmpImpostorsArray = [];
  47958. this._tmpPositionVector = BABYLON.Vector3.Zero();
  47959. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  47960. this.world.clear();
  47961. //making sure no stats are calculated
  47962. this.world.isNoStat = true;
  47963. }
  47964. OimoJSPlugin.prototype.setGravity = function (gravity) {
  47965. this.world.gravity.copy(gravity);
  47966. };
  47967. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  47968. this.world.timeStep = timeStep;
  47969. };
  47970. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  47971. var _this = this;
  47972. impostors.forEach(function (impostor) {
  47973. impostor.beforeStep();
  47974. });
  47975. this.world.step();
  47976. impostors.forEach(function (impostor) {
  47977. impostor.afterStep();
  47978. //update the ordered impostors array
  47979. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  47980. });
  47981. //check for collisions
  47982. var contact = this.world.contacts;
  47983. while (contact !== null) {
  47984. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  47985. contact = contact.next;
  47986. continue;
  47987. }
  47988. //is this body colliding with any other? get the impostor
  47989. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  47990. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  47991. if (!mainImpostor || !collidingImpostor) {
  47992. contact = contact.next;
  47993. continue;
  47994. }
  47995. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  47996. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  47997. contact = contact.next;
  47998. }
  47999. };
  48000. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  48001. var mass = impostor.physicsBody.massInfo.mass;
  48002. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  48003. };
  48004. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  48005. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  48006. this.applyImpulse(impostor, force, contactPoint);
  48007. };
  48008. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  48009. var _this = this;
  48010. //parent-child relationship. Does this impostor has a parent impostor?
  48011. if (impostor.parent) {
  48012. if (impostor.physicsBody) {
  48013. this.removePhysicsBody(impostor);
  48014. //TODO is that needed?
  48015. impostor.forceUpdate();
  48016. }
  48017. return;
  48018. }
  48019. if (impostor.isBodyInitRequired()) {
  48020. var bodyConfig = {
  48021. name: impostor.uniqueId,
  48022. //Oimo must have mass, also for static objects.
  48023. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  48024. size: [],
  48025. type: [],
  48026. pos: [],
  48027. rot: [],
  48028. move: impostor.getParam("mass") !== 0,
  48029. //Supporting older versions of Oimo
  48030. world: this.world
  48031. };
  48032. var impostors = [impostor];
  48033. function addToArray(parent) {
  48034. if (!parent.getChildMeshes)
  48035. return;
  48036. parent.getChildMeshes().forEach(function (m) {
  48037. if (m.physicsImpostor) {
  48038. impostors.push(m.physicsImpostor);
  48039. m.physicsImpostor._init();
  48040. }
  48041. });
  48042. }
  48043. addToArray(impostor.object);
  48044. function checkWithEpsilon(value) {
  48045. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  48046. }
  48047. impostors.forEach(function (i) {
  48048. //get the correct bounding box
  48049. var oldQuaternion = i.object.rotationQuaternion;
  48050. var rot = new OIMO.Euler().setFromQuaternion({
  48051. x: impostor.object.rotationQuaternion.x,
  48052. y: impostor.object.rotationQuaternion.y,
  48053. z: impostor.object.rotationQuaternion.z,
  48054. s: impostor.object.rotationQuaternion.w
  48055. });
  48056. var extendSize = i.getObjectExtendSize();
  48057. if (i === impostor) {
  48058. var center = impostor.getObjectCenter();
  48059. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  48060. //Can also use Array.prototype.push.apply
  48061. bodyConfig.pos.push(center.x);
  48062. bodyConfig.pos.push(center.y);
  48063. bodyConfig.pos.push(center.z);
  48064. //tmp solution
  48065. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  48066. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  48067. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  48068. }
  48069. else {
  48070. bodyConfig.pos.push(i.object.position.x);
  48071. bodyConfig.pos.push(i.object.position.y);
  48072. bodyConfig.pos.push(i.object.position.z);
  48073. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  48074. bodyConfig.rot.push(0);
  48075. bodyConfig.rot.push(0);
  48076. bodyConfig.rot.push(0);
  48077. }
  48078. // register mesh
  48079. switch (i.type) {
  48080. case BABYLON.PhysicsImpostor.ParticleImpostor:
  48081. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  48082. case BABYLON.PhysicsImpostor.SphereImpostor:
  48083. var radiusX = extendSize.x;
  48084. var radiusY = extendSize.y;
  48085. var radiusZ = extendSize.z;
  48086. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  48087. bodyConfig.type.push('sphere');
  48088. //due to the way oimo works with compounds, add 3 times
  48089. bodyConfig.size.push(size);
  48090. bodyConfig.size.push(size);
  48091. bodyConfig.size.push(size);
  48092. break;
  48093. case BABYLON.PhysicsImpostor.CylinderImpostor:
  48094. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  48095. var sizeY = checkWithEpsilon(extendSize.y);
  48096. bodyConfig.type.push('cylinder');
  48097. bodyConfig.size.push(sizeX);
  48098. bodyConfig.size.push(sizeY);
  48099. //due to the way oimo works with compounds, add one more value.
  48100. bodyConfig.size.push(sizeY);
  48101. break;
  48102. case BABYLON.PhysicsImpostor.PlaneImpostor:
  48103. case BABYLON.PhysicsImpostor.BoxImpostor:
  48104. default:
  48105. var sizeX = checkWithEpsilon(extendSize.x);
  48106. var sizeY = checkWithEpsilon(extendSize.y);
  48107. var sizeZ = checkWithEpsilon(extendSize.z);
  48108. bodyConfig.type.push('box');
  48109. bodyConfig.size.push(sizeX);
  48110. bodyConfig.size.push(sizeY);
  48111. bodyConfig.size.push(sizeZ);
  48112. break;
  48113. }
  48114. //actually not needed, but hey...
  48115. i.object.rotationQuaternion = oldQuaternion;
  48116. });
  48117. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  48118. }
  48119. else {
  48120. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  48121. }
  48122. impostor.setDeltaPosition(this._tmpPositionVector);
  48123. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  48124. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  48125. };
  48126. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  48127. //impostor.physicsBody.dispose();
  48128. //Same as : (older oimo versions)
  48129. this.world.removeRigidBody(impostor.physicsBody);
  48130. };
  48131. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  48132. var mainBody = impostorJoint.mainImpostor.physicsBody;
  48133. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  48134. if (!mainBody || !connectedBody) {
  48135. return;
  48136. }
  48137. var jointData = impostorJoint.joint.jointData;
  48138. var options = jointData.nativeParams || {};
  48139. var type;
  48140. var nativeJointData = {
  48141. body1: mainBody,
  48142. body2: connectedBody,
  48143. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  48144. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  48145. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  48146. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  48147. min: options.min,
  48148. max: options.max,
  48149. collision: options.collision || jointData.collision,
  48150. spring: options.spring,
  48151. //supporting older version of Oimo
  48152. world: this.world
  48153. };
  48154. switch (impostorJoint.joint.type) {
  48155. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  48156. type = "jointBall";
  48157. break;
  48158. case BABYLON.PhysicsJoint.SpringJoint:
  48159. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  48160. var springData = jointData;
  48161. nativeJointData.min = springData.length || nativeJointData.min;
  48162. //Max should also be set, just make sure it is at least min
  48163. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  48164. case BABYLON.PhysicsJoint.DistanceJoint:
  48165. type = "jointDistance";
  48166. nativeJointData.max = jointData.maxDistance;
  48167. break;
  48168. case BABYLON.PhysicsJoint.PrismaticJoint:
  48169. type = "jointPrisme";
  48170. break;
  48171. case BABYLON.PhysicsJoint.SliderJoint:
  48172. type = "jointSlide";
  48173. break;
  48174. case BABYLON.PhysicsJoint.WheelJoint:
  48175. type = "jointWheel";
  48176. break;
  48177. case BABYLON.PhysicsJoint.HingeJoint:
  48178. default:
  48179. type = "jointHinge";
  48180. break;
  48181. }
  48182. nativeJointData.type = type;
  48183. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  48184. };
  48185. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  48186. //Bug in Oimo prevents us from disposing a joint in the playground
  48187. //joint.joint.physicsJoint.dispose();
  48188. //So we will bruteforce it!
  48189. try {
  48190. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  48191. }
  48192. catch (e) {
  48193. BABYLON.Tools.Warn(e);
  48194. }
  48195. };
  48196. OimoJSPlugin.prototype.isSupported = function () {
  48197. return OIMO !== undefined;
  48198. };
  48199. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  48200. if (!impostor.physicsBody.sleeping) {
  48201. //TODO check that
  48202. if (impostor.physicsBody.shapes.next) {
  48203. var parentShape = this._getLastShape(impostor.physicsBody);
  48204. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  48205. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  48206. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  48207. }
  48208. else {
  48209. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  48210. }
  48211. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  48212. impostor.object.rotationQuaternion.normalize();
  48213. }
  48214. };
  48215. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  48216. var body = impostor.physicsBody;
  48217. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  48218. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  48219. body.syncShapes();
  48220. body.awake();
  48221. };
  48222. OimoJSPlugin.prototype._getLastShape = function (body) {
  48223. var lastShape = body.shapes;
  48224. while (lastShape.next) {
  48225. lastShape = lastShape.next;
  48226. }
  48227. return lastShape;
  48228. };
  48229. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  48230. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  48231. };
  48232. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  48233. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  48234. };
  48235. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  48236. var v = impostor.physicsBody.linearVelocity;
  48237. if (!v)
  48238. return null;
  48239. return new BABYLON.Vector3(v.x, v.y, v.z);
  48240. };
  48241. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  48242. var v = impostor.physicsBody.angularVelocity;
  48243. if (!v)
  48244. return null;
  48245. return new BABYLON.Vector3(v.x, v.y, v.z);
  48246. };
  48247. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  48248. var staticBody = mass === 0;
  48249. //this will actually set the body's density and not its mass.
  48250. //But this is how oimo treats the mass variable.
  48251. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  48252. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  48253. };
  48254. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  48255. impostor.physicsBody.sleep();
  48256. };
  48257. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  48258. impostor.physicsBody.awake();
  48259. };
  48260. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  48261. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  48262. if (minDistance !== void 0) {
  48263. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  48264. }
  48265. };
  48266. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  48267. //TODO separate rotational and transational motors.
  48268. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  48269. if (motor) {
  48270. motor.setMotor(speed, maxForce);
  48271. }
  48272. };
  48273. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  48274. //TODO separate rotational and transational motors.
  48275. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  48276. if (motor) {
  48277. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  48278. }
  48279. };
  48280. OimoJSPlugin.prototype.dispose = function () {
  48281. this.world.clear();
  48282. };
  48283. return OimoJSPlugin;
  48284. }());
  48285. BABYLON.OimoJSPlugin = OimoJSPlugin;
  48286. })(BABYLON || (BABYLON = {}));
  48287. var BABYLON;
  48288. (function (BABYLON) {
  48289. var DisplayPassPostProcess = (function (_super) {
  48290. __extends(DisplayPassPostProcess, _super);
  48291. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  48292. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  48293. }
  48294. return DisplayPassPostProcess;
  48295. }(BABYLON.PostProcess));
  48296. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  48297. })(BABYLON || (BABYLON = {}));
  48298. var BABYLON;
  48299. (function (BABYLON) {
  48300. var SimplificationSettings = (function () {
  48301. function SimplificationSettings(quality, distance, optimizeMesh) {
  48302. this.quality = quality;
  48303. this.distance = distance;
  48304. this.optimizeMesh = optimizeMesh;
  48305. }
  48306. return SimplificationSettings;
  48307. }());
  48308. BABYLON.SimplificationSettings = SimplificationSettings;
  48309. var SimplificationQueue = (function () {
  48310. function SimplificationQueue() {
  48311. this.running = false;
  48312. this._simplificationArray = [];
  48313. }
  48314. SimplificationQueue.prototype.addTask = function (task) {
  48315. this._simplificationArray.push(task);
  48316. };
  48317. SimplificationQueue.prototype.executeNext = function () {
  48318. var task = this._simplificationArray.pop();
  48319. if (task) {
  48320. this.running = true;
  48321. this.runSimplification(task);
  48322. }
  48323. else {
  48324. this.running = false;
  48325. }
  48326. };
  48327. SimplificationQueue.prototype.runSimplification = function (task) {
  48328. var _this = this;
  48329. if (task.parallelProcessing) {
  48330. //parallel simplifier
  48331. task.settings.forEach(function (setting) {
  48332. var simplifier = _this.getSimplifier(task);
  48333. simplifier.simplify(setting, function (newMesh) {
  48334. task.mesh.addLODLevel(setting.distance, newMesh);
  48335. newMesh.isVisible = true;
  48336. //check if it is the last
  48337. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  48338. //all done, run the success callback.
  48339. task.successCallback();
  48340. }
  48341. _this.executeNext();
  48342. });
  48343. });
  48344. }
  48345. else {
  48346. //single simplifier.
  48347. var simplifier = this.getSimplifier(task);
  48348. var runDecimation = function (setting, callback) {
  48349. simplifier.simplify(setting, function (newMesh) {
  48350. task.mesh.addLODLevel(setting.distance, newMesh);
  48351. newMesh.isVisible = true;
  48352. //run the next quality level
  48353. callback();
  48354. });
  48355. };
  48356. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  48357. runDecimation(task.settings[loop.index], function () {
  48358. loop.executeNext();
  48359. });
  48360. }, function () {
  48361. //execution ended, run the success callback.
  48362. if (task.successCallback) {
  48363. task.successCallback();
  48364. }
  48365. _this.executeNext();
  48366. });
  48367. }
  48368. };
  48369. SimplificationQueue.prototype.getSimplifier = function (task) {
  48370. switch (task.simplificationType) {
  48371. case SimplificationType.QUADRATIC:
  48372. default:
  48373. return new QuadraticErrorSimplification(task.mesh);
  48374. }
  48375. };
  48376. return SimplificationQueue;
  48377. }());
  48378. BABYLON.SimplificationQueue = SimplificationQueue;
  48379. /**
  48380. * The implemented types of simplification.
  48381. * At the moment only Quadratic Error Decimation is implemented.
  48382. */
  48383. (function (SimplificationType) {
  48384. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  48385. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  48386. var SimplificationType = BABYLON.SimplificationType;
  48387. var DecimationTriangle = (function () {
  48388. function DecimationTriangle(vertices) {
  48389. this.vertices = vertices;
  48390. this.error = new Array(4);
  48391. this.deleted = false;
  48392. this.isDirty = false;
  48393. this.deletePending = false;
  48394. this.borderFactor = 0;
  48395. }
  48396. return DecimationTriangle;
  48397. }());
  48398. BABYLON.DecimationTriangle = DecimationTriangle;
  48399. var DecimationVertex = (function () {
  48400. function DecimationVertex(position, id) {
  48401. this.position = position;
  48402. this.id = id;
  48403. this.isBorder = true;
  48404. this.q = new QuadraticMatrix();
  48405. this.triangleCount = 0;
  48406. this.triangleStart = 0;
  48407. this.originalOffsets = [];
  48408. }
  48409. DecimationVertex.prototype.updatePosition = function (newPosition) {
  48410. this.position.copyFrom(newPosition);
  48411. };
  48412. return DecimationVertex;
  48413. }());
  48414. BABYLON.DecimationVertex = DecimationVertex;
  48415. var QuadraticMatrix = (function () {
  48416. function QuadraticMatrix(data) {
  48417. this.data = new Array(10);
  48418. for (var i = 0; i < 10; ++i) {
  48419. if (data && data[i]) {
  48420. this.data[i] = data[i];
  48421. }
  48422. else {
  48423. this.data[i] = 0;
  48424. }
  48425. }
  48426. }
  48427. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  48428. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  48429. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  48430. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  48431. return det;
  48432. };
  48433. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  48434. for (var i = 0; i < 10; ++i) {
  48435. this.data[i] += matrix.data[i];
  48436. }
  48437. };
  48438. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  48439. for (var i = 0; i < 10; ++i) {
  48440. this.data[i] += data[i];
  48441. }
  48442. };
  48443. QuadraticMatrix.prototype.add = function (matrix) {
  48444. var m = new QuadraticMatrix();
  48445. for (var i = 0; i < 10; ++i) {
  48446. m.data[i] = this.data[i] + matrix.data[i];
  48447. }
  48448. return m;
  48449. };
  48450. QuadraticMatrix.FromData = function (a, b, c, d) {
  48451. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  48452. };
  48453. //returning an array to avoid garbage collection
  48454. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  48455. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  48456. };
  48457. return QuadraticMatrix;
  48458. }());
  48459. BABYLON.QuadraticMatrix = QuadraticMatrix;
  48460. var Reference = (function () {
  48461. function Reference(vertexId, triangleId) {
  48462. this.vertexId = vertexId;
  48463. this.triangleId = triangleId;
  48464. }
  48465. return Reference;
  48466. }());
  48467. BABYLON.Reference = Reference;
  48468. /**
  48469. * An implementation of the Quadratic Error simplification algorithm.
  48470. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  48471. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  48472. * @author RaananW
  48473. */
  48474. var QuadraticErrorSimplification = (function () {
  48475. function QuadraticErrorSimplification(_mesh) {
  48476. this._mesh = _mesh;
  48477. this.initialized = false;
  48478. this.syncIterations = 5000;
  48479. this.aggressiveness = 7;
  48480. this.decimationIterations = 100;
  48481. this.boundingBoxEpsilon = BABYLON.Epsilon;
  48482. }
  48483. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  48484. var _this = this;
  48485. this.initDecimatedMesh();
  48486. //iterating through the submeshes array, one after the other.
  48487. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  48488. _this.initWithMesh(loop.index, function () {
  48489. _this.runDecimation(settings, loop.index, function () {
  48490. loop.executeNext();
  48491. });
  48492. }, settings.optimizeMesh);
  48493. }, function () {
  48494. setTimeout(function () {
  48495. successCallback(_this._reconstructedMesh);
  48496. }, 0);
  48497. });
  48498. };
  48499. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  48500. var _this = this;
  48501. var gCount = 0;
  48502. triangle.vertices.forEach(function (vertex) {
  48503. var count = 0;
  48504. var vPos = vertex.position;
  48505. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  48506. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  48507. ++count;
  48508. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  48509. ++count;
  48510. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  48511. ++count;
  48512. if (count > 1) {
  48513. ++gCount;
  48514. }
  48515. ;
  48516. });
  48517. if (gCount > 1) {
  48518. console.log(triangle, gCount);
  48519. }
  48520. return gCount > 1;
  48521. };
  48522. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  48523. var _this = this;
  48524. var targetCount = ~~(this.triangles.length * settings.quality);
  48525. var deletedTriangles = 0;
  48526. var triangleCount = this.triangles.length;
  48527. var iterationFunction = function (iteration, callback) {
  48528. setTimeout(function () {
  48529. if (iteration % 5 === 0) {
  48530. _this.updateMesh(iteration === 0);
  48531. }
  48532. for (var i = 0; i < _this.triangles.length; ++i) {
  48533. _this.triangles[i].isDirty = false;
  48534. }
  48535. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  48536. var trianglesIterator = function (i) {
  48537. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  48538. var t = _this.triangles[tIdx];
  48539. if (!t)
  48540. return;
  48541. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  48542. return;
  48543. }
  48544. for (var j = 0; j < 3; ++j) {
  48545. if (t.error[j] < threshold) {
  48546. var deleted0 = [];
  48547. var deleted1 = [];
  48548. var v0 = t.vertices[j];
  48549. var v1 = t.vertices[(j + 1) % 3];
  48550. if (v0.isBorder || v1.isBorder)
  48551. continue;
  48552. var p = BABYLON.Vector3.Zero();
  48553. var n = BABYLON.Vector3.Zero();
  48554. var uv = BABYLON.Vector2.Zero();
  48555. var color = new BABYLON.Color4(0, 0, 0, 1);
  48556. _this.calculateError(v0, v1, p, n, uv, color);
  48557. var delTr = [];
  48558. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  48559. continue;
  48560. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  48561. continue;
  48562. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  48563. continue;
  48564. var uniqueArray = [];
  48565. delTr.forEach(function (deletedT) {
  48566. if (uniqueArray.indexOf(deletedT) === -1) {
  48567. deletedT.deletePending = true;
  48568. uniqueArray.push(deletedT);
  48569. }
  48570. });
  48571. if (uniqueArray.length % 2 !== 0) {
  48572. continue;
  48573. }
  48574. v0.q = v1.q.add(v0.q);
  48575. v0.updatePosition(p);
  48576. var tStart = _this.references.length;
  48577. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  48578. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  48579. var tCount = _this.references.length - tStart;
  48580. if (tCount <= v0.triangleCount) {
  48581. if (tCount) {
  48582. for (var c = 0; c < tCount; c++) {
  48583. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  48584. }
  48585. }
  48586. }
  48587. else {
  48588. v0.triangleStart = tStart;
  48589. }
  48590. v0.triangleCount = tCount;
  48591. break;
  48592. }
  48593. }
  48594. };
  48595. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  48596. }, 0);
  48597. };
  48598. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  48599. if (triangleCount - deletedTriangles <= targetCount)
  48600. loop.breakLoop();
  48601. else {
  48602. iterationFunction(loop.index, function () {
  48603. loop.executeNext();
  48604. });
  48605. }
  48606. }, function () {
  48607. setTimeout(function () {
  48608. //reconstruct this part of the mesh
  48609. _this.reconstructMesh(submeshIndex);
  48610. successCallback();
  48611. }, 0);
  48612. });
  48613. };
  48614. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  48615. var _this = this;
  48616. this.vertices = [];
  48617. this.triangles = [];
  48618. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48619. var indices = this._mesh.getIndices();
  48620. var submesh = this._mesh.subMeshes[submeshIndex];
  48621. var findInVertices = function (positionToSearch) {
  48622. if (optimizeMesh) {
  48623. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  48624. if (_this.vertices[ii].position.equals(positionToSearch)) {
  48625. return _this.vertices[ii];
  48626. }
  48627. }
  48628. }
  48629. return null;
  48630. };
  48631. var vertexReferences = [];
  48632. var vertexInit = function (i) {
  48633. var offset = i + submesh.verticesStart;
  48634. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  48635. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  48636. vertex.originalOffsets.push(offset);
  48637. if (vertex.id === _this.vertices.length) {
  48638. _this.vertices.push(vertex);
  48639. }
  48640. vertexReferences.push(vertex.id);
  48641. };
  48642. //var totalVertices = mesh.getTotalVertices();
  48643. var totalVertices = submesh.verticesCount;
  48644. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  48645. var indicesInit = function (i) {
  48646. var offset = (submesh.indexStart / 3) + i;
  48647. var pos = (offset * 3);
  48648. var i0 = indices[pos + 0];
  48649. var i1 = indices[pos + 1];
  48650. var i2 = indices[pos + 2];
  48651. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  48652. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  48653. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  48654. var triangle = new DecimationTriangle([v0, v1, v2]);
  48655. triangle.originalOffset = pos;
  48656. _this.triangles.push(triangle);
  48657. };
  48658. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  48659. _this.init(callback);
  48660. });
  48661. });
  48662. };
  48663. QuadraticErrorSimplification.prototype.init = function (callback) {
  48664. var _this = this;
  48665. var triangleInit1 = function (i) {
  48666. var t = _this.triangles[i];
  48667. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  48668. for (var j = 0; j < 3; j++) {
  48669. 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))));
  48670. }
  48671. };
  48672. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  48673. var triangleInit2 = function (i) {
  48674. var t = _this.triangles[i];
  48675. for (var j = 0; j < 3; ++j) {
  48676. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  48677. }
  48678. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  48679. };
  48680. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  48681. _this.initialized = true;
  48682. callback();
  48683. });
  48684. });
  48685. };
  48686. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  48687. var newTriangles = [];
  48688. var i;
  48689. for (i = 0; i < this.vertices.length; ++i) {
  48690. this.vertices[i].triangleCount = 0;
  48691. }
  48692. var t;
  48693. var j;
  48694. for (i = 0; i < this.triangles.length; ++i) {
  48695. if (!this.triangles[i].deleted) {
  48696. t = this.triangles[i];
  48697. for (j = 0; j < 3; ++j) {
  48698. t.vertices[j].triangleCount = 1;
  48699. }
  48700. newTriangles.push(t);
  48701. }
  48702. }
  48703. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  48704. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  48705. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  48706. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  48707. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48708. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48709. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48710. var vertexCount = 0;
  48711. for (i = 0; i < this.vertices.length; ++i) {
  48712. var vertex = this.vertices[i];
  48713. vertex.id = vertexCount;
  48714. if (vertex.triangleCount) {
  48715. vertex.originalOffsets.forEach(function (originalOffset) {
  48716. newPositionData.push(vertex.position.x);
  48717. newPositionData.push(vertex.position.y);
  48718. newPositionData.push(vertex.position.z);
  48719. newNormalData.push(normalData[originalOffset * 3]);
  48720. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  48721. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  48722. if (uvs && uvs.length) {
  48723. newUVsData.push(uvs[(originalOffset * 2)]);
  48724. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  48725. }
  48726. else if (colorsData && colorsData.length) {
  48727. newColorsData.push(colorsData[(originalOffset * 4)]);
  48728. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  48729. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  48730. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  48731. }
  48732. ++vertexCount;
  48733. });
  48734. }
  48735. }
  48736. var startingIndex = this._reconstructedMesh.getTotalIndices();
  48737. var startingVertex = this._reconstructedMesh.getTotalVertices();
  48738. var submeshesArray = this._reconstructedMesh.subMeshes;
  48739. this._reconstructedMesh.subMeshes = [];
  48740. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  48741. var originalIndices = this._mesh.getIndices();
  48742. for (i = 0; i < newTriangles.length; ++i) {
  48743. t = newTriangles[i]; //now get the new referencing point for each vertex
  48744. [0, 1, 2].forEach(function (idx) {
  48745. var id = originalIndices[t.originalOffset + idx];
  48746. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  48747. if (offset < 0)
  48748. offset = 0;
  48749. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  48750. });
  48751. }
  48752. //overwriting the old vertex buffers and indices.
  48753. this._reconstructedMesh.setIndices(newIndicesArray);
  48754. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  48755. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  48756. if (newUVsData.length > 0)
  48757. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  48758. if (newColorsData.length > 0)
  48759. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  48760. //create submesh
  48761. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  48762. if (submeshIndex > 0) {
  48763. this._reconstructedMesh.subMeshes = [];
  48764. submeshesArray.forEach(function (submesh) {
  48765. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  48766. });
  48767. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  48768. }
  48769. };
  48770. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  48771. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  48772. this._reconstructedMesh.material = this._mesh.material;
  48773. this._reconstructedMesh.parent = this._mesh.parent;
  48774. this._reconstructedMesh.isVisible = false;
  48775. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  48776. };
  48777. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  48778. for (var i = 0; i < vertex1.triangleCount; ++i) {
  48779. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  48780. if (t.deleted)
  48781. continue;
  48782. var s = this.references[vertex1.triangleStart + i].vertexId;
  48783. var v1 = t.vertices[(s + 1) % 3];
  48784. var v2 = t.vertices[(s + 2) % 3];
  48785. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  48786. deletedArray[i] = true;
  48787. delTr.push(t);
  48788. continue;
  48789. }
  48790. var d1 = v1.position.subtract(point);
  48791. d1 = d1.normalize();
  48792. var d2 = v2.position.subtract(point);
  48793. d2 = d2.normalize();
  48794. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  48795. return true;
  48796. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  48797. deletedArray[i] = false;
  48798. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  48799. return true;
  48800. }
  48801. return false;
  48802. };
  48803. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  48804. var newDeleted = deletedTriangles;
  48805. for (var i = 0; i < vertex.triangleCount; ++i) {
  48806. var ref = this.references[vertex.triangleStart + i];
  48807. var t = this.triangles[ref.triangleId];
  48808. if (t.deleted)
  48809. continue;
  48810. if (deletedArray[i] && t.deletePending) {
  48811. t.deleted = true;
  48812. newDeleted++;
  48813. continue;
  48814. }
  48815. t.vertices[ref.vertexId] = origVertex;
  48816. t.isDirty = true;
  48817. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  48818. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  48819. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  48820. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  48821. this.references.push(ref);
  48822. }
  48823. return newDeleted;
  48824. };
  48825. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  48826. for (var i = 0; i < this.vertices.length; ++i) {
  48827. var vCount = [];
  48828. var vId = [];
  48829. var v = this.vertices[i];
  48830. var j;
  48831. for (j = 0; j < v.triangleCount; ++j) {
  48832. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  48833. for (var ii = 0; ii < 3; ii++) {
  48834. var ofs = 0;
  48835. var vv = triangle.vertices[ii];
  48836. while (ofs < vCount.length) {
  48837. if (vId[ofs] === vv.id)
  48838. break;
  48839. ++ofs;
  48840. }
  48841. if (ofs === vCount.length) {
  48842. vCount.push(1);
  48843. vId.push(vv.id);
  48844. }
  48845. else {
  48846. vCount[ofs]++;
  48847. }
  48848. }
  48849. }
  48850. for (j = 0; j < vCount.length; ++j) {
  48851. if (vCount[j] === 1) {
  48852. this.vertices[vId[j]].isBorder = true;
  48853. }
  48854. else {
  48855. this.vertices[vId[j]].isBorder = false;
  48856. }
  48857. }
  48858. }
  48859. };
  48860. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  48861. if (identifyBorders === void 0) { identifyBorders = false; }
  48862. var i;
  48863. if (!identifyBorders) {
  48864. var newTrianglesVector = [];
  48865. for (i = 0; i < this.triangles.length; ++i) {
  48866. if (!this.triangles[i].deleted) {
  48867. newTrianglesVector.push(this.triangles[i]);
  48868. }
  48869. }
  48870. this.triangles = newTrianglesVector;
  48871. }
  48872. for (i = 0; i < this.vertices.length; ++i) {
  48873. this.vertices[i].triangleCount = 0;
  48874. this.vertices[i].triangleStart = 0;
  48875. }
  48876. var t;
  48877. var j;
  48878. var v;
  48879. for (i = 0; i < this.triangles.length; ++i) {
  48880. t = this.triangles[i];
  48881. for (j = 0; j < 3; ++j) {
  48882. v = t.vertices[j];
  48883. v.triangleCount++;
  48884. }
  48885. }
  48886. var tStart = 0;
  48887. for (i = 0; i < this.vertices.length; ++i) {
  48888. this.vertices[i].triangleStart = tStart;
  48889. tStart += this.vertices[i].triangleCount;
  48890. this.vertices[i].triangleCount = 0;
  48891. }
  48892. var newReferences = new Array(this.triangles.length * 3);
  48893. for (i = 0; i < this.triangles.length; ++i) {
  48894. t = this.triangles[i];
  48895. for (j = 0; j < 3; ++j) {
  48896. v = t.vertices[j];
  48897. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  48898. v.triangleCount++;
  48899. }
  48900. }
  48901. this.references = newReferences;
  48902. if (identifyBorders) {
  48903. this.identifyBorder();
  48904. }
  48905. };
  48906. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  48907. var x = point.x;
  48908. var y = point.y;
  48909. var z = point.z;
  48910. 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
  48911. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  48912. };
  48913. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  48914. var q = vertex1.q.add(vertex2.q);
  48915. var border = vertex1.isBorder && vertex2.isBorder;
  48916. var error = 0;
  48917. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  48918. if (qDet !== 0 && !border) {
  48919. if (!pointResult) {
  48920. pointResult = BABYLON.Vector3.Zero();
  48921. }
  48922. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  48923. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  48924. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  48925. error = this.vertexError(q, pointResult);
  48926. }
  48927. else {
  48928. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  48929. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  48930. var error1 = this.vertexError(q, vertex1.position);
  48931. var error2 = this.vertexError(q, vertex2.position);
  48932. var error3 = this.vertexError(q, p3);
  48933. error = Math.min(error1, error2, error3);
  48934. if (error === error1) {
  48935. if (pointResult) {
  48936. pointResult.copyFrom(vertex1.position);
  48937. }
  48938. }
  48939. else if (error === error2) {
  48940. if (pointResult) {
  48941. pointResult.copyFrom(vertex2.position);
  48942. }
  48943. }
  48944. else {
  48945. if (pointResult) {
  48946. pointResult.copyFrom(p3);
  48947. }
  48948. }
  48949. }
  48950. return error;
  48951. };
  48952. return QuadraticErrorSimplification;
  48953. }());
  48954. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  48955. })(BABYLON || (BABYLON = {}));
  48956. var BABYLON;
  48957. (function (BABYLON) {
  48958. var serializedGeometries = [];
  48959. var serializeGeometry = function (geometry, serializationGeometries) {
  48960. if (serializedGeometries[geometry.id]) {
  48961. return;
  48962. }
  48963. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  48964. serializationGeometries.boxes.push(geometry.serialize());
  48965. }
  48966. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  48967. serializationGeometries.spheres.push(geometry.serialize());
  48968. }
  48969. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  48970. serializationGeometries.cylinders.push(geometry.serialize());
  48971. }
  48972. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  48973. serializationGeometries.toruses.push(geometry.serialize());
  48974. }
  48975. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  48976. serializationGeometries.grounds.push(geometry.serialize());
  48977. }
  48978. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  48979. serializationGeometries.planes.push(geometry.serialize());
  48980. }
  48981. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  48982. serializationGeometries.torusKnots.push(geometry.serialize());
  48983. }
  48984. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  48985. throw new Error("Unknown primitive type");
  48986. }
  48987. else {
  48988. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  48989. }
  48990. serializedGeometries[geometry.id] = true;
  48991. };
  48992. var serializeMesh = function (mesh, serializationScene) {
  48993. var serializationObject = {};
  48994. serializationObject.name = mesh.name;
  48995. serializationObject.id = mesh.id;
  48996. if (BABYLON.Tags.HasTags(mesh)) {
  48997. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  48998. }
  48999. serializationObject.position = mesh.position.asArray();
  49000. if (mesh.rotationQuaternion) {
  49001. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  49002. }
  49003. else if (mesh.rotation) {
  49004. serializationObject.rotation = mesh.rotation.asArray();
  49005. }
  49006. serializationObject.scaling = mesh.scaling.asArray();
  49007. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  49008. serializationObject.isEnabled = mesh.isEnabled();
  49009. serializationObject.isVisible = mesh.isVisible;
  49010. serializationObject.infiniteDistance = mesh.infiniteDistance;
  49011. serializationObject.pickable = mesh.isPickable;
  49012. serializationObject.receiveShadows = mesh.receiveShadows;
  49013. serializationObject.billboardMode = mesh.billboardMode;
  49014. serializationObject.visibility = mesh.visibility;
  49015. serializationObject.checkCollisions = mesh.checkCollisions;
  49016. // Parent
  49017. if (mesh.parent) {
  49018. serializationObject.parentId = mesh.parent.id;
  49019. }
  49020. // Geometry
  49021. var geometry = mesh._geometry;
  49022. if (geometry) {
  49023. var geometryId = geometry.id;
  49024. serializationObject.geometryId = geometryId;
  49025. if (!mesh.getScene().getGeometryByID(geometryId)) {
  49026. // 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
  49027. serializeGeometry(geometry, serializationScene.geometries);
  49028. }
  49029. // SubMeshes
  49030. serializationObject.subMeshes = [];
  49031. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  49032. var subMesh = mesh.subMeshes[subIndex];
  49033. serializationObject.subMeshes.push({
  49034. materialIndex: subMesh.materialIndex,
  49035. verticesStart: subMesh.verticesStart,
  49036. verticesCount: subMesh.verticesCount,
  49037. indexStart: subMesh.indexStart,
  49038. indexCount: subMesh.indexCount
  49039. });
  49040. }
  49041. }
  49042. // Material
  49043. if (mesh.material) {
  49044. serializationObject.materialId = mesh.material.id;
  49045. }
  49046. else {
  49047. mesh.material = null;
  49048. }
  49049. // Skeleton
  49050. if (mesh.skeleton) {
  49051. serializationObject.skeletonId = mesh.skeleton.id;
  49052. }
  49053. // Physics
  49054. //TODO implement correct serialization for physics impostors.
  49055. if (mesh.getPhysicsImpostor()) {
  49056. serializationObject.physicsMass = mesh.getPhysicsMass();
  49057. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  49058. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  49059. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  49060. }
  49061. // Instances
  49062. serializationObject.instances = [];
  49063. for (var index = 0; index < mesh.instances.length; index++) {
  49064. var instance = mesh.instances[index];
  49065. var serializationInstance = {
  49066. name: instance.name,
  49067. position: instance.position.asArray(),
  49068. scaling: instance.scaling.asArray()
  49069. };
  49070. if (instance.rotationQuaternion) {
  49071. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  49072. }
  49073. else if (instance.rotation) {
  49074. serializationInstance.rotation = instance.rotation.asArray();
  49075. }
  49076. serializationObject.instances.push(serializationInstance);
  49077. // Animations
  49078. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  49079. serializationInstance.ranges = instance.serializeAnimationRanges();
  49080. }
  49081. // Animations
  49082. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  49083. serializationObject.ranges = mesh.serializeAnimationRanges();
  49084. // Layer mask
  49085. serializationObject.layerMask = mesh.layerMask;
  49086. // Action Manager
  49087. if (mesh.actionManager) {
  49088. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  49089. }
  49090. return serializationObject;
  49091. };
  49092. var finalizeSingleMesh = function (mesh, serializationObject) {
  49093. //only works if the mesh is already loaded
  49094. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  49095. //serialize material
  49096. if (mesh.material) {
  49097. if (mesh.material instanceof BABYLON.StandardMaterial) {
  49098. serializationObject.materials = serializationObject.materials || [];
  49099. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  49100. serializationObject.materials.push(mesh.material.serialize());
  49101. }
  49102. }
  49103. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  49104. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  49105. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  49106. serializationObject.multiMaterials.push(mesh.material.serialize());
  49107. }
  49108. }
  49109. }
  49110. //serialize geometry
  49111. var geometry = mesh._geometry;
  49112. if (geometry) {
  49113. if (!serializationObject.geometries) {
  49114. serializationObject.geometries = {};
  49115. serializationObject.geometries.boxes = [];
  49116. serializationObject.geometries.spheres = [];
  49117. serializationObject.geometries.cylinders = [];
  49118. serializationObject.geometries.toruses = [];
  49119. serializationObject.geometries.grounds = [];
  49120. serializationObject.geometries.planes = [];
  49121. serializationObject.geometries.torusKnots = [];
  49122. serializationObject.geometries.vertexData = [];
  49123. }
  49124. serializeGeometry(geometry, serializationObject.geometries);
  49125. }
  49126. // Skeletons
  49127. if (mesh.skeleton) {
  49128. serializationObject.skeletons = serializationObject.skeletons || [];
  49129. serializationObject.skeletons.push(mesh.skeleton.serialize());
  49130. }
  49131. //serialize the actual mesh
  49132. serializationObject.meshes = serializationObject.meshes || [];
  49133. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  49134. }
  49135. };
  49136. var SceneSerializer = (function () {
  49137. function SceneSerializer() {
  49138. }
  49139. SceneSerializer.ClearCache = function () {
  49140. serializedGeometries = [];
  49141. };
  49142. SceneSerializer.Serialize = function (scene) {
  49143. var serializationObject = {};
  49144. // Scene
  49145. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  49146. serializationObject.autoClear = scene.autoClear;
  49147. serializationObject.clearColor = scene.clearColor.asArray();
  49148. serializationObject.ambientColor = scene.ambientColor.asArray();
  49149. serializationObject.gravity = scene.gravity.asArray();
  49150. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  49151. serializationObject.workerCollisions = scene.workerCollisions;
  49152. // Fog
  49153. if (scene.fogMode && scene.fogMode !== 0) {
  49154. serializationObject.fogMode = scene.fogMode;
  49155. serializationObject.fogColor = scene.fogColor.asArray();
  49156. serializationObject.fogStart = scene.fogStart;
  49157. serializationObject.fogEnd = scene.fogEnd;
  49158. serializationObject.fogDensity = scene.fogDensity;
  49159. }
  49160. //Physics
  49161. if (scene.isPhysicsEnabled()) {
  49162. serializationObject.physicsEnabled = true;
  49163. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  49164. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  49165. }
  49166. // Lights
  49167. serializationObject.lights = [];
  49168. var index;
  49169. var light;
  49170. for (index = 0; index < scene.lights.length; index++) {
  49171. light = scene.lights[index];
  49172. serializationObject.lights.push(light.serialize());
  49173. }
  49174. // Cameras
  49175. serializationObject.cameras = [];
  49176. for (index = 0; index < scene.cameras.length; index++) {
  49177. var camera = scene.cameras[index];
  49178. serializationObject.cameras.push(camera.serialize());
  49179. }
  49180. if (scene.activeCamera) {
  49181. serializationObject.activeCameraID = scene.activeCamera.id;
  49182. }
  49183. // Animations
  49184. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  49185. // Materials
  49186. serializationObject.materials = [];
  49187. serializationObject.multiMaterials = [];
  49188. var material;
  49189. for (index = 0; index < scene.materials.length; index++) {
  49190. material = scene.materials[index];
  49191. serializationObject.materials.push(material.serialize());
  49192. }
  49193. // MultiMaterials
  49194. serializationObject.multiMaterials = [];
  49195. for (index = 0; index < scene.multiMaterials.length; index++) {
  49196. var multiMaterial = scene.multiMaterials[index];
  49197. serializationObject.multiMaterials.push(multiMaterial.serialize());
  49198. }
  49199. // Skeletons
  49200. serializationObject.skeletons = [];
  49201. for (index = 0; index < scene.skeletons.length; index++) {
  49202. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  49203. }
  49204. // Geometries
  49205. serializationObject.geometries = {};
  49206. serializationObject.geometries.boxes = [];
  49207. serializationObject.geometries.spheres = [];
  49208. serializationObject.geometries.cylinders = [];
  49209. serializationObject.geometries.toruses = [];
  49210. serializationObject.geometries.grounds = [];
  49211. serializationObject.geometries.planes = [];
  49212. serializationObject.geometries.torusKnots = [];
  49213. serializationObject.geometries.vertexData = [];
  49214. serializedGeometries = [];
  49215. var geometries = scene.getGeometries();
  49216. for (index = 0; index < geometries.length; index++) {
  49217. var geometry = geometries[index];
  49218. if (geometry.isReady()) {
  49219. serializeGeometry(geometry, serializationObject.geometries);
  49220. }
  49221. }
  49222. // Meshes
  49223. serializationObject.meshes = [];
  49224. for (index = 0; index < scene.meshes.length; index++) {
  49225. var abstractMesh = scene.meshes[index];
  49226. if (abstractMesh instanceof BABYLON.Mesh) {
  49227. var mesh = abstractMesh;
  49228. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  49229. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  49230. }
  49231. }
  49232. }
  49233. // Particles Systems
  49234. serializationObject.particleSystems = [];
  49235. for (index = 0; index < scene.particleSystems.length; index++) {
  49236. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  49237. }
  49238. // Lens flares
  49239. serializationObject.lensFlareSystems = [];
  49240. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  49241. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  49242. }
  49243. // Shadows
  49244. serializationObject.shadowGenerators = [];
  49245. for (index = 0; index < scene.lights.length; index++) {
  49246. light = scene.lights[index];
  49247. if (light.getShadowGenerator()) {
  49248. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  49249. }
  49250. }
  49251. // Action Manager
  49252. if (scene.actionManager) {
  49253. serializationObject.actions = scene.actionManager.serialize("scene");
  49254. }
  49255. // Audio
  49256. serializationObject.sounds = [];
  49257. for (index = 0; index < scene.soundTracks.length; index++) {
  49258. var soundtrack = scene.soundTracks[index];
  49259. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  49260. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  49261. }
  49262. }
  49263. return serializationObject;
  49264. };
  49265. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  49266. if (withParents === void 0) { withParents = false; }
  49267. if (withChildren === void 0) { withChildren = false; }
  49268. var serializationObject = {};
  49269. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  49270. if (withParents || withChildren) {
  49271. //deliberate for loop! not for each, appended should be processed as well.
  49272. for (var i = 0; i < toSerialize.length; ++i) {
  49273. if (withChildren) {
  49274. toSerialize[i].getDescendants().forEach(function (node) {
  49275. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  49276. toSerialize.push(node);
  49277. }
  49278. });
  49279. }
  49280. //make sure the array doesn't contain the object already
  49281. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  49282. toSerialize.push(toSerialize[i].parent);
  49283. }
  49284. }
  49285. }
  49286. toSerialize.forEach(function (mesh) {
  49287. finalizeSingleMesh(mesh, serializationObject);
  49288. });
  49289. return serializationObject;
  49290. };
  49291. return SceneSerializer;
  49292. }());
  49293. BABYLON.SceneSerializer = SceneSerializer;
  49294. })(BABYLON || (BABYLON = {}));
  49295. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  49296. // Huge respect for a such great lib.
  49297. // Earcut license:
  49298. // Copyright (c) 2016, Mapbox
  49299. //
  49300. // Permission to use, copy, modify, and/or distribute this software for any purpose
  49301. // with or without fee is hereby granted, provided that the above copyright notice
  49302. // and this permission notice appear in all copies.
  49303. //
  49304. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  49305. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  49306. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  49307. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  49308. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  49309. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  49310. // THIS SOFTWARE.
  49311. var Earcut;
  49312. (function (Earcut) {
  49313. /**
  49314. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  49315. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  49316. * @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).
  49317. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  49318. */
  49319. function earcut(data, holeIndices, dim) {
  49320. dim = dim || 2;
  49321. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  49322. if (!outerNode)
  49323. return triangles;
  49324. var minX, minY, maxX, maxY, x, y, size;
  49325. if (hasHoles)
  49326. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  49327. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  49328. if (data.length > 80 * dim) {
  49329. minX = maxX = data[0];
  49330. minY = maxY = data[1];
  49331. for (var i = dim; i < outerLen; i += dim) {
  49332. x = data[i];
  49333. y = data[i + 1];
  49334. if (x < minX)
  49335. minX = x;
  49336. if (y < minY)
  49337. minY = y;
  49338. if (x > maxX)
  49339. maxX = x;
  49340. if (y > maxY)
  49341. maxY = y;
  49342. }
  49343. // minX, minY and size are later used to transform coords into integers for z-order calculation
  49344. size = Math.max(maxX - minX, maxY - minY);
  49345. }
  49346. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  49347. return triangles;
  49348. }
  49349. Earcut.earcut = earcut;
  49350. // create a circular doubly linked list from polygon points in the specified winding order
  49351. function linkedList(data, start, end, dim, clockwise) {
  49352. var i, last;
  49353. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  49354. for (i = start; i < end; i += dim)
  49355. last = insertNode(i, data[i], data[i + 1], last);
  49356. }
  49357. else {
  49358. for (i = end - dim; i >= start; i -= dim)
  49359. last = insertNode(i, data[i], data[i + 1], last);
  49360. }
  49361. if (last && equals(last, last.next)) {
  49362. removeNode(last);
  49363. last = last.next;
  49364. }
  49365. return last;
  49366. }
  49367. // eliminate colinear or duplicate points
  49368. function filterPoints(start, end) {
  49369. if (!start)
  49370. return start;
  49371. if (!end)
  49372. end = start;
  49373. var p = start, again;
  49374. do {
  49375. again = false;
  49376. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  49377. removeNode(p);
  49378. p = end = p.prev;
  49379. if (p === p.next)
  49380. return null;
  49381. again = true;
  49382. }
  49383. else {
  49384. p = p.next;
  49385. }
  49386. } while (again || p !== end);
  49387. return end;
  49388. }
  49389. // main ear slicing loop which triangulates a polygon (given as a linked list)
  49390. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  49391. if (!ear)
  49392. return;
  49393. // interlink polygon nodes in z-order
  49394. if (!pass && size)
  49395. indexCurve(ear, minX, minY, size);
  49396. var stop = ear, prev, next;
  49397. // iterate through ears, slicing them one by one
  49398. while (ear.prev !== ear.next) {
  49399. prev = ear.prev;
  49400. next = ear.next;
  49401. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  49402. // cut off the triangle
  49403. triangles.push(prev.i / dim);
  49404. triangles.push(ear.i / dim);
  49405. triangles.push(next.i / dim);
  49406. removeNode(ear);
  49407. // skipping the next vertice leads to less sliver triangles
  49408. ear = next.next;
  49409. stop = next.next;
  49410. continue;
  49411. }
  49412. ear = next;
  49413. // if we looped through the whole remaining polygon and can't find any more ears
  49414. if (ear === stop) {
  49415. // try filtering points and slicing again
  49416. if (!pass) {
  49417. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  49418. }
  49419. else if (pass === 1) {
  49420. ear = cureLocalIntersections(ear, triangles, dim);
  49421. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  49422. }
  49423. else if (pass === 2) {
  49424. splitEarcut(ear, triangles, dim, minX, minY, size);
  49425. }
  49426. break;
  49427. }
  49428. }
  49429. }
  49430. // check whether a polygon node forms a valid ear with adjacent nodes
  49431. function isEar(ear) {
  49432. var a = ear.prev, b = ear, c = ear.next;
  49433. if (area(a, b, c) >= 0)
  49434. return false; // reflex, can't be an ear
  49435. // now make sure we don't have other points inside the potential ear
  49436. var p = ear.next.next;
  49437. while (p !== ear.prev) {
  49438. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  49439. area(p.prev, p, p.next) >= 0)
  49440. return false;
  49441. p = p.next;
  49442. }
  49443. return true;
  49444. }
  49445. function isEarHashed(ear, minX, minY, size) {
  49446. var a = ear.prev, b = ear, c = ear.next;
  49447. if (area(a, b, c) >= 0)
  49448. return false; // reflex, can't be an ear
  49449. // triangle bbox; min & max are calculated like this for speed
  49450. 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);
  49451. // z-order range for the current triangle bbox;
  49452. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  49453. // first look for points inside the triangle in increasing z-order
  49454. var p = ear.nextZ;
  49455. while (p && p.z <= maxZ) {
  49456. if (p !== ear.prev &&
  49457. p !== ear.next &&
  49458. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  49459. area(p.prev, p, p.next) >= 0)
  49460. return false;
  49461. p = p.nextZ;
  49462. }
  49463. // then look for points in decreasing z-order
  49464. p = ear.prevZ;
  49465. while (p && p.z >= minZ) {
  49466. if (p !== ear.prev &&
  49467. p !== ear.next &&
  49468. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  49469. area(p.prev, p, p.next) >= 0)
  49470. return false;
  49471. p = p.prevZ;
  49472. }
  49473. return true;
  49474. }
  49475. // go through all polygon nodes and cure small local self-intersections
  49476. function cureLocalIntersections(start, triangles, dim) {
  49477. var p = start;
  49478. do {
  49479. var a = p.prev, b = p.next.next;
  49480. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  49481. triangles.push(a.i / dim);
  49482. triangles.push(p.i / dim);
  49483. triangles.push(b.i / dim);
  49484. // remove two nodes involved
  49485. removeNode(p);
  49486. removeNode(p.next);
  49487. p = start = b;
  49488. }
  49489. p = p.next;
  49490. } while (p !== start);
  49491. return p;
  49492. }
  49493. // try splitting polygon into two and triangulate them independently
  49494. function splitEarcut(start, triangles, dim, minX, minY, size) {
  49495. // look for a valid diagonal that divides the polygon into two
  49496. var a = start;
  49497. do {
  49498. var b = a.next.next;
  49499. while (b !== a.prev) {
  49500. if (a.i !== b.i && isValidDiagonal(a, b)) {
  49501. // split the polygon in two by the diagonal
  49502. var c = splitPolygon(a, b);
  49503. // filter colinear points around the cuts
  49504. a = filterPoints(a, a.next);
  49505. c = filterPoints(c, c.next);
  49506. // run earcut on each half
  49507. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  49508. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  49509. return;
  49510. }
  49511. b = b.next;
  49512. }
  49513. a = a.next;
  49514. } while (a !== start);
  49515. }
  49516. // link every hole into the outer loop, producing a single-ring polygon without holes
  49517. function eliminateHoles(data, holeIndices, outerNode, dim) {
  49518. var queue = [], i, len, start, end, list;
  49519. for (i = 0, len = holeIndices.length; i < len; i++) {
  49520. start = holeIndices[i] * dim;
  49521. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  49522. list = linkedList(data, start, end, dim, false);
  49523. if (list === list.next)
  49524. list.steiner = true;
  49525. queue.push(getLeftmost(list));
  49526. }
  49527. queue.sort(compareX);
  49528. // process holes from left to right
  49529. for (i = 0; i < queue.length; i++) {
  49530. eliminateHole(queue[i], outerNode);
  49531. outerNode = filterPoints(outerNode, outerNode.next);
  49532. }
  49533. return outerNode;
  49534. }
  49535. function compareX(a, b) {
  49536. return a.x - b.x;
  49537. }
  49538. // find a bridge between vertices that connects hole with an outer ring and and link it
  49539. function eliminateHole(hole, outerNode) {
  49540. outerNode = findHoleBridge(hole, outerNode);
  49541. if (outerNode) {
  49542. var b = splitPolygon(outerNode, hole);
  49543. filterPoints(b, b.next);
  49544. }
  49545. }
  49546. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  49547. function findHoleBridge(hole, outerNode) {
  49548. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  49549. // find a segment intersected by a ray from the hole's leftmost point to the left;
  49550. // segment's endpoint with lesser x will be potential connection point
  49551. do {
  49552. if (hy <= p.y && hy >= p.next.y) {
  49553. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  49554. if (x <= hx && x > qx) {
  49555. qx = x;
  49556. if (x === hx) {
  49557. if (hy === p.y)
  49558. return p;
  49559. if (hy === p.next.y)
  49560. return p.next;
  49561. }
  49562. m = p.x < p.next.x ? p : p.next;
  49563. }
  49564. }
  49565. p = p.next;
  49566. } while (p !== outerNode);
  49567. if (!m)
  49568. return null;
  49569. if (hx === qx)
  49570. return m.prev; // hole touches outer segment; pick lower endpoint
  49571. // look for points inside the triangle of hole point, segment intersection and endpoint;
  49572. // if there are no points found, we have a valid connection;
  49573. // otherwise choose the point of the minimum angle with the ray as connection point
  49574. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  49575. p = m.next;
  49576. while (p !== stop) {
  49577. if (hx >= p.x &&
  49578. p.x >= mx &&
  49579. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  49580. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  49581. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  49582. m = p;
  49583. tanMin = tan;
  49584. }
  49585. }
  49586. p = p.next;
  49587. }
  49588. return m;
  49589. }
  49590. // interlink polygon nodes in z-order
  49591. function indexCurve(start, minX, minY, size) {
  49592. var p = start;
  49593. do {
  49594. if (p.z === null)
  49595. p.z = zOrder(p.x, p.y, minX, minY, size);
  49596. p.prevZ = p.prev;
  49597. p.nextZ = p.next;
  49598. p = p.next;
  49599. } while (p !== start);
  49600. p.prevZ.nextZ = null;
  49601. p.prevZ = null;
  49602. sortLinked(p);
  49603. }
  49604. // Simon Tatham's linked list merge sort algorithm
  49605. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  49606. function sortLinked(list) {
  49607. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  49608. do {
  49609. p = list;
  49610. list = null;
  49611. tail = null;
  49612. numMerges = 0;
  49613. while (p) {
  49614. numMerges++;
  49615. q = p;
  49616. pSize = 0;
  49617. for (i = 0; i < inSize; i++) {
  49618. pSize++;
  49619. q = q.nextZ;
  49620. if (!q)
  49621. break;
  49622. }
  49623. qSize = inSize;
  49624. while (pSize > 0 || (qSize > 0 && q)) {
  49625. if (pSize === 0) {
  49626. e = q;
  49627. q = q.nextZ;
  49628. qSize--;
  49629. }
  49630. else if (qSize === 0 || !q) {
  49631. e = p;
  49632. p = p.nextZ;
  49633. pSize--;
  49634. }
  49635. else if (p.z <= q.z) {
  49636. e = p;
  49637. p = p.nextZ;
  49638. pSize--;
  49639. }
  49640. else {
  49641. e = q;
  49642. q = q.nextZ;
  49643. qSize--;
  49644. }
  49645. if (tail)
  49646. tail.nextZ = e;
  49647. else
  49648. list = e;
  49649. e.prevZ = tail;
  49650. tail = e;
  49651. }
  49652. p = q;
  49653. }
  49654. tail.nextZ = null;
  49655. inSize *= 2;
  49656. } while (numMerges > 1);
  49657. return list;
  49658. }
  49659. // z-order of a point given coords and size of the data bounding box
  49660. function zOrder(x, y, minX, minY, size) {
  49661. // coords are transformed into non-negative 15-bit integer range
  49662. x = 32767 * (x - minX) / size;
  49663. y = 32767 * (y - minY) / size;
  49664. x = (x | (x << 8)) & 0x00FF00FF;
  49665. x = (x | (x << 4)) & 0x0F0F0F0F;
  49666. x = (x | (x << 2)) & 0x33333333;
  49667. x = (x | (x << 1)) & 0x55555555;
  49668. y = (y | (y << 8)) & 0x00FF00FF;
  49669. y = (y | (y << 4)) & 0x0F0F0F0F;
  49670. y = (y | (y << 2)) & 0x33333333;
  49671. y = (y | (y << 1)) & 0x55555555;
  49672. return x | (y << 1);
  49673. }
  49674. // find the leftmost node of a polygon ring
  49675. function getLeftmost(start) {
  49676. var p = start, leftmost = start;
  49677. do {
  49678. if (p.x < leftmost.x)
  49679. leftmost = p;
  49680. p = p.next;
  49681. } while (p !== start);
  49682. return leftmost;
  49683. }
  49684. // check if a point lies within a convex triangle
  49685. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  49686. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  49687. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  49688. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  49689. }
  49690. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  49691. function isValidDiagonal(a, b) {
  49692. return a.next.i !== b.i &&
  49693. a.prev.i !== b.i &&
  49694. !intersectsPolygon(a, b) &&
  49695. locallyInside(a, b) &&
  49696. locallyInside(b, a) &&
  49697. middleInside(a, b);
  49698. }
  49699. // signed area of a triangle
  49700. function area(p, q, r) {
  49701. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  49702. }
  49703. // check if two points are equal
  49704. function equals(p1, p2) {
  49705. return p1.x === p2.x && p1.y === p2.y;
  49706. }
  49707. // check if two segments intersect
  49708. function intersects(p1, q1, p2, q2) {
  49709. if ((equals(p1, q1) && equals(p2, q2)) ||
  49710. (equals(p1, q2) && equals(p2, q1)))
  49711. return true;
  49712. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  49713. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  49714. }
  49715. // check if a polygon diagonal intersects any polygon segments
  49716. function intersectsPolygon(a, b) {
  49717. var p = a;
  49718. do {
  49719. if (p.i !== a.i &&
  49720. p.next.i !== a.i &&
  49721. p.i !== b.i &&
  49722. p.next.i !== b.i &&
  49723. intersects(p, p.next, a, b))
  49724. return true;
  49725. p = p.next;
  49726. } while (p !== a);
  49727. return false;
  49728. }
  49729. // check if a polygon diagonal is locally inside the polygon
  49730. function locallyInside(a, b) {
  49731. return area(a.prev, a, a.next) < 0
  49732. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  49733. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  49734. }
  49735. // check if the middle point of a polygon diagonal is inside the polygon
  49736. function middleInside(a, b) {
  49737. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  49738. do {
  49739. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  49740. inside = !inside;
  49741. p = p.next;
  49742. } while (p !== a);
  49743. return inside;
  49744. }
  49745. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  49746. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  49747. function splitPolygon(a, b) {
  49748. 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;
  49749. a.next = b;
  49750. b.prev = a;
  49751. a2.next = an;
  49752. an.prev = a2;
  49753. b2.next = a2;
  49754. a2.prev = b2;
  49755. bp.next = b2;
  49756. b2.prev = bp;
  49757. return b2;
  49758. }
  49759. // create a node and optionally link it with previous one (in a circular doubly linked list)
  49760. function insertNode(i, x, y, last) {
  49761. var p = new Node(i, x, y);
  49762. if (!last) {
  49763. p.prev = p;
  49764. p.next = p;
  49765. }
  49766. else {
  49767. p.next = last.next;
  49768. p.prev = last;
  49769. last.next.prev = p;
  49770. last.next = p;
  49771. }
  49772. return p;
  49773. }
  49774. function removeNode(p) {
  49775. p.next.prev = p.prev;
  49776. p.prev.next = p.next;
  49777. if (p.prevZ)
  49778. p.prevZ.nextZ = p.nextZ;
  49779. if (p.nextZ)
  49780. p.nextZ.prevZ = p.prevZ;
  49781. }
  49782. function Node(i, x, y) {
  49783. // vertice index in coordinates array
  49784. this.i = i;
  49785. // vertex coordinates
  49786. this.x = x;
  49787. this.y = y;
  49788. // previous and next vertice nodes in a polygon ring
  49789. this.prev = null;
  49790. this.next = null;
  49791. // z-order curve value
  49792. this.z = null;
  49793. // previous and next nodes in z-order
  49794. this.prevZ = null;
  49795. this.nextZ = null;
  49796. // indicates whether this is a steiner point
  49797. this.steiner = false;
  49798. }
  49799. /**
  49800. * return a percentage difference between the polygon area and its triangulation area;
  49801. * used to verify correctness of triangulation
  49802. */
  49803. function deviation(data, holeIndices, dim, triangles) {
  49804. var hasHoles = holeIndices && holeIndices.length;
  49805. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  49806. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  49807. if (hasHoles) {
  49808. for (var i = 0, len = holeIndices.length; i < len; i++) {
  49809. var start = holeIndices[i] * dim;
  49810. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  49811. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  49812. }
  49813. }
  49814. var trianglesArea = 0;
  49815. for (i = 0; i < triangles.length; i += 3) {
  49816. var a = triangles[i] * dim;
  49817. var b = triangles[i + 1] * dim;
  49818. var c = triangles[i + 2] * dim;
  49819. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  49820. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  49821. }
  49822. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  49823. }
  49824. Earcut.deviation = deviation;
  49825. ;
  49826. function signedArea(data, start, end, dim) {
  49827. var sum = 0;
  49828. for (var i = start, j = end - dim; i < end; i += dim) {
  49829. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  49830. j = i;
  49831. }
  49832. return sum;
  49833. }
  49834. /**
  49835. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  49836. */
  49837. function flatten(data) {
  49838. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  49839. for (var i = 0; i < data.length; i++) {
  49840. for (var j = 0; j < data[i].length; j++) {
  49841. for (var d = 0; d < dim; d++)
  49842. result.vertices.push(data[i][j][d]);
  49843. }
  49844. if (i > 0) {
  49845. holeIndex += data[i - 1].length;
  49846. result.holes.push(holeIndex);
  49847. }
  49848. }
  49849. return result;
  49850. }
  49851. Earcut.flatten = flatten;
  49852. ;
  49853. })(Earcut || (Earcut = {}));
  49854. var BABYLON;
  49855. (function (BABYLON) {
  49856. // Unique ID when we import meshes from Babylon to CSG
  49857. var currentCSGMeshId = 0;
  49858. // # class Vertex
  49859. // Represents a vertex of a polygon. Use your own vertex class instead of this
  49860. // one to provide additional features like texture coordinates and vertex
  49861. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  49862. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  49863. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  49864. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  49865. // is not used anywhere else.
  49866. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  49867. var Vertex = (function () {
  49868. function Vertex(pos, normal, uv) {
  49869. this.pos = pos;
  49870. this.normal = normal;
  49871. this.uv = uv;
  49872. }
  49873. Vertex.prototype.clone = function () {
  49874. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  49875. };
  49876. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  49877. // orientation of a polygon is flipped.
  49878. Vertex.prototype.flip = function () {
  49879. this.normal = this.normal.scale(-1);
  49880. };
  49881. // Create a new vertex between this vertex and `other` by linearly
  49882. // interpolating all properties using a parameter of `t`. Subclasses should
  49883. // override this to interpolate additional properties.
  49884. Vertex.prototype.interpolate = function (other, t) {
  49885. 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));
  49886. };
  49887. return Vertex;
  49888. }());
  49889. // # class Plane
  49890. // Represents a plane in 3D space.
  49891. var Plane = (function () {
  49892. function Plane(normal, w) {
  49893. this.normal = normal;
  49894. this.w = w;
  49895. }
  49896. Plane.FromPoints = function (a, b, c) {
  49897. var v0 = c.subtract(a);
  49898. var v1 = b.subtract(a);
  49899. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  49900. return null;
  49901. }
  49902. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  49903. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  49904. };
  49905. Plane.prototype.clone = function () {
  49906. return new Plane(this.normal.clone(), this.w);
  49907. };
  49908. Plane.prototype.flip = function () {
  49909. this.normal.scaleInPlace(-1);
  49910. this.w = -this.w;
  49911. };
  49912. // Split `polygon` by this plane if needed, then put the polygon or polygon
  49913. // fragments in the appropriate lists. Coplanar polygons go into either
  49914. // `coplanarFront` or `coplanarBack` depending on their orientation with
  49915. // respect to this plane. Polygons in front or in back of this plane go into
  49916. // either `front` or `back`.
  49917. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  49918. var COPLANAR = 0;
  49919. var FRONT = 1;
  49920. var BACK = 2;
  49921. var SPANNING = 3;
  49922. // Classify each point as well as the entire polygon into one of the above
  49923. // four classes.
  49924. var polygonType = 0;
  49925. var types = [];
  49926. var i;
  49927. var t;
  49928. for (i = 0; i < polygon.vertices.length; i++) {
  49929. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  49930. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  49931. polygonType |= type;
  49932. types.push(type);
  49933. }
  49934. // Put the polygon in the correct list, splitting it when necessary.
  49935. switch (polygonType) {
  49936. case COPLANAR:
  49937. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  49938. break;
  49939. case FRONT:
  49940. front.push(polygon);
  49941. break;
  49942. case BACK:
  49943. back.push(polygon);
  49944. break;
  49945. case SPANNING:
  49946. var f = [], b = [];
  49947. for (i = 0; i < polygon.vertices.length; i++) {
  49948. var j = (i + 1) % polygon.vertices.length;
  49949. var ti = types[i], tj = types[j];
  49950. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  49951. if (ti !== BACK)
  49952. f.push(vi);
  49953. if (ti !== FRONT)
  49954. b.push(ti !== BACK ? vi.clone() : vi);
  49955. if ((ti | tj) === SPANNING) {
  49956. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  49957. var v = vi.interpolate(vj, t);
  49958. f.push(v);
  49959. b.push(v.clone());
  49960. }
  49961. }
  49962. var poly;
  49963. if (f.length >= 3) {
  49964. poly = new Polygon(f, polygon.shared);
  49965. if (poly.plane)
  49966. front.push(poly);
  49967. }
  49968. if (b.length >= 3) {
  49969. poly = new Polygon(b, polygon.shared);
  49970. if (poly.plane)
  49971. back.push(poly);
  49972. }
  49973. break;
  49974. }
  49975. };
  49976. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  49977. // point is on the plane.
  49978. Plane.EPSILON = 1e-5;
  49979. return Plane;
  49980. }());
  49981. // # class Polygon
  49982. // Represents a convex polygon. The vertices used to initialize a polygon must
  49983. // be coplanar and form a convex loop.
  49984. //
  49985. // Each convex polygon has a `shared` property, which is shared between all
  49986. // polygons that are clones of each other or were split from the same polygon.
  49987. // This can be used to define per-polygon properties (such as surface color).
  49988. var Polygon = (function () {
  49989. function Polygon(vertices, shared) {
  49990. this.vertices = vertices;
  49991. this.shared = shared;
  49992. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  49993. }
  49994. Polygon.prototype.clone = function () {
  49995. var vertices = this.vertices.map(function (v) { return v.clone(); });
  49996. return new Polygon(vertices, this.shared);
  49997. };
  49998. Polygon.prototype.flip = function () {
  49999. this.vertices.reverse().map(function (v) { v.flip(); });
  50000. this.plane.flip();
  50001. };
  50002. return Polygon;
  50003. }());
  50004. // # class Node
  50005. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  50006. // by picking a polygon to split along. That polygon (and all other coplanar
  50007. // polygons) are added directly to that node and the other polygons are added to
  50008. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  50009. // no distinction between internal and leaf nodes.
  50010. var Node = (function () {
  50011. function Node(polygons) {
  50012. this.plane = null;
  50013. this.front = null;
  50014. this.back = null;
  50015. this.polygons = [];
  50016. if (polygons) {
  50017. this.build(polygons);
  50018. }
  50019. }
  50020. Node.prototype.clone = function () {
  50021. var node = new Node();
  50022. node.plane = this.plane && this.plane.clone();
  50023. node.front = this.front && this.front.clone();
  50024. node.back = this.back && this.back.clone();
  50025. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  50026. return node;
  50027. };
  50028. // Convert solid space to empty space and empty space to solid space.
  50029. Node.prototype.invert = function () {
  50030. for (var i = 0; i < this.polygons.length; i++) {
  50031. this.polygons[i].flip();
  50032. }
  50033. if (this.plane) {
  50034. this.plane.flip();
  50035. }
  50036. if (this.front) {
  50037. this.front.invert();
  50038. }
  50039. if (this.back) {
  50040. this.back.invert();
  50041. }
  50042. var temp = this.front;
  50043. this.front = this.back;
  50044. this.back = temp;
  50045. };
  50046. // Recursively remove all polygons in `polygons` that are inside this BSP
  50047. // tree.
  50048. Node.prototype.clipPolygons = function (polygons) {
  50049. if (!this.plane)
  50050. return polygons.slice();
  50051. var front = [], back = [];
  50052. for (var i = 0; i < polygons.length; i++) {
  50053. this.plane.splitPolygon(polygons[i], front, back, front, back);
  50054. }
  50055. if (this.front) {
  50056. front = this.front.clipPolygons(front);
  50057. }
  50058. if (this.back) {
  50059. back = this.back.clipPolygons(back);
  50060. }
  50061. else {
  50062. back = [];
  50063. }
  50064. return front.concat(back);
  50065. };
  50066. // Remove all polygons in this BSP tree that are inside the other BSP tree
  50067. // `bsp`.
  50068. Node.prototype.clipTo = function (bsp) {
  50069. this.polygons = bsp.clipPolygons(this.polygons);
  50070. if (this.front)
  50071. this.front.clipTo(bsp);
  50072. if (this.back)
  50073. this.back.clipTo(bsp);
  50074. };
  50075. // Return a list of all polygons in this BSP tree.
  50076. Node.prototype.allPolygons = function () {
  50077. var polygons = this.polygons.slice();
  50078. if (this.front)
  50079. polygons = polygons.concat(this.front.allPolygons());
  50080. if (this.back)
  50081. polygons = polygons.concat(this.back.allPolygons());
  50082. return polygons;
  50083. };
  50084. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  50085. // new polygons are filtered down to the bottom of the tree and become new
  50086. // nodes there. Each set of polygons is partitioned using the first polygon
  50087. // (no heuristic is used to pick a good split).
  50088. Node.prototype.build = function (polygons) {
  50089. if (!polygons.length)
  50090. return;
  50091. if (!this.plane)
  50092. this.plane = polygons[0].plane.clone();
  50093. var front = [], back = [];
  50094. for (var i = 0; i < polygons.length; i++) {
  50095. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  50096. }
  50097. if (front.length) {
  50098. if (!this.front)
  50099. this.front = new Node();
  50100. this.front.build(front);
  50101. }
  50102. if (back.length) {
  50103. if (!this.back)
  50104. this.back = new Node();
  50105. this.back.build(back);
  50106. }
  50107. };
  50108. return Node;
  50109. }());
  50110. var CSG = (function () {
  50111. function CSG() {
  50112. this.polygons = new Array();
  50113. }
  50114. // Convert BABYLON.Mesh to BABYLON.CSG
  50115. CSG.FromMesh = function (mesh) {
  50116. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  50117. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  50118. if (mesh instanceof BABYLON.Mesh) {
  50119. mesh.computeWorldMatrix(true);
  50120. matrix = mesh.getWorldMatrix();
  50121. meshPosition = mesh.position.clone();
  50122. meshRotation = mesh.rotation.clone();
  50123. if (mesh.rotationQuaternion) {
  50124. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  50125. }
  50126. meshScaling = mesh.scaling.clone();
  50127. }
  50128. else {
  50129. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  50130. }
  50131. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50132. var subMeshes = mesh.subMeshes;
  50133. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  50134. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  50135. vertices = [];
  50136. for (var j = 0; j < 3; j++) {
  50137. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  50138. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  50139. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  50140. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  50141. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  50142. vertex = new Vertex(position, normal, uv);
  50143. vertices.push(vertex);
  50144. }
  50145. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  50146. // To handle the case of degenerated triangle
  50147. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  50148. if (polygon.plane)
  50149. polygons.push(polygon);
  50150. }
  50151. }
  50152. var csg = CSG.FromPolygons(polygons);
  50153. csg.matrix = matrix;
  50154. csg.position = meshPosition;
  50155. csg.rotation = meshRotation;
  50156. csg.scaling = meshScaling;
  50157. csg.rotationQuaternion = meshRotationQuaternion;
  50158. currentCSGMeshId++;
  50159. return csg;
  50160. };
  50161. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  50162. CSG.FromPolygons = function (polygons) {
  50163. var csg = new CSG();
  50164. csg.polygons = polygons;
  50165. return csg;
  50166. };
  50167. CSG.prototype.clone = function () {
  50168. var csg = new CSG();
  50169. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  50170. csg.copyTransformAttributes(this);
  50171. return csg;
  50172. };
  50173. CSG.prototype.toPolygons = function () {
  50174. return this.polygons;
  50175. };
  50176. CSG.prototype.union = function (csg) {
  50177. var a = new Node(this.clone().polygons);
  50178. var b = new Node(csg.clone().polygons);
  50179. a.clipTo(b);
  50180. b.clipTo(a);
  50181. b.invert();
  50182. b.clipTo(a);
  50183. b.invert();
  50184. a.build(b.allPolygons());
  50185. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  50186. };
  50187. CSG.prototype.unionInPlace = function (csg) {
  50188. var a = new Node(this.polygons);
  50189. var b = new Node(csg.polygons);
  50190. a.clipTo(b);
  50191. b.clipTo(a);
  50192. b.invert();
  50193. b.clipTo(a);
  50194. b.invert();
  50195. a.build(b.allPolygons());
  50196. this.polygons = a.allPolygons();
  50197. };
  50198. CSG.prototype.subtract = function (csg) {
  50199. var a = new Node(this.clone().polygons);
  50200. var b = new Node(csg.clone().polygons);
  50201. a.invert();
  50202. a.clipTo(b);
  50203. b.clipTo(a);
  50204. b.invert();
  50205. b.clipTo(a);
  50206. b.invert();
  50207. a.build(b.allPolygons());
  50208. a.invert();
  50209. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  50210. };
  50211. CSG.prototype.subtractInPlace = function (csg) {
  50212. var a = new Node(this.polygons);
  50213. var b = new Node(csg.polygons);
  50214. a.invert();
  50215. a.clipTo(b);
  50216. b.clipTo(a);
  50217. b.invert();
  50218. b.clipTo(a);
  50219. b.invert();
  50220. a.build(b.allPolygons());
  50221. a.invert();
  50222. this.polygons = a.allPolygons();
  50223. };
  50224. CSG.prototype.intersect = function (csg) {
  50225. var a = new Node(this.clone().polygons);
  50226. var b = new Node(csg.clone().polygons);
  50227. a.invert();
  50228. b.clipTo(a);
  50229. b.invert();
  50230. a.clipTo(b);
  50231. b.clipTo(a);
  50232. a.build(b.allPolygons());
  50233. a.invert();
  50234. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  50235. };
  50236. CSG.prototype.intersectInPlace = function (csg) {
  50237. var a = new Node(this.polygons);
  50238. var b = new Node(csg.polygons);
  50239. a.invert();
  50240. b.clipTo(a);
  50241. b.invert();
  50242. a.clipTo(b);
  50243. b.clipTo(a);
  50244. a.build(b.allPolygons());
  50245. a.invert();
  50246. this.polygons = a.allPolygons();
  50247. };
  50248. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  50249. // not modified.
  50250. CSG.prototype.inverse = function () {
  50251. var csg = this.clone();
  50252. csg.inverseInPlace();
  50253. return csg;
  50254. };
  50255. CSG.prototype.inverseInPlace = function () {
  50256. this.polygons.map(function (p) { p.flip(); });
  50257. };
  50258. // This is used to keep meshes transformations so they can be restored
  50259. // when we build back a Babylon Mesh
  50260. // NB : All CSG operations are performed in world coordinates
  50261. CSG.prototype.copyTransformAttributes = function (csg) {
  50262. this.matrix = csg.matrix;
  50263. this.position = csg.position;
  50264. this.rotation = csg.rotation;
  50265. this.scaling = csg.scaling;
  50266. this.rotationQuaternion = csg.rotationQuaternion;
  50267. return this;
  50268. };
  50269. // Build Raw mesh from CSG
  50270. // Coordinates here are in world space
  50271. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  50272. var matrix = this.matrix.clone();
  50273. matrix.invert();
  50274. 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;
  50275. if (keepSubMeshes) {
  50276. // Sort Polygons, since subMeshes are indices range
  50277. polygons.sort(function (a, b) {
  50278. if (a.shared.meshId === b.shared.meshId) {
  50279. return a.shared.subMeshId - b.shared.subMeshId;
  50280. }
  50281. else {
  50282. return a.shared.meshId - b.shared.meshId;
  50283. }
  50284. });
  50285. }
  50286. for (var i = 0, il = polygons.length; i < il; i++) {
  50287. polygon = polygons[i];
  50288. // Building SubMeshes
  50289. if (!subMesh_dict[polygon.shared.meshId]) {
  50290. subMesh_dict[polygon.shared.meshId] = {};
  50291. }
  50292. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  50293. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  50294. indexStart: +Infinity,
  50295. indexEnd: -Infinity,
  50296. materialIndex: polygon.shared.materialIndex
  50297. };
  50298. }
  50299. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  50300. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  50301. polygonIndices[0] = 0;
  50302. polygonIndices[1] = j - 1;
  50303. polygonIndices[2] = j;
  50304. for (var k = 0; k < 3; k++) {
  50305. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  50306. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  50307. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  50308. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  50309. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  50310. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  50311. // Check if 2 points can be merged
  50312. if (!(typeof vertex_idx !== 'undefined' &&
  50313. normals[vertex_idx * 3] === localNormal.x &&
  50314. normals[vertex_idx * 3 + 1] === localNormal.y &&
  50315. normals[vertex_idx * 3 + 2] === localNormal.z &&
  50316. uvs[vertex_idx * 2] === uv.x &&
  50317. uvs[vertex_idx * 2 + 1] === uv.y)) {
  50318. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  50319. uvs.push(uv.x, uv.y);
  50320. normals.push(normal.x, normal.y, normal.z);
  50321. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  50322. }
  50323. indices.push(vertex_idx);
  50324. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  50325. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  50326. currentIndex++;
  50327. }
  50328. }
  50329. }
  50330. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  50331. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  50332. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  50333. mesh.setIndices(indices);
  50334. if (keepSubMeshes) {
  50335. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  50336. var materialIndexOffset = 0, materialMaxIndex;
  50337. mesh.subMeshes = new Array();
  50338. for (var m in subMesh_dict) {
  50339. materialMaxIndex = -1;
  50340. for (var sm in subMesh_dict[m]) {
  50341. subMesh_obj = subMesh_dict[m][sm];
  50342. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  50343. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  50344. }
  50345. materialIndexOffset += ++materialMaxIndex;
  50346. }
  50347. }
  50348. return mesh;
  50349. };
  50350. // Build Mesh from CSG taking material and transforms into account
  50351. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  50352. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  50353. mesh.material = material;
  50354. mesh.position.copyFrom(this.position);
  50355. mesh.rotation.copyFrom(this.rotation);
  50356. if (this.rotationQuaternion) {
  50357. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  50358. }
  50359. mesh.scaling.copyFrom(this.scaling);
  50360. mesh.computeWorldMatrix(true);
  50361. return mesh;
  50362. };
  50363. return CSG;
  50364. }());
  50365. BABYLON.CSG = CSG;
  50366. })(BABYLON || (BABYLON = {}));
  50367. var BABYLON;
  50368. (function (BABYLON) {
  50369. var VRDistortionCorrectionPostProcess = (function (_super) {
  50370. __extends(VRDistortionCorrectionPostProcess, _super);
  50371. //ANY
  50372. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  50373. var _this = this;
  50374. _super.call(this, name, "vrDistortionCorrection", [
  50375. 'LensCenter',
  50376. 'Scale',
  50377. 'ScaleIn',
  50378. 'HmdWarpParam'
  50379. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  50380. this._isRightEye = isRightEye;
  50381. this._distortionFactors = vrMetrics.distortionK;
  50382. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  50383. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  50384. this.onSizeChangedObservable.add(function () {
  50385. _this.aspectRatio = _this.width * .5 / _this.height;
  50386. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  50387. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  50388. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  50389. });
  50390. this.onApplyObservable.add(function (effect) {
  50391. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  50392. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  50393. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  50394. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  50395. });
  50396. }
  50397. return VRDistortionCorrectionPostProcess;
  50398. }(BABYLON.PostProcess));
  50399. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  50400. })(BABYLON || (BABYLON = {}));
  50401. // Mainly based on these 2 articles :
  50402. // 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
  50403. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  50404. var BABYLON;
  50405. (function (BABYLON) {
  50406. (function (JoystickAxis) {
  50407. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  50408. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  50409. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  50410. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  50411. var JoystickAxis = BABYLON.JoystickAxis;
  50412. var VirtualJoystick = (function () {
  50413. function VirtualJoystick(leftJoystick) {
  50414. var _this = this;
  50415. if (leftJoystick) {
  50416. this._leftJoystick = true;
  50417. }
  50418. else {
  50419. this._leftJoystick = false;
  50420. }
  50421. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  50422. VirtualJoystick._globalJoystickIndex++;
  50423. // By default left & right arrow keys are moving the X
  50424. // and up & down keys are moving the Y
  50425. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  50426. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  50427. this.reverseLeftRight = false;
  50428. this.reverseUpDown = false;
  50429. // collections of pointers
  50430. this._touches = new BABYLON.StringDictionary();
  50431. this.deltaPosition = BABYLON.Vector3.Zero();
  50432. this._joystickSensibility = 25;
  50433. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  50434. this._rotationSpeed = 25;
  50435. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  50436. this._rotateOnAxisRelativeToMesh = false;
  50437. this._onResize = function (evt) {
  50438. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  50439. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  50440. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  50441. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  50442. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  50443. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  50444. };
  50445. // injecting a canvas element on top of the canvas 3D game
  50446. if (!VirtualJoystick.vjCanvas) {
  50447. window.addEventListener("resize", this._onResize, false);
  50448. VirtualJoystick.vjCanvas = document.createElement("canvas");
  50449. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  50450. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  50451. VirtualJoystick.vjCanvas.width = window.innerWidth;
  50452. VirtualJoystick.vjCanvas.height = window.innerHeight;
  50453. VirtualJoystick.vjCanvas.style.width = "100%";
  50454. VirtualJoystick.vjCanvas.style.height = "100%";
  50455. VirtualJoystick.vjCanvas.style.position = "absolute";
  50456. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  50457. VirtualJoystick.vjCanvas.style.top = "0px";
  50458. VirtualJoystick.vjCanvas.style.left = "0px";
  50459. VirtualJoystick.vjCanvas.style.zIndex = "5";
  50460. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  50461. // Support for jQuery PEP polyfill
  50462. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  50463. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  50464. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  50465. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  50466. document.body.appendChild(VirtualJoystick.vjCanvas);
  50467. }
  50468. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  50469. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  50470. this.pressed = false;
  50471. // default joystick color
  50472. this._joystickColor = "cyan";
  50473. this._joystickPointerID = -1;
  50474. // current joystick position
  50475. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  50476. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  50477. // origin joystick position
  50478. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  50479. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  50480. this._onPointerDownHandlerRef = function (evt) {
  50481. _this._onPointerDown(evt);
  50482. };
  50483. this._onPointerMoveHandlerRef = function (evt) {
  50484. _this._onPointerMove(evt);
  50485. };
  50486. this._onPointerOutHandlerRef = function (evt) {
  50487. _this._onPointerUp(evt);
  50488. };
  50489. this._onPointerUpHandlerRef = function (evt) {
  50490. _this._onPointerUp(evt);
  50491. };
  50492. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  50493. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  50494. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  50495. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  50496. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  50497. evt.preventDefault(); // Disables system menu
  50498. }, false);
  50499. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  50500. }
  50501. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  50502. this._joystickSensibility = newJoystickSensibility;
  50503. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  50504. };
  50505. VirtualJoystick.prototype._onPointerDown = function (e) {
  50506. var positionOnScreenCondition;
  50507. e.preventDefault();
  50508. if (this._leftJoystick === true) {
  50509. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  50510. }
  50511. else {
  50512. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  50513. }
  50514. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  50515. // First contact will be dedicated to the virtual joystick
  50516. this._joystickPointerID = e.pointerId;
  50517. this._joystickPointerStartPos.x = e.clientX;
  50518. this._joystickPointerStartPos.y = e.clientY;
  50519. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  50520. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  50521. this._deltaJoystickVector.x = 0;
  50522. this._deltaJoystickVector.y = 0;
  50523. this.pressed = true;
  50524. this._touches.add(e.pointerId.toString(), e);
  50525. }
  50526. else {
  50527. // You can only trigger the action buttons with a joystick declared
  50528. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  50529. this._action();
  50530. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  50531. }
  50532. }
  50533. };
  50534. VirtualJoystick.prototype._onPointerMove = function (e) {
  50535. // If the current pointer is the one associated to the joystick (first touch contact)
  50536. if (this._joystickPointerID == e.pointerId) {
  50537. this._joystickPointerPos.x = e.clientX;
  50538. this._joystickPointerPos.y = e.clientY;
  50539. this._deltaJoystickVector = this._joystickPointerPos.clone();
  50540. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  50541. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  50542. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  50543. switch (this._axisTargetedByLeftAndRight) {
  50544. case JoystickAxis.X:
  50545. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  50546. break;
  50547. case JoystickAxis.Y:
  50548. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  50549. break;
  50550. case JoystickAxis.Z:
  50551. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  50552. break;
  50553. }
  50554. var directionUpDown = this.reverseUpDown ? 1 : -1;
  50555. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  50556. switch (this._axisTargetedByUpAndDown) {
  50557. case JoystickAxis.X:
  50558. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  50559. break;
  50560. case JoystickAxis.Y:
  50561. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  50562. break;
  50563. case JoystickAxis.Z:
  50564. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  50565. break;
  50566. }
  50567. }
  50568. else {
  50569. var data = this._touches.get(e.pointerId.toString());
  50570. if (data) {
  50571. data.x = e.clientX;
  50572. data.y = e.clientY;
  50573. }
  50574. }
  50575. };
  50576. VirtualJoystick.prototype._onPointerUp = function (e) {
  50577. if (this._joystickPointerID == e.pointerId) {
  50578. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  50579. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  50580. this._joystickPointerID = -1;
  50581. this.pressed = false;
  50582. }
  50583. else {
  50584. var touch = this._touches.get(e.pointerId.toString());
  50585. if (touch) {
  50586. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  50587. }
  50588. }
  50589. this._deltaJoystickVector.x = 0;
  50590. this._deltaJoystickVector.y = 0;
  50591. this._touches.remove(e.pointerId.toString());
  50592. };
  50593. /**
  50594. * Change the color of the virtual joystick
  50595. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  50596. */
  50597. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  50598. this._joystickColor = newColor;
  50599. };
  50600. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  50601. this._action = action;
  50602. };
  50603. // Define which axis you'd like to control for left & right
  50604. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  50605. switch (axis) {
  50606. case JoystickAxis.X:
  50607. case JoystickAxis.Y:
  50608. case JoystickAxis.Z:
  50609. this._axisTargetedByLeftAndRight = axis;
  50610. break;
  50611. default:
  50612. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  50613. break;
  50614. }
  50615. };
  50616. // Define which axis you'd like to control for up & down
  50617. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  50618. switch (axis) {
  50619. case JoystickAxis.X:
  50620. case JoystickAxis.Y:
  50621. case JoystickAxis.Z:
  50622. this._axisTargetedByUpAndDown = axis;
  50623. break;
  50624. default:
  50625. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  50626. break;
  50627. }
  50628. };
  50629. VirtualJoystick.prototype._clearCanvas = function () {
  50630. if (this._leftJoystick) {
  50631. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  50632. }
  50633. else {
  50634. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  50635. }
  50636. };
  50637. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  50638. var _this = this;
  50639. if (this.pressed) {
  50640. this._touches.forEach(function (touch) {
  50641. if (touch.pointerId === _this._joystickPointerID) {
  50642. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  50643. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  50644. VirtualJoystick.vjCanvasContext.beginPath();
  50645. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  50646. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  50647. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  50648. VirtualJoystick.vjCanvasContext.stroke();
  50649. VirtualJoystick.vjCanvasContext.closePath();
  50650. VirtualJoystick.vjCanvasContext.beginPath();
  50651. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  50652. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  50653. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  50654. VirtualJoystick.vjCanvasContext.stroke();
  50655. VirtualJoystick.vjCanvasContext.closePath();
  50656. VirtualJoystick.vjCanvasContext.beginPath();
  50657. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  50658. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  50659. VirtualJoystick.vjCanvasContext.stroke();
  50660. VirtualJoystick.vjCanvasContext.closePath();
  50661. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  50662. }
  50663. else {
  50664. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  50665. VirtualJoystick.vjCanvasContext.beginPath();
  50666. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  50667. VirtualJoystick.vjCanvasContext.beginPath();
  50668. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  50669. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  50670. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  50671. VirtualJoystick.vjCanvasContext.stroke();
  50672. VirtualJoystick.vjCanvasContext.closePath();
  50673. touch.prevX = touch.x;
  50674. touch.prevY = touch.y;
  50675. }
  50676. ;
  50677. });
  50678. }
  50679. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  50680. };
  50681. VirtualJoystick.prototype.releaseCanvas = function () {
  50682. if (VirtualJoystick.vjCanvas) {
  50683. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  50684. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  50685. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  50686. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  50687. window.removeEventListener("resize", this._onResize);
  50688. document.body.removeChild(VirtualJoystick.vjCanvas);
  50689. VirtualJoystick.vjCanvas = null;
  50690. }
  50691. };
  50692. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  50693. VirtualJoystick._globalJoystickIndex = 0;
  50694. return VirtualJoystick;
  50695. }());
  50696. BABYLON.VirtualJoystick = VirtualJoystick;
  50697. })(BABYLON || (BABYLON = {}));
  50698. var BABYLON;
  50699. (function (BABYLON) {
  50700. // We're mainly based on the logic defined into the FreeCamera code
  50701. var VirtualJoysticksCamera = (function (_super) {
  50702. __extends(VirtualJoysticksCamera, _super);
  50703. function VirtualJoysticksCamera(name, position, scene) {
  50704. _super.call(this, name, position, scene);
  50705. this.inputs.addVirtualJoystick();
  50706. }
  50707. return VirtualJoysticksCamera;
  50708. }(BABYLON.FreeCamera));
  50709. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  50710. })(BABYLON || (BABYLON = {}));
  50711. var BABYLON;
  50712. (function (BABYLON) {
  50713. var FreeCameraVirtualJoystickInput = (function () {
  50714. function FreeCameraVirtualJoystickInput() {
  50715. }
  50716. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  50717. return this._leftjoystick;
  50718. };
  50719. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  50720. return this._rightjoystick;
  50721. };
  50722. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  50723. if (this._leftjoystick) {
  50724. var camera = this.camera;
  50725. var speed = camera._computeLocalCameraSpeed() * 50;
  50726. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  50727. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  50728. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  50729. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  50730. if (!this._leftjoystick.pressed) {
  50731. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  50732. }
  50733. if (!this._rightjoystick.pressed) {
  50734. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  50735. }
  50736. }
  50737. };
  50738. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  50739. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  50740. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  50741. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  50742. this._leftjoystick.setJoystickSensibility(0.15);
  50743. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  50744. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  50745. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  50746. this._rightjoystick.reverseUpDown = true;
  50747. this._rightjoystick.setJoystickSensibility(0.05);
  50748. this._rightjoystick.setJoystickColor("yellow");
  50749. };
  50750. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  50751. this._leftjoystick.releaseCanvas();
  50752. this._rightjoystick.releaseCanvas();
  50753. };
  50754. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  50755. return "FreeCameraVirtualJoystickInput";
  50756. };
  50757. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  50758. return "virtualJoystick";
  50759. };
  50760. return FreeCameraVirtualJoystickInput;
  50761. }());
  50762. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  50763. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  50764. })(BABYLON || (BABYLON = {}));
  50765. var BABYLON;
  50766. (function (BABYLON) {
  50767. var AnaglyphPostProcess = (function (_super) {
  50768. __extends(AnaglyphPostProcess, _super);
  50769. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  50770. var _this = this;
  50771. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  50772. this._passedProcess = rigCameras[0]._rigPostProcess;
  50773. this.onApplyObservable.add(function (effect) {
  50774. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  50775. });
  50776. }
  50777. return AnaglyphPostProcess;
  50778. }(BABYLON.PostProcess));
  50779. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  50780. })(BABYLON || (BABYLON = {}));
  50781. var BABYLON;
  50782. (function (BABYLON) {
  50783. var OutlineRenderer = (function () {
  50784. function OutlineRenderer(scene) {
  50785. this._scene = scene;
  50786. }
  50787. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  50788. var _this = this;
  50789. if (useOverlay === void 0) { useOverlay = false; }
  50790. var scene = this._scene;
  50791. var engine = this._scene.getEngine();
  50792. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  50793. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  50794. return;
  50795. }
  50796. var mesh = subMesh.getRenderingMesh();
  50797. var material = subMesh.getMaterial();
  50798. engine.enableEffect(this._effect);
  50799. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  50800. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  50801. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  50802. // Bones
  50803. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50804. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  50805. }
  50806. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  50807. // Alpha test
  50808. if (material && material.needAlphaTesting()) {
  50809. var alphaTexture = material.getAlphaTestTexture();
  50810. this._effect.setTexture("diffuseSampler", alphaTexture);
  50811. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  50812. }
  50813. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  50814. };
  50815. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  50816. var defines = [];
  50817. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  50818. var mesh = subMesh.getMesh();
  50819. var material = subMesh.getMaterial();
  50820. // Alpha test
  50821. if (material && material.needAlphaTesting()) {
  50822. defines.push("#define ALPHATEST");
  50823. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50824. attribs.push(BABYLON.VertexBuffer.UVKind);
  50825. defines.push("#define UV1");
  50826. }
  50827. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  50828. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  50829. defines.push("#define UV2");
  50830. }
  50831. }
  50832. // Bones
  50833. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50834. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  50835. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  50836. if (mesh.numBoneInfluencers > 4) {
  50837. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  50838. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  50839. }
  50840. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  50841. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  50842. }
  50843. else {
  50844. defines.push("#define NUM_BONE_INFLUENCERS 0");
  50845. }
  50846. // Instances
  50847. if (useInstances) {
  50848. defines.push("#define INSTANCES");
  50849. attribs.push("world0");
  50850. attribs.push("world1");
  50851. attribs.push("world2");
  50852. attribs.push("world3");
  50853. }
  50854. // Get correct effect
  50855. var join = defines.join("\n");
  50856. if (this._cachedDefines !== join) {
  50857. this._cachedDefines = join;
  50858. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  50859. }
  50860. return this._effect.isReady();
  50861. };
  50862. return OutlineRenderer;
  50863. }());
  50864. BABYLON.OutlineRenderer = OutlineRenderer;
  50865. })(BABYLON || (BABYLON = {}));
  50866. var BABYLON;
  50867. (function (BABYLON) {
  50868. var MeshAssetTask = (function () {
  50869. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  50870. this.name = name;
  50871. this.meshesNames = meshesNames;
  50872. this.rootUrl = rootUrl;
  50873. this.sceneFilename = sceneFilename;
  50874. this.isCompleted = false;
  50875. }
  50876. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50877. var _this = this;
  50878. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  50879. _this.loadedMeshes = meshes;
  50880. _this.loadedParticleSystems = particleSystems;
  50881. _this.loadedSkeletons = skeletons;
  50882. _this.isCompleted = true;
  50883. if (_this.onSuccess) {
  50884. _this.onSuccess(_this);
  50885. }
  50886. onSuccess();
  50887. }, null, function () {
  50888. if (_this.onError) {
  50889. _this.onError(_this);
  50890. }
  50891. onError();
  50892. });
  50893. };
  50894. return MeshAssetTask;
  50895. }());
  50896. BABYLON.MeshAssetTask = MeshAssetTask;
  50897. var TextFileAssetTask = (function () {
  50898. function TextFileAssetTask(name, url) {
  50899. this.name = name;
  50900. this.url = url;
  50901. this.isCompleted = false;
  50902. }
  50903. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50904. var _this = this;
  50905. BABYLON.Tools.LoadFile(this.url, function (data) {
  50906. _this.text = data;
  50907. _this.isCompleted = true;
  50908. if (_this.onSuccess) {
  50909. _this.onSuccess(_this);
  50910. }
  50911. onSuccess();
  50912. }, null, scene.database, false, function () {
  50913. if (_this.onError) {
  50914. _this.onError(_this);
  50915. }
  50916. onError();
  50917. });
  50918. };
  50919. return TextFileAssetTask;
  50920. }());
  50921. BABYLON.TextFileAssetTask = TextFileAssetTask;
  50922. var BinaryFileAssetTask = (function () {
  50923. function BinaryFileAssetTask(name, url) {
  50924. this.name = name;
  50925. this.url = url;
  50926. this.isCompleted = false;
  50927. }
  50928. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50929. var _this = this;
  50930. BABYLON.Tools.LoadFile(this.url, function (data) {
  50931. _this.data = data;
  50932. _this.isCompleted = true;
  50933. if (_this.onSuccess) {
  50934. _this.onSuccess(_this);
  50935. }
  50936. onSuccess();
  50937. }, null, scene.database, true, function () {
  50938. if (_this.onError) {
  50939. _this.onError(_this);
  50940. }
  50941. onError();
  50942. });
  50943. };
  50944. return BinaryFileAssetTask;
  50945. }());
  50946. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  50947. var ImageAssetTask = (function () {
  50948. function ImageAssetTask(name, url) {
  50949. this.name = name;
  50950. this.url = url;
  50951. this.isCompleted = false;
  50952. }
  50953. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50954. var _this = this;
  50955. var img = new Image();
  50956. img.onload = function () {
  50957. _this.image = img;
  50958. _this.isCompleted = true;
  50959. if (_this.onSuccess) {
  50960. _this.onSuccess(_this);
  50961. }
  50962. onSuccess();
  50963. };
  50964. img.onerror = function () {
  50965. if (_this.onError) {
  50966. _this.onError(_this);
  50967. }
  50968. onError();
  50969. };
  50970. img.src = this.url;
  50971. };
  50972. return ImageAssetTask;
  50973. }());
  50974. BABYLON.ImageAssetTask = ImageAssetTask;
  50975. var TextureAssetTask = (function () {
  50976. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  50977. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50978. this.name = name;
  50979. this.url = url;
  50980. this.noMipmap = noMipmap;
  50981. this.invertY = invertY;
  50982. this.samplingMode = samplingMode;
  50983. this.isCompleted = false;
  50984. }
  50985. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50986. var _this = this;
  50987. var onload = function () {
  50988. _this.isCompleted = true;
  50989. if (_this.onSuccess) {
  50990. _this.onSuccess(_this);
  50991. }
  50992. onSuccess();
  50993. };
  50994. var onerror = function () {
  50995. if (_this.onError) {
  50996. _this.onError(_this);
  50997. }
  50998. onError();
  50999. };
  51000. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  51001. };
  51002. return TextureAssetTask;
  51003. }());
  51004. BABYLON.TextureAssetTask = TextureAssetTask;
  51005. var AssetsManager = (function () {
  51006. function AssetsManager(scene) {
  51007. this._tasks = new Array();
  51008. this._waitingTasksCount = 0;
  51009. this.useDefaultLoadingScreen = true;
  51010. this._scene = scene;
  51011. }
  51012. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  51013. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  51014. this._tasks.push(task);
  51015. return task;
  51016. };
  51017. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  51018. var task = new TextFileAssetTask(taskName, url);
  51019. this._tasks.push(task);
  51020. return task;
  51021. };
  51022. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  51023. var task = new BinaryFileAssetTask(taskName, url);
  51024. this._tasks.push(task);
  51025. return task;
  51026. };
  51027. AssetsManager.prototype.addImageTask = function (taskName, url) {
  51028. var task = new ImageAssetTask(taskName, url);
  51029. this._tasks.push(task);
  51030. return task;
  51031. };
  51032. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  51033. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51034. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  51035. this._tasks.push(task);
  51036. return task;
  51037. };
  51038. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  51039. this._waitingTasksCount--;
  51040. if (this._waitingTasksCount === 0) {
  51041. if (this.onFinish) {
  51042. this.onFinish(this._tasks);
  51043. }
  51044. this._scene.getEngine().hideLoadingUI();
  51045. }
  51046. };
  51047. AssetsManager.prototype._runTask = function (task) {
  51048. var _this = this;
  51049. task.run(this._scene, function () {
  51050. if (_this.onTaskSuccess) {
  51051. _this.onTaskSuccess(task);
  51052. }
  51053. _this._decreaseWaitingTasksCount();
  51054. }, function () {
  51055. if (_this.onTaskError) {
  51056. _this.onTaskError(task);
  51057. }
  51058. _this._decreaseWaitingTasksCount();
  51059. });
  51060. };
  51061. AssetsManager.prototype.reset = function () {
  51062. this._tasks = new Array();
  51063. return this;
  51064. };
  51065. AssetsManager.prototype.load = function () {
  51066. this._waitingTasksCount = this._tasks.length;
  51067. if (this._waitingTasksCount === 0) {
  51068. if (this.onFinish) {
  51069. this.onFinish(this._tasks);
  51070. }
  51071. return this;
  51072. }
  51073. if (this.useDefaultLoadingScreen) {
  51074. this._scene.getEngine().displayLoadingUI();
  51075. }
  51076. for (var index = 0; index < this._tasks.length; index++) {
  51077. var task = this._tasks[index];
  51078. this._runTask(task);
  51079. }
  51080. return this;
  51081. };
  51082. return AssetsManager;
  51083. }());
  51084. BABYLON.AssetsManager = AssetsManager;
  51085. })(BABYLON || (BABYLON = {}));
  51086. var BABYLON;
  51087. (function (BABYLON) {
  51088. var VRCameraMetrics = (function () {
  51089. function VRCameraMetrics() {
  51090. this.compensateDistortion = true;
  51091. }
  51092. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  51093. get: function () {
  51094. return this.hResolution / (2 * this.vResolution);
  51095. },
  51096. enumerable: true,
  51097. configurable: true
  51098. });
  51099. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  51100. get: function () {
  51101. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  51102. },
  51103. enumerable: true,
  51104. configurable: true
  51105. });
  51106. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  51107. get: function () {
  51108. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  51109. var h = (4 * meters) / this.hScreenSize;
  51110. return BABYLON.Matrix.Translation(h, 0, 0);
  51111. },
  51112. enumerable: true,
  51113. configurable: true
  51114. });
  51115. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  51116. get: function () {
  51117. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  51118. var h = (4 * meters) / this.hScreenSize;
  51119. return BABYLON.Matrix.Translation(-h, 0, 0);
  51120. },
  51121. enumerable: true,
  51122. configurable: true
  51123. });
  51124. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  51125. get: function () {
  51126. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  51127. },
  51128. enumerable: true,
  51129. configurable: true
  51130. });
  51131. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  51132. get: function () {
  51133. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  51134. },
  51135. enumerable: true,
  51136. configurable: true
  51137. });
  51138. VRCameraMetrics.GetDefault = function () {
  51139. var result = new VRCameraMetrics();
  51140. result.hResolution = 1280;
  51141. result.vResolution = 800;
  51142. result.hScreenSize = 0.149759993;
  51143. result.vScreenSize = 0.0935999975;
  51144. result.vScreenCenter = 0.0467999987,
  51145. result.eyeToScreenDistance = 0.0410000011;
  51146. result.lensSeparationDistance = 0.0635000020;
  51147. result.interpupillaryDistance = 0.0640000030;
  51148. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  51149. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  51150. result.postProcessScaleFactor = 1.714605507808412;
  51151. result.lensCenterOffset = 0.151976421;
  51152. return result;
  51153. };
  51154. return VRCameraMetrics;
  51155. }());
  51156. BABYLON.VRCameraMetrics = VRCameraMetrics;
  51157. })(BABYLON || (BABYLON = {}));
  51158. var BABYLON;
  51159. (function (BABYLON) {
  51160. var VRDeviceOrientationFreeCamera = (function (_super) {
  51161. __extends(VRDeviceOrientationFreeCamera, _super);
  51162. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  51163. if (compensateDistortion === void 0) { compensateDistortion = true; }
  51164. _super.call(this, name, position, scene);
  51165. this.rotationQuaternion = new BABYLON.Quaternion();
  51166. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  51167. metrics.compensateDistortion = compensateDistortion;
  51168. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  51169. this.inputs.addDeviceOrientation();
  51170. }
  51171. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  51172. return "VRDeviceOrientationFreeCamera";
  51173. };
  51174. return VRDeviceOrientationFreeCamera;
  51175. }(BABYLON.FreeCamera));
  51176. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  51177. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  51178. __extends(VRDeviceOrientationArcRotateCamera, _super);
  51179. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
  51180. if (compensateDistortion === void 0) { compensateDistortion = true; }
  51181. _super.call(this, name, alpha, beta, radius, target, scene);
  51182. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  51183. metrics.compensateDistortion = compensateDistortion;
  51184. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  51185. this.inputs.addVRDeviceOrientation();
  51186. }
  51187. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  51188. return "VRDeviceOrientationArcRotateCamera";
  51189. };
  51190. return VRDeviceOrientationArcRotateCamera;
  51191. }(BABYLON.ArcRotateCamera));
  51192. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  51193. })(BABYLON || (BABYLON = {}));
  51194. var BABYLON;
  51195. (function (BABYLON) {
  51196. var WebVRFreeCamera = (function (_super) {
  51197. __extends(WebVRFreeCamera, _super);
  51198. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  51199. if (compensateDistortion === void 0) { compensateDistortion = true; }
  51200. _super.call(this, name, position, scene);
  51201. this._hmdDevice = null;
  51202. this._sensorDevice = null;
  51203. this._cacheState = null;
  51204. this._vrEnabled = false;
  51205. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  51206. metrics.compensateDistortion = compensateDistortion;
  51207. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  51208. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  51209. this.rotationQuaternion = new BABYLON.Quaternion();
  51210. }
  51211. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  51212. var size = devices.length;
  51213. var i = 0;
  51214. // Reset devices.
  51215. this._sensorDevice = null;
  51216. this._hmdDevice = null;
  51217. // Search for a HmdDevice.
  51218. while (i < size && this._hmdDevice === null) {
  51219. if (devices[i] instanceof HMDVRDevice) {
  51220. this._hmdDevice = devices[i];
  51221. }
  51222. i++;
  51223. }
  51224. i = 0;
  51225. while (i < size && this._sensorDevice === null) {
  51226. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  51227. this._sensorDevice = devices[i];
  51228. }
  51229. i++;
  51230. }
  51231. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  51232. };
  51233. WebVRFreeCamera.prototype._checkInputs = function () {
  51234. if (this._vrEnabled) {
  51235. this._cacheState = this._sensorDevice.getState();
  51236. this.rotationQuaternion.copyFrom(this._cacheState.orientation);
  51237. //Flip in XY plane
  51238. this.rotationQuaternion.z *= -1;
  51239. this.rotationQuaternion.w *= -1;
  51240. }
  51241. _super.prototype._checkInputs.call(this);
  51242. };
  51243. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  51244. _super.prototype.attachControl.call(this, element, noPreventDefault);
  51245. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  51246. if (navigator.getVRDevices) {
  51247. navigator.getVRDevices().then(this._getWebVRDevices);
  51248. }
  51249. else if (navigator.mozGetVRDevices) {
  51250. navigator.mozGetVRDevices(this._getWebVRDevices);
  51251. }
  51252. };
  51253. WebVRFreeCamera.prototype.detachControl = function (element) {
  51254. _super.prototype.detachControl.call(this, element);
  51255. this._vrEnabled = false;
  51256. };
  51257. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  51258. if (!this._hmdDevice)
  51259. return;
  51260. this.getEngine().switchFullscreen(requestPointerlock, { vrDisplay: this._hmdDevice });
  51261. };
  51262. WebVRFreeCamera.prototype.getTypeName = function () {
  51263. return "WebVRFreeCamera";
  51264. };
  51265. return WebVRFreeCamera;
  51266. }(BABYLON.FreeCamera));
  51267. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  51268. })(BABYLON || (BABYLON = {}));
  51269. var BABYLON;
  51270. (function (BABYLON) {
  51271. // Standard optimizations
  51272. var SceneOptimization = (function () {
  51273. function SceneOptimization(priority) {
  51274. if (priority === void 0) { priority = 0; }
  51275. this.priority = priority;
  51276. this.apply = function (scene) {
  51277. return true; // Return true if everything that can be done was applied
  51278. };
  51279. }
  51280. return SceneOptimization;
  51281. }());
  51282. BABYLON.SceneOptimization = SceneOptimization;
  51283. var TextureOptimization = (function (_super) {
  51284. __extends(TextureOptimization, _super);
  51285. function TextureOptimization(priority, maximumSize) {
  51286. var _this = this;
  51287. if (priority === void 0) { priority = 0; }
  51288. if (maximumSize === void 0) { maximumSize = 1024; }
  51289. _super.call(this, priority);
  51290. this.priority = priority;
  51291. this.maximumSize = maximumSize;
  51292. this.apply = function (scene) {
  51293. var allDone = true;
  51294. for (var index = 0; index < scene.textures.length; index++) {
  51295. var texture = scene.textures[index];
  51296. if (!texture.canRescale) {
  51297. continue;
  51298. }
  51299. var currentSize = texture.getSize();
  51300. var maxDimension = Math.max(currentSize.width, currentSize.height);
  51301. if (maxDimension > _this.maximumSize) {
  51302. texture.scale(0.5);
  51303. allDone = false;
  51304. }
  51305. }
  51306. return allDone;
  51307. };
  51308. }
  51309. return TextureOptimization;
  51310. }(SceneOptimization));
  51311. BABYLON.TextureOptimization = TextureOptimization;
  51312. var HardwareScalingOptimization = (function (_super) {
  51313. __extends(HardwareScalingOptimization, _super);
  51314. function HardwareScalingOptimization(priority, maximumScale) {
  51315. var _this = this;
  51316. if (priority === void 0) { priority = 0; }
  51317. if (maximumScale === void 0) { maximumScale = 2; }
  51318. _super.call(this, priority);
  51319. this.priority = priority;
  51320. this.maximumScale = maximumScale;
  51321. this._currentScale = 1;
  51322. this.apply = function (scene) {
  51323. _this._currentScale++;
  51324. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  51325. return _this._currentScale >= _this.maximumScale;
  51326. };
  51327. }
  51328. return HardwareScalingOptimization;
  51329. }(SceneOptimization));
  51330. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  51331. var ShadowsOptimization = (function (_super) {
  51332. __extends(ShadowsOptimization, _super);
  51333. function ShadowsOptimization() {
  51334. _super.apply(this, arguments);
  51335. this.apply = function (scene) {
  51336. scene.shadowsEnabled = false;
  51337. return true;
  51338. };
  51339. }
  51340. return ShadowsOptimization;
  51341. }(SceneOptimization));
  51342. BABYLON.ShadowsOptimization = ShadowsOptimization;
  51343. var PostProcessesOptimization = (function (_super) {
  51344. __extends(PostProcessesOptimization, _super);
  51345. function PostProcessesOptimization() {
  51346. _super.apply(this, arguments);
  51347. this.apply = function (scene) {
  51348. scene.postProcessesEnabled = false;
  51349. return true;
  51350. };
  51351. }
  51352. return PostProcessesOptimization;
  51353. }(SceneOptimization));
  51354. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  51355. var LensFlaresOptimization = (function (_super) {
  51356. __extends(LensFlaresOptimization, _super);
  51357. function LensFlaresOptimization() {
  51358. _super.apply(this, arguments);
  51359. this.apply = function (scene) {
  51360. scene.lensFlaresEnabled = false;
  51361. return true;
  51362. };
  51363. }
  51364. return LensFlaresOptimization;
  51365. }(SceneOptimization));
  51366. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  51367. var ParticlesOptimization = (function (_super) {
  51368. __extends(ParticlesOptimization, _super);
  51369. function ParticlesOptimization() {
  51370. _super.apply(this, arguments);
  51371. this.apply = function (scene) {
  51372. scene.particlesEnabled = false;
  51373. return true;
  51374. };
  51375. }
  51376. return ParticlesOptimization;
  51377. }(SceneOptimization));
  51378. BABYLON.ParticlesOptimization = ParticlesOptimization;
  51379. var RenderTargetsOptimization = (function (_super) {
  51380. __extends(RenderTargetsOptimization, _super);
  51381. function RenderTargetsOptimization() {
  51382. _super.apply(this, arguments);
  51383. this.apply = function (scene) {
  51384. scene.renderTargetsEnabled = false;
  51385. return true;
  51386. };
  51387. }
  51388. return RenderTargetsOptimization;
  51389. }(SceneOptimization));
  51390. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  51391. var MergeMeshesOptimization = (function (_super) {
  51392. __extends(MergeMeshesOptimization, _super);
  51393. function MergeMeshesOptimization() {
  51394. var _this = this;
  51395. _super.apply(this, arguments);
  51396. this._canBeMerged = function (abstractMesh) {
  51397. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  51398. return false;
  51399. }
  51400. var mesh = abstractMesh;
  51401. if (!mesh.isVisible || !mesh.isEnabled()) {
  51402. return false;
  51403. }
  51404. if (mesh.instances.length > 0) {
  51405. return false;
  51406. }
  51407. if (mesh.skeleton || mesh.hasLODLevels) {
  51408. return false;
  51409. }
  51410. if (mesh.parent) {
  51411. return false;
  51412. }
  51413. return true;
  51414. };
  51415. this.apply = function (scene, updateSelectionTree) {
  51416. var globalPool = scene.meshes.slice(0);
  51417. var globalLength = globalPool.length;
  51418. for (var index = 0; index < globalLength; index++) {
  51419. var currentPool = new Array();
  51420. var current = globalPool[index];
  51421. // Checks
  51422. if (!_this._canBeMerged(current)) {
  51423. continue;
  51424. }
  51425. currentPool.push(current);
  51426. // Find compatible meshes
  51427. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  51428. var otherMesh = globalPool[subIndex];
  51429. if (!_this._canBeMerged(otherMesh)) {
  51430. continue;
  51431. }
  51432. if (otherMesh.material !== current.material) {
  51433. continue;
  51434. }
  51435. if (otherMesh.checkCollisions !== current.checkCollisions) {
  51436. continue;
  51437. }
  51438. currentPool.push(otherMesh);
  51439. globalLength--;
  51440. globalPool.splice(subIndex, 1);
  51441. subIndex--;
  51442. }
  51443. if (currentPool.length < 2) {
  51444. continue;
  51445. }
  51446. // Merge meshes
  51447. BABYLON.Mesh.MergeMeshes(currentPool);
  51448. }
  51449. if (updateSelectionTree != undefined) {
  51450. if (updateSelectionTree) {
  51451. scene.createOrUpdateSelectionOctree();
  51452. }
  51453. }
  51454. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  51455. scene.createOrUpdateSelectionOctree();
  51456. }
  51457. return true;
  51458. };
  51459. }
  51460. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  51461. get: function () {
  51462. return MergeMeshesOptimization._UpdateSelectionTree;
  51463. },
  51464. set: function (value) {
  51465. MergeMeshesOptimization._UpdateSelectionTree = value;
  51466. },
  51467. enumerable: true,
  51468. configurable: true
  51469. });
  51470. MergeMeshesOptimization._UpdateSelectionTree = false;
  51471. return MergeMeshesOptimization;
  51472. }(SceneOptimization));
  51473. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  51474. // Options
  51475. var SceneOptimizerOptions = (function () {
  51476. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  51477. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  51478. if (trackerDuration === void 0) { trackerDuration = 2000; }
  51479. this.targetFrameRate = targetFrameRate;
  51480. this.trackerDuration = trackerDuration;
  51481. this.optimizations = new Array();
  51482. }
  51483. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  51484. var result = new SceneOptimizerOptions(targetFrameRate);
  51485. var priority = 0;
  51486. result.optimizations.push(new MergeMeshesOptimization(priority));
  51487. result.optimizations.push(new ShadowsOptimization(priority));
  51488. result.optimizations.push(new LensFlaresOptimization(priority));
  51489. // Next priority
  51490. priority++;
  51491. result.optimizations.push(new PostProcessesOptimization(priority));
  51492. result.optimizations.push(new ParticlesOptimization(priority));
  51493. // Next priority
  51494. priority++;
  51495. result.optimizations.push(new TextureOptimization(priority, 1024));
  51496. return result;
  51497. };
  51498. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  51499. var result = new SceneOptimizerOptions(targetFrameRate);
  51500. var priority = 0;
  51501. result.optimizations.push(new MergeMeshesOptimization(priority));
  51502. result.optimizations.push(new ShadowsOptimization(priority));
  51503. result.optimizations.push(new LensFlaresOptimization(priority));
  51504. // Next priority
  51505. priority++;
  51506. result.optimizations.push(new PostProcessesOptimization(priority));
  51507. result.optimizations.push(new ParticlesOptimization(priority));
  51508. // Next priority
  51509. priority++;
  51510. result.optimizations.push(new TextureOptimization(priority, 512));
  51511. // Next priority
  51512. priority++;
  51513. result.optimizations.push(new RenderTargetsOptimization(priority));
  51514. // Next priority
  51515. priority++;
  51516. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  51517. return result;
  51518. };
  51519. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  51520. var result = new SceneOptimizerOptions(targetFrameRate);
  51521. var priority = 0;
  51522. result.optimizations.push(new MergeMeshesOptimization(priority));
  51523. result.optimizations.push(new ShadowsOptimization(priority));
  51524. result.optimizations.push(new LensFlaresOptimization(priority));
  51525. // Next priority
  51526. priority++;
  51527. result.optimizations.push(new PostProcessesOptimization(priority));
  51528. result.optimizations.push(new ParticlesOptimization(priority));
  51529. // Next priority
  51530. priority++;
  51531. result.optimizations.push(new TextureOptimization(priority, 256));
  51532. // Next priority
  51533. priority++;
  51534. result.optimizations.push(new RenderTargetsOptimization(priority));
  51535. // Next priority
  51536. priority++;
  51537. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  51538. return result;
  51539. };
  51540. return SceneOptimizerOptions;
  51541. }());
  51542. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  51543. // Scene optimizer tool
  51544. var SceneOptimizer = (function () {
  51545. function SceneOptimizer() {
  51546. }
  51547. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  51548. // TODO: add an epsilon
  51549. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  51550. if (onSuccess) {
  51551. onSuccess();
  51552. }
  51553. return;
  51554. }
  51555. // Apply current level of optimizations
  51556. var allDone = true;
  51557. var noOptimizationApplied = true;
  51558. for (var index = 0; index < options.optimizations.length; index++) {
  51559. var optimization = options.optimizations[index];
  51560. if (optimization.priority === currentPriorityLevel) {
  51561. noOptimizationApplied = false;
  51562. allDone = allDone && optimization.apply(scene);
  51563. }
  51564. }
  51565. // If no optimization was applied, this is a failure :(
  51566. if (noOptimizationApplied) {
  51567. if (onFailure) {
  51568. onFailure();
  51569. }
  51570. return;
  51571. }
  51572. // If all optimizations were done, move to next level
  51573. if (allDone) {
  51574. currentPriorityLevel++;
  51575. }
  51576. // Let's the system running for a specific amount of time before checking FPS
  51577. scene.executeWhenReady(function () {
  51578. setTimeout(function () {
  51579. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  51580. }, options.trackerDuration);
  51581. });
  51582. };
  51583. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  51584. if (!options) {
  51585. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  51586. }
  51587. // Let's the system running for a specific amount of time before checking FPS
  51588. scene.executeWhenReady(function () {
  51589. setTimeout(function () {
  51590. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  51591. }, options.trackerDuration);
  51592. });
  51593. };
  51594. return SceneOptimizer;
  51595. }());
  51596. BABYLON.SceneOptimizer = SceneOptimizer;
  51597. })(BABYLON || (BABYLON = {}));
  51598. var BABYLON;
  51599. (function (BABYLON) {
  51600. var Internals;
  51601. (function (Internals) {
  51602. var MeshLODLevel = (function () {
  51603. function MeshLODLevel(distance, mesh) {
  51604. this.distance = distance;
  51605. this.mesh = mesh;
  51606. }
  51607. return MeshLODLevel;
  51608. }());
  51609. Internals.MeshLODLevel = MeshLODLevel;
  51610. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51611. })(BABYLON || (BABYLON = {}));
  51612. var BABYLON;
  51613. (function (BABYLON) {
  51614. var RawTexture = (function (_super) {
  51615. __extends(RawTexture, _super);
  51616. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  51617. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51618. if (invertY === void 0) { invertY = false; }
  51619. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51620. _super.call(this, null, scene, !generateMipMaps, invertY);
  51621. this.format = format;
  51622. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  51623. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51624. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51625. }
  51626. RawTexture.prototype.update = function (data) {
  51627. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  51628. };
  51629. // Statics
  51630. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51631. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51632. if (invertY === void 0) { invertY = false; }
  51633. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51634. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  51635. };
  51636. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51637. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51638. if (invertY === void 0) { invertY = false; }
  51639. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51640. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51641. };
  51642. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51643. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51644. if (invertY === void 0) { invertY = false; }
  51645. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51646. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51647. };
  51648. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51649. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51650. if (invertY === void 0) { invertY = false; }
  51651. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51652. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  51653. };
  51654. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51655. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51656. if (invertY === void 0) { invertY = false; }
  51657. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51658. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  51659. };
  51660. return RawTexture;
  51661. }(BABYLON.Texture));
  51662. BABYLON.RawTexture = RawTexture;
  51663. })(BABYLON || (BABYLON = {}));
  51664. var BABYLON;
  51665. (function (BABYLON) {
  51666. var IndexedVector2 = (function (_super) {
  51667. __extends(IndexedVector2, _super);
  51668. function IndexedVector2(original, index) {
  51669. _super.call(this, original.x, original.y);
  51670. this.index = index;
  51671. }
  51672. return IndexedVector2;
  51673. }(BABYLON.Vector2));
  51674. var PolygonPoints = (function () {
  51675. function PolygonPoints() {
  51676. this.elements = new Array();
  51677. }
  51678. PolygonPoints.prototype.add = function (originalPoints) {
  51679. var _this = this;
  51680. var result = new Array();
  51681. originalPoints.forEach(function (point) {
  51682. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  51683. var newPoint = new IndexedVector2(point, _this.elements.length);
  51684. result.push(newPoint);
  51685. _this.elements.push(newPoint);
  51686. }
  51687. });
  51688. return result;
  51689. };
  51690. PolygonPoints.prototype.computeBounds = function () {
  51691. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  51692. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  51693. this.elements.forEach(function (point) {
  51694. // x
  51695. if (point.x < lmin.x) {
  51696. lmin.x = point.x;
  51697. }
  51698. else if (point.x > lmax.x) {
  51699. lmax.x = point.x;
  51700. }
  51701. // y
  51702. if (point.y < lmin.y) {
  51703. lmin.y = point.y;
  51704. }
  51705. else if (point.y > lmax.y) {
  51706. lmax.y = point.y;
  51707. }
  51708. });
  51709. return {
  51710. min: lmin,
  51711. max: lmax,
  51712. width: lmax.x - lmin.x,
  51713. height: lmax.y - lmin.y
  51714. };
  51715. };
  51716. return PolygonPoints;
  51717. }());
  51718. var Polygon = (function () {
  51719. function Polygon() {
  51720. }
  51721. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  51722. return [
  51723. new BABYLON.Vector2(xmin, ymin),
  51724. new BABYLON.Vector2(xmax, ymin),
  51725. new BABYLON.Vector2(xmax, ymax),
  51726. new BABYLON.Vector2(xmin, ymax)
  51727. ];
  51728. };
  51729. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  51730. if (cx === void 0) { cx = 0; }
  51731. if (cy === void 0) { cy = 0; }
  51732. if (numberOfSides === void 0) { numberOfSides = 32; }
  51733. var result = new Array();
  51734. var angle = 0;
  51735. var increment = (Math.PI * 2) / numberOfSides;
  51736. for (var i = 0; i < numberOfSides; i++) {
  51737. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  51738. angle -= increment;
  51739. }
  51740. return result;
  51741. };
  51742. Polygon.Parse = function (input) {
  51743. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  51744. var i, result = [];
  51745. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  51746. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  51747. }
  51748. return result;
  51749. };
  51750. Polygon.StartingAt = function (x, y) {
  51751. return BABYLON.Path2.StartingAt(x, y);
  51752. };
  51753. return Polygon;
  51754. }());
  51755. BABYLON.Polygon = Polygon;
  51756. var PolygonMeshBuilder = (function () {
  51757. function PolygonMeshBuilder(name, contours, scene) {
  51758. this._points = new PolygonPoints();
  51759. this._outlinepoints = new PolygonPoints();
  51760. this._holes = [];
  51761. this._epoints = new Array();
  51762. this._eholes = new Array();
  51763. this._name = name;
  51764. this._scene = scene;
  51765. var points;
  51766. if (contours instanceof BABYLON.Path2) {
  51767. points = contours.getPoints();
  51768. }
  51769. else {
  51770. points = contours;
  51771. }
  51772. this._addToepoint(points);
  51773. this._points.add(points);
  51774. this._outlinepoints.add(points);
  51775. }
  51776. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  51777. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  51778. var p = points_1[_i];
  51779. this._epoints.push(p.x, p.y);
  51780. }
  51781. };
  51782. PolygonMeshBuilder.prototype.addHole = function (hole) {
  51783. this._points.add(hole);
  51784. var holepoints = new PolygonPoints();
  51785. holepoints.add(hole);
  51786. this._holes.push(holepoints);
  51787. this._eholes.push(this._epoints.length / 2);
  51788. this._addToepoint(hole);
  51789. return this;
  51790. };
  51791. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  51792. var _this = this;
  51793. if (updatable === void 0) { updatable = false; }
  51794. var result = new BABYLON.Mesh(this._name, this._scene);
  51795. var normals = [];
  51796. var positions = [];
  51797. var uvs = [];
  51798. var bounds = this._points.computeBounds();
  51799. this._points.elements.forEach(function (p) {
  51800. normals.push(0, 1.0, 0);
  51801. positions.push(p.x, 0, p.y);
  51802. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  51803. });
  51804. var indices = [];
  51805. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  51806. for (var i = 0; i < res.length; i++) {
  51807. indices.push(res[i]);
  51808. }
  51809. if (depth > 0) {
  51810. var positionscount = (positions.length / 3); //get the current pointcount
  51811. this._points.elements.forEach(function (p) {
  51812. normals.push(0, -1.0, 0);
  51813. positions.push(p.x, -depth, p.y);
  51814. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  51815. });
  51816. var totalCount = indices.length;
  51817. for (var i = 0; i < totalCount; i += 3) {
  51818. var i0 = indices[i + 0];
  51819. var i1 = indices[i + 1];
  51820. var i2 = indices[i + 2];
  51821. indices.push(i2 + positionscount);
  51822. indices.push(i1 + positionscount);
  51823. indices.push(i0 + positionscount);
  51824. }
  51825. //Add the sides
  51826. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  51827. this._holes.forEach(function (hole) {
  51828. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  51829. });
  51830. }
  51831. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  51832. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  51833. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  51834. result.setIndices(indices);
  51835. return result;
  51836. };
  51837. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  51838. var StartIndex = positions.length / 3;
  51839. var ulength = 0;
  51840. for (var i = 0; i < points.elements.length; i++) {
  51841. var p = points.elements[i];
  51842. var p1;
  51843. if ((i + 1) > points.elements.length - 1) {
  51844. p1 = points.elements[0];
  51845. }
  51846. else {
  51847. p1 = points.elements[i + 1];
  51848. }
  51849. positions.push(p.x, 0, p.y);
  51850. positions.push(p.x, -depth, p.y);
  51851. positions.push(p1.x, 0, p1.y);
  51852. positions.push(p1.x, -depth, p1.y);
  51853. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  51854. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  51855. var v3 = v2.subtract(v1);
  51856. var v4 = new BABYLON.Vector3(0, 1, 0);
  51857. var vn = BABYLON.Vector3.Cross(v3, v4);
  51858. vn = vn.normalize();
  51859. uvs.push(ulength / bounds.width, 0);
  51860. uvs.push(ulength / bounds.width, 1);
  51861. ulength += v3.length();
  51862. uvs.push((ulength / bounds.width), 0);
  51863. uvs.push((ulength / bounds.width), 1);
  51864. if (!flip) {
  51865. normals.push(-vn.x, -vn.y, -vn.z);
  51866. normals.push(-vn.x, -vn.y, -vn.z);
  51867. normals.push(-vn.x, -vn.y, -vn.z);
  51868. normals.push(-vn.x, -vn.y, -vn.z);
  51869. indices.push(StartIndex);
  51870. indices.push(StartIndex + 1);
  51871. indices.push(StartIndex + 2);
  51872. indices.push(StartIndex + 1);
  51873. indices.push(StartIndex + 3);
  51874. indices.push(StartIndex + 2);
  51875. }
  51876. else {
  51877. normals.push(vn.x, vn.y, vn.z);
  51878. normals.push(vn.x, vn.y, vn.z);
  51879. normals.push(vn.x, vn.y, vn.z);
  51880. normals.push(vn.x, vn.y, vn.z);
  51881. indices.push(StartIndex);
  51882. indices.push(StartIndex + 2);
  51883. indices.push(StartIndex + 1);
  51884. indices.push(StartIndex + 1);
  51885. indices.push(StartIndex + 2);
  51886. indices.push(StartIndex + 3);
  51887. }
  51888. StartIndex += 4;
  51889. }
  51890. ;
  51891. };
  51892. return PolygonMeshBuilder;
  51893. }());
  51894. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  51895. })(BABYLON || (BABYLON = {}));
  51896. var BABYLON;
  51897. (function (BABYLON) {
  51898. var Octree = (function () {
  51899. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  51900. if (maxDepth === void 0) { maxDepth = 2; }
  51901. this.maxDepth = maxDepth;
  51902. this.dynamicContent = new Array();
  51903. this._maxBlockCapacity = maxBlockCapacity || 64;
  51904. this._selectionContent = new BABYLON.SmartArray(1024);
  51905. this._creationFunc = creationFunc;
  51906. }
  51907. // Methods
  51908. Octree.prototype.update = function (worldMin, worldMax, entries) {
  51909. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  51910. };
  51911. Octree.prototype.addMesh = function (entry) {
  51912. for (var index = 0; index < this.blocks.length; index++) {
  51913. var block = this.blocks[index];
  51914. block.addEntry(entry);
  51915. }
  51916. };
  51917. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  51918. this._selectionContent.reset();
  51919. for (var index = 0; index < this.blocks.length; index++) {
  51920. var block = this.blocks[index];
  51921. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  51922. }
  51923. if (allowDuplicate) {
  51924. this._selectionContent.concat(this.dynamicContent);
  51925. }
  51926. else {
  51927. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  51928. }
  51929. return this._selectionContent;
  51930. };
  51931. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  51932. this._selectionContent.reset();
  51933. for (var index = 0; index < this.blocks.length; index++) {
  51934. var block = this.blocks[index];
  51935. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  51936. }
  51937. if (allowDuplicate) {
  51938. this._selectionContent.concat(this.dynamicContent);
  51939. }
  51940. else {
  51941. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  51942. }
  51943. return this._selectionContent;
  51944. };
  51945. Octree.prototype.intersectsRay = function (ray) {
  51946. this._selectionContent.reset();
  51947. for (var index = 0; index < this.blocks.length; index++) {
  51948. var block = this.blocks[index];
  51949. block.intersectsRay(ray, this._selectionContent);
  51950. }
  51951. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  51952. return this._selectionContent;
  51953. };
  51954. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  51955. target.blocks = new Array();
  51956. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  51957. // Segmenting space
  51958. for (var x = 0; x < 2; x++) {
  51959. for (var y = 0; y < 2; y++) {
  51960. for (var z = 0; z < 2; z++) {
  51961. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  51962. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  51963. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  51964. block.addEntries(entries);
  51965. target.blocks.push(block);
  51966. }
  51967. }
  51968. }
  51969. };
  51970. Octree.CreationFuncForMeshes = function (entry, block) {
  51971. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  51972. block.entries.push(entry);
  51973. }
  51974. };
  51975. Octree.CreationFuncForSubMeshes = function (entry, block) {
  51976. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  51977. block.entries.push(entry);
  51978. }
  51979. };
  51980. return Octree;
  51981. }());
  51982. BABYLON.Octree = Octree;
  51983. })(BABYLON || (BABYLON = {}));
  51984. var BABYLON;
  51985. (function (BABYLON) {
  51986. var OctreeBlock = (function () {
  51987. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  51988. this.entries = new Array();
  51989. this._boundingVectors = new Array();
  51990. this._capacity = capacity;
  51991. this._depth = depth;
  51992. this._maxDepth = maxDepth;
  51993. this._creationFunc = creationFunc;
  51994. this._minPoint = minPoint;
  51995. this._maxPoint = maxPoint;
  51996. this._boundingVectors.push(minPoint.clone());
  51997. this._boundingVectors.push(maxPoint.clone());
  51998. this._boundingVectors.push(minPoint.clone());
  51999. this._boundingVectors[2].x = maxPoint.x;
  52000. this._boundingVectors.push(minPoint.clone());
  52001. this._boundingVectors[3].y = maxPoint.y;
  52002. this._boundingVectors.push(minPoint.clone());
  52003. this._boundingVectors[4].z = maxPoint.z;
  52004. this._boundingVectors.push(maxPoint.clone());
  52005. this._boundingVectors[5].z = minPoint.z;
  52006. this._boundingVectors.push(maxPoint.clone());
  52007. this._boundingVectors[6].x = minPoint.x;
  52008. this._boundingVectors.push(maxPoint.clone());
  52009. this._boundingVectors[7].y = minPoint.y;
  52010. }
  52011. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  52012. // Property
  52013. get: function () {
  52014. return this._capacity;
  52015. },
  52016. enumerable: true,
  52017. configurable: true
  52018. });
  52019. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  52020. get: function () {
  52021. return this._minPoint;
  52022. },
  52023. enumerable: true,
  52024. configurable: true
  52025. });
  52026. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  52027. get: function () {
  52028. return this._maxPoint;
  52029. },
  52030. enumerable: true,
  52031. configurable: true
  52032. });
  52033. // Methods
  52034. OctreeBlock.prototype.addEntry = function (entry) {
  52035. if (this.blocks) {
  52036. for (var index = 0; index < this.blocks.length; index++) {
  52037. var block = this.blocks[index];
  52038. block.addEntry(entry);
  52039. }
  52040. return;
  52041. }
  52042. this._creationFunc(entry, this);
  52043. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  52044. this.createInnerBlocks();
  52045. }
  52046. };
  52047. OctreeBlock.prototype.addEntries = function (entries) {
  52048. for (var index = 0; index < entries.length; index++) {
  52049. var mesh = entries[index];
  52050. this.addEntry(mesh);
  52051. }
  52052. };
  52053. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  52054. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  52055. if (this.blocks) {
  52056. for (var index = 0; index < this.blocks.length; index++) {
  52057. var block = this.blocks[index];
  52058. block.select(frustumPlanes, selection, allowDuplicate);
  52059. }
  52060. return;
  52061. }
  52062. if (allowDuplicate) {
  52063. selection.concat(this.entries);
  52064. }
  52065. else {
  52066. selection.concatWithNoDuplicate(this.entries);
  52067. }
  52068. }
  52069. };
  52070. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  52071. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  52072. if (this.blocks) {
  52073. for (var index = 0; index < this.blocks.length; index++) {
  52074. var block = this.blocks[index];
  52075. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  52076. }
  52077. return;
  52078. }
  52079. if (allowDuplicate) {
  52080. selection.concat(this.entries);
  52081. }
  52082. else {
  52083. selection.concatWithNoDuplicate(this.entries);
  52084. }
  52085. }
  52086. };
  52087. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  52088. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  52089. if (this.blocks) {
  52090. for (var index = 0; index < this.blocks.length; index++) {
  52091. var block = this.blocks[index];
  52092. block.intersectsRay(ray, selection);
  52093. }
  52094. return;
  52095. }
  52096. selection.concatWithNoDuplicate(this.entries);
  52097. }
  52098. };
  52099. OctreeBlock.prototype.createInnerBlocks = function () {
  52100. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  52101. };
  52102. return OctreeBlock;
  52103. }());
  52104. BABYLON.OctreeBlock = OctreeBlock;
  52105. })(BABYLON || (BABYLON = {}));
  52106. var BABYLON;
  52107. (function (BABYLON) {
  52108. var BlurPostProcess = (function (_super) {
  52109. __extends(BlurPostProcess, _super);
  52110. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  52111. var _this = this;
  52112. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  52113. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  52114. this.direction = direction;
  52115. this.blurWidth = blurWidth;
  52116. this.onApplyObservable.add(function (effect) {
  52117. effect.setFloat2("screenSize", _this.width, _this.height);
  52118. effect.setVector2("direction", _this.direction);
  52119. effect.setFloat("blurWidth", _this.blurWidth);
  52120. });
  52121. }
  52122. return BlurPostProcess;
  52123. }(BABYLON.PostProcess));
  52124. BABYLON.BlurPostProcess = BlurPostProcess;
  52125. })(BABYLON || (BABYLON = {}));
  52126. var BABYLON;
  52127. (function (BABYLON) {
  52128. var RefractionPostProcess = (function (_super) {
  52129. __extends(RefractionPostProcess, _super);
  52130. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  52131. var _this = this;
  52132. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  52133. this.color = color;
  52134. this.depth = depth;
  52135. this.colorLevel = colorLevel;
  52136. this.onActivateObservable.add(function (cam) {
  52137. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  52138. });
  52139. this.onApplyObservable.add(function (effect) {
  52140. effect.setColor3("baseColor", _this.color);
  52141. effect.setFloat("depth", _this.depth);
  52142. effect.setFloat("colorLevel", _this.colorLevel);
  52143. effect.setTexture("refractionSampler", _this._refRexture);
  52144. });
  52145. }
  52146. // Methods
  52147. RefractionPostProcess.prototype.dispose = function (camera) {
  52148. if (this._refRexture) {
  52149. this._refRexture.dispose();
  52150. }
  52151. _super.prototype.dispose.call(this, camera);
  52152. };
  52153. return RefractionPostProcess;
  52154. }(BABYLON.PostProcess));
  52155. BABYLON.RefractionPostProcess = RefractionPostProcess;
  52156. })(BABYLON || (BABYLON = {}));
  52157. var BABYLON;
  52158. (function (BABYLON) {
  52159. var BlackAndWhitePostProcess = (function (_super) {
  52160. __extends(BlackAndWhitePostProcess, _super);
  52161. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  52162. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  52163. }
  52164. return BlackAndWhitePostProcess;
  52165. }(BABYLON.PostProcess));
  52166. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  52167. })(BABYLON || (BABYLON = {}));
  52168. var BABYLON;
  52169. (function (BABYLON) {
  52170. var ConvolutionPostProcess = (function (_super) {
  52171. __extends(ConvolutionPostProcess, _super);
  52172. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  52173. var _this = this;
  52174. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  52175. this.kernel = kernel;
  52176. this.onApply = function (effect) {
  52177. effect.setFloat2("screenSize", _this.width, _this.height);
  52178. effect.setArray("kernel", _this.kernel);
  52179. };
  52180. }
  52181. // Statics
  52182. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  52183. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  52184. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  52185. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  52186. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  52187. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  52188. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  52189. return ConvolutionPostProcess;
  52190. }(BABYLON.PostProcess));
  52191. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  52192. })(BABYLON || (BABYLON = {}));
  52193. var BABYLON;
  52194. (function (BABYLON) {
  52195. var FilterPostProcess = (function (_super) {
  52196. __extends(FilterPostProcess, _super);
  52197. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  52198. var _this = this;
  52199. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  52200. this.kernelMatrix = kernelMatrix;
  52201. this.onApply = function (effect) {
  52202. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  52203. };
  52204. }
  52205. return FilterPostProcess;
  52206. }(BABYLON.PostProcess));
  52207. BABYLON.FilterPostProcess = FilterPostProcess;
  52208. })(BABYLON || (BABYLON = {}));
  52209. var BABYLON;
  52210. (function (BABYLON) {
  52211. var FxaaPostProcess = (function (_super) {
  52212. __extends(FxaaPostProcess, _super);
  52213. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  52214. var _this = this;
  52215. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  52216. this.onSizeChangedObservable.add(function () {
  52217. _this.texelWidth = 1.0 / _this.width;
  52218. _this.texelHeight = 1.0 / _this.height;
  52219. });
  52220. this.onApplyObservable.add(function (effect) {
  52221. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  52222. });
  52223. }
  52224. return FxaaPostProcess;
  52225. }(BABYLON.PostProcess));
  52226. BABYLON.FxaaPostProcess = FxaaPostProcess;
  52227. })(BABYLON || (BABYLON = {}));
  52228. var BABYLON;
  52229. (function (BABYLON) {
  52230. var StereoscopicInterlacePostProcess = (function (_super) {
  52231. __extends(StereoscopicInterlacePostProcess, _super);
  52232. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  52233. var _this = this;
  52234. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  52235. this._passedProcess = rigCameras[0]._rigPostProcess;
  52236. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  52237. this.onSizeChangedObservable.add(function () {
  52238. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  52239. });
  52240. this.onApplyObservable.add(function (effect) {
  52241. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  52242. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  52243. });
  52244. }
  52245. return StereoscopicInterlacePostProcess;
  52246. }(BABYLON.PostProcess));
  52247. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  52248. })(BABYLON || (BABYLON = {}));
  52249. var BABYLON;
  52250. (function (BABYLON) {
  52251. var LensFlare = (function () {
  52252. function LensFlare(size, position, color, imgUrl, system) {
  52253. this.size = size;
  52254. this.position = position;
  52255. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  52256. this.dispose = function () {
  52257. if (this.texture) {
  52258. this.texture.dispose();
  52259. }
  52260. // Remove from scene
  52261. var index = this._system.lensFlares.indexOf(this);
  52262. this._system.lensFlares.splice(index, 1);
  52263. };
  52264. this.color = color || new BABYLON.Color3(1, 1, 1);
  52265. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  52266. this._system = system;
  52267. system.lensFlares.push(this);
  52268. }
  52269. return LensFlare;
  52270. }());
  52271. BABYLON.LensFlare = LensFlare;
  52272. })(BABYLON || (BABYLON = {}));
  52273. var BABYLON;
  52274. (function (BABYLON) {
  52275. var LensFlareSystem = (function () {
  52276. function LensFlareSystem(name, emitter, scene) {
  52277. this.name = name;
  52278. this.lensFlares = new Array();
  52279. this.borderLimit = 300;
  52280. this.layerMask = 0x0FFFFFFF;
  52281. this._vertexBuffers = {};
  52282. this._isEnabled = true;
  52283. this._scene = scene;
  52284. this._emitter = emitter;
  52285. this.id = name;
  52286. scene.lensFlareSystems.push(this);
  52287. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  52288. var engine = scene.getEngine();
  52289. // VBO
  52290. var vertices = [];
  52291. vertices.push(1, 1);
  52292. vertices.push(-1, 1);
  52293. vertices.push(-1, -1);
  52294. vertices.push(1, -1);
  52295. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  52296. // Indices
  52297. var indices = [];
  52298. indices.push(0);
  52299. indices.push(1);
  52300. indices.push(2);
  52301. indices.push(0);
  52302. indices.push(2);
  52303. indices.push(3);
  52304. this._indexBuffer = engine.createIndexBuffer(indices);
  52305. // Effects
  52306. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  52307. }
  52308. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  52309. get: function () {
  52310. return this._isEnabled;
  52311. },
  52312. set: function (value) {
  52313. this._isEnabled = value;
  52314. },
  52315. enumerable: true,
  52316. configurable: true
  52317. });
  52318. LensFlareSystem.prototype.getScene = function () {
  52319. return this._scene;
  52320. };
  52321. LensFlareSystem.prototype.getEmitter = function () {
  52322. return this._emitter;
  52323. };
  52324. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  52325. this._emitter = newEmitter;
  52326. };
  52327. LensFlareSystem.prototype.getEmitterPosition = function () {
  52328. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  52329. };
  52330. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  52331. var position = this.getEmitterPosition();
  52332. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  52333. this._positionX = position.x;
  52334. this._positionY = position.y;
  52335. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  52336. if (position.z > 0) {
  52337. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  52338. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  52339. return true;
  52340. }
  52341. }
  52342. return false;
  52343. };
  52344. LensFlareSystem.prototype._isVisible = function () {
  52345. if (!this._isEnabled) {
  52346. return false;
  52347. }
  52348. var emitterPosition = this.getEmitterPosition();
  52349. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  52350. var distance = direction.length();
  52351. direction.normalize();
  52352. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  52353. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  52354. return !pickInfo.hit || pickInfo.distance > distance;
  52355. };
  52356. LensFlareSystem.prototype.render = function () {
  52357. if (!this._effect.isReady())
  52358. return false;
  52359. var engine = this._scene.getEngine();
  52360. var viewport = this._scene.activeCamera.viewport;
  52361. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  52362. // Position
  52363. if (!this.computeEffectivePosition(globalViewport)) {
  52364. return false;
  52365. }
  52366. // Visibility
  52367. if (!this._isVisible()) {
  52368. return false;
  52369. }
  52370. // Intensity
  52371. var awayX;
  52372. var awayY;
  52373. if (this._positionX < this.borderLimit + globalViewport.x) {
  52374. awayX = this.borderLimit + globalViewport.x - this._positionX;
  52375. }
  52376. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  52377. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  52378. }
  52379. else {
  52380. awayX = 0;
  52381. }
  52382. if (this._positionY < this.borderLimit + globalViewport.y) {
  52383. awayY = this.borderLimit + globalViewport.y - this._positionY;
  52384. }
  52385. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  52386. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  52387. }
  52388. else {
  52389. awayY = 0;
  52390. }
  52391. var away = (awayX > awayY) ? awayX : awayY;
  52392. if (away > this.borderLimit) {
  52393. away = this.borderLimit;
  52394. }
  52395. var intensity = 1.0 - (away / this.borderLimit);
  52396. if (intensity < 0) {
  52397. return false;
  52398. }
  52399. if (intensity > 1.0) {
  52400. intensity = 1.0;
  52401. }
  52402. // Position
  52403. var centerX = globalViewport.x + globalViewport.width / 2;
  52404. var centerY = globalViewport.y + globalViewport.height / 2;
  52405. var distX = centerX - this._positionX;
  52406. var distY = centerY - this._positionY;
  52407. // Effects
  52408. engine.enableEffect(this._effect);
  52409. engine.setState(false);
  52410. engine.setDepthBuffer(false);
  52411. // VBOs
  52412. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  52413. // Flares
  52414. for (var index = 0; index < this.lensFlares.length; index++) {
  52415. var flare = this.lensFlares[index];
  52416. engine.setAlphaMode(flare.alphaMode);
  52417. var x = centerX - (distX * flare.position);
  52418. var y = centerY - (distY * flare.position);
  52419. var cw = flare.size;
  52420. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  52421. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  52422. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  52423. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  52424. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  52425. // Texture
  52426. this._effect.setTexture("textureSampler", flare.texture);
  52427. // Color
  52428. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  52429. // Draw order
  52430. engine.draw(true, 0, 6);
  52431. }
  52432. engine.setDepthBuffer(true);
  52433. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52434. return true;
  52435. };
  52436. LensFlareSystem.prototype.dispose = function () {
  52437. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  52438. if (vertexBuffer) {
  52439. vertexBuffer.dispose();
  52440. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  52441. }
  52442. if (this._indexBuffer) {
  52443. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52444. this._indexBuffer = null;
  52445. }
  52446. while (this.lensFlares.length) {
  52447. this.lensFlares[0].dispose();
  52448. }
  52449. // Remove from scene
  52450. var index = this._scene.lensFlareSystems.indexOf(this);
  52451. this._scene.lensFlareSystems.splice(index, 1);
  52452. };
  52453. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  52454. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  52455. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  52456. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  52457. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  52458. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  52459. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  52460. var parsedFlare = parsedLensFlareSystem.flares[index];
  52461. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  52462. }
  52463. return lensFlareSystem;
  52464. };
  52465. LensFlareSystem.prototype.serialize = function () {
  52466. var serializationObject = {};
  52467. serializationObject.id = this.id;
  52468. serializationObject.name = this.name;
  52469. serializationObject.emitterId = this.getEmitter().id;
  52470. serializationObject.borderLimit = this.borderLimit;
  52471. serializationObject.flares = [];
  52472. for (var index = 0; index < this.lensFlares.length; index++) {
  52473. var flare = this.lensFlares[index];
  52474. serializationObject.flares.push({
  52475. size: flare.size,
  52476. position: flare.position,
  52477. color: flare.color.asArray(),
  52478. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  52479. });
  52480. }
  52481. return serializationObject;
  52482. };
  52483. return LensFlareSystem;
  52484. }());
  52485. BABYLON.LensFlareSystem = LensFlareSystem;
  52486. })(BABYLON || (BABYLON = {}));
  52487. var BABYLON;
  52488. (function (BABYLON) {
  52489. // We're mainly based on the logic defined into the FreeCamera code
  52490. var DeviceOrientationCamera = (function (_super) {
  52491. __extends(DeviceOrientationCamera, _super);
  52492. //-- end properties for backward compatibility for inputs
  52493. function DeviceOrientationCamera(name, position, scene) {
  52494. _super.call(this, name, position, scene);
  52495. this.inputs.addDeviceOrientation();
  52496. }
  52497. Object.defineProperty(DeviceOrientationCamera.prototype, "angularSensibility", {
  52498. //-- Begin properties for backward compatibility for inputs
  52499. get: function () {
  52500. return 0;
  52501. },
  52502. set: function (value) {
  52503. },
  52504. enumerable: true,
  52505. configurable: true
  52506. });
  52507. Object.defineProperty(DeviceOrientationCamera.prototype, "moveSensibility", {
  52508. get: function () {
  52509. return 0;
  52510. },
  52511. set: function (value) {
  52512. },
  52513. enumerable: true,
  52514. configurable: true
  52515. });
  52516. DeviceOrientationCamera.prototype.getTypeName = function () {
  52517. return "DeviceOrientationCamera";
  52518. };
  52519. return DeviceOrientationCamera;
  52520. }(BABYLON.FreeCamera));
  52521. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  52522. })(BABYLON || (BABYLON = {}));
  52523. var BABYLON;
  52524. (function (BABYLON) {
  52525. // We're mainly based on the logic defined into the FreeCamera code
  52526. var UniversalCamera = (function (_super) {
  52527. __extends(UniversalCamera, _super);
  52528. //-- end properties for backward compatibility for inputs
  52529. function UniversalCamera(name, position, scene) {
  52530. _super.call(this, name, position, scene);
  52531. this.inputs.addGamepad();
  52532. }
  52533. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  52534. //-- Begin properties for backward compatibility for inputs
  52535. get: function () {
  52536. var gamepad = this.inputs.attached["gamepad"];
  52537. if (gamepad)
  52538. return gamepad.gamepadAngularSensibility;
  52539. },
  52540. set: function (value) {
  52541. var gamepad = this.inputs.attached["gamepad"];
  52542. if (gamepad)
  52543. gamepad.gamepadAngularSensibility = value;
  52544. },
  52545. enumerable: true,
  52546. configurable: true
  52547. });
  52548. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  52549. get: function () {
  52550. var gamepad = this.inputs.attached["gamepad"];
  52551. if (gamepad)
  52552. return gamepad.gamepadMoveSensibility;
  52553. },
  52554. set: function (value) {
  52555. var gamepad = this.inputs.attached["gamepad"];
  52556. if (gamepad)
  52557. gamepad.gamepadMoveSensibility = value;
  52558. },
  52559. enumerable: true,
  52560. configurable: true
  52561. });
  52562. UniversalCamera.prototype.getTypeName = function () {
  52563. return "UniversalCamera";
  52564. };
  52565. return UniversalCamera;
  52566. }(BABYLON.TouchCamera));
  52567. BABYLON.UniversalCamera = UniversalCamera;
  52568. })(BABYLON || (BABYLON = {}));
  52569. var BABYLON;
  52570. (function (BABYLON) {
  52571. var Gamepads = (function () {
  52572. function Gamepads(ongamedpadconnected) {
  52573. var _this = this;
  52574. this.babylonGamepads = [];
  52575. this.oneGamepadConnected = false;
  52576. this.isMonitoring = false;
  52577. this.gamepadEventSupported = 'GamepadEvent' in window;
  52578. this.gamepadSupportAvailable = (navigator.getGamepads ||
  52579. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  52580. this._callbackGamepadConnected = ongamedpadconnected;
  52581. if (this.gamepadSupportAvailable) {
  52582. // Checking if the gamepad connected event is supported (like in Firefox)
  52583. if (this.gamepadEventSupported) {
  52584. this._onGamepadConnectedEvent = function (evt) {
  52585. _this._onGamepadConnected(evt);
  52586. };
  52587. this._onGamepadDisonnectedEvent = function (evt) {
  52588. _this._onGamepadDisconnected(evt);
  52589. };
  52590. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  52591. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  52592. }
  52593. else {
  52594. this._startMonitoringGamepads();
  52595. }
  52596. }
  52597. }
  52598. Gamepads.prototype.dispose = function () {
  52599. if (Gamepads.gamepadDOMInfo) {
  52600. document.body.removeChild(Gamepads.gamepadDOMInfo);
  52601. }
  52602. if (this._onGamepadConnectedEvent) {
  52603. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  52604. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  52605. this._onGamepadConnectedEvent = null;
  52606. this._onGamepadDisonnectedEvent = null;
  52607. }
  52608. };
  52609. Gamepads.prototype._onGamepadConnected = function (evt) {
  52610. var newGamepad = this._addNewGamepad(evt.gamepad);
  52611. if (this._callbackGamepadConnected)
  52612. this._callbackGamepadConnected(newGamepad);
  52613. this._startMonitoringGamepads();
  52614. };
  52615. Gamepads.prototype._addNewGamepad = function (gamepad) {
  52616. if (!this.oneGamepadConnected) {
  52617. this.oneGamepadConnected = true;
  52618. if (Gamepads.gamepadDOMInfo) {
  52619. document.body.removeChild(Gamepads.gamepadDOMInfo);
  52620. Gamepads.gamepadDOMInfo = null;
  52621. }
  52622. }
  52623. var newGamepad;
  52624. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  52625. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  52626. }
  52627. else {
  52628. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  52629. }
  52630. this.babylonGamepads.push(newGamepad);
  52631. return newGamepad;
  52632. };
  52633. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  52634. // Remove the gamepad from the list of gamepads to monitor.
  52635. for (var i in this.babylonGamepads) {
  52636. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  52637. this.babylonGamepads.splice(+i, 1);
  52638. break;
  52639. }
  52640. }
  52641. // If no gamepads are left, stop the polling loop.
  52642. if (this.babylonGamepads.length == 0) {
  52643. this._stopMonitoringGamepads();
  52644. }
  52645. };
  52646. Gamepads.prototype._startMonitoringGamepads = function () {
  52647. if (!this.isMonitoring) {
  52648. this.isMonitoring = true;
  52649. this._checkGamepadsStatus();
  52650. }
  52651. };
  52652. Gamepads.prototype._stopMonitoringGamepads = function () {
  52653. this.isMonitoring = false;
  52654. };
  52655. Gamepads.prototype._checkGamepadsStatus = function () {
  52656. var _this = this;
  52657. // updating gamepad objects
  52658. this._updateGamepadObjects();
  52659. for (var i in this.babylonGamepads) {
  52660. this.babylonGamepads[i].update();
  52661. }
  52662. if (this.isMonitoring) {
  52663. if (window.requestAnimationFrame) {
  52664. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  52665. }
  52666. else if (window.mozRequestAnimationFrame) {
  52667. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  52668. }
  52669. else if (window.webkitRequestAnimationFrame) {
  52670. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  52671. }
  52672. }
  52673. };
  52674. // This function is called only on Chrome, which does not yet support
  52675. // connection/disconnection events, but requires you to monitor
  52676. // an array for changes.
  52677. Gamepads.prototype._updateGamepadObjects = function () {
  52678. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  52679. for (var i = 0; i < gamepads.length; i++) {
  52680. if (gamepads[i]) {
  52681. if (!(gamepads[i].index in this.babylonGamepads)) {
  52682. var newGamepad = this._addNewGamepad(gamepads[i]);
  52683. if (this._callbackGamepadConnected) {
  52684. this._callbackGamepadConnected(newGamepad);
  52685. }
  52686. }
  52687. else {
  52688. this.babylonGamepads[i].browserGamepad = gamepads[i];
  52689. }
  52690. }
  52691. }
  52692. };
  52693. return Gamepads;
  52694. }());
  52695. BABYLON.Gamepads = Gamepads;
  52696. var StickValues = (function () {
  52697. function StickValues(x, y) {
  52698. this.x = x;
  52699. this.y = y;
  52700. }
  52701. return StickValues;
  52702. }());
  52703. BABYLON.StickValues = StickValues;
  52704. var Gamepad = (function () {
  52705. function Gamepad(id, index, browserGamepad) {
  52706. this.id = id;
  52707. this.index = index;
  52708. this.browserGamepad = browserGamepad;
  52709. if (this.browserGamepad.axes.length >= 2) {
  52710. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  52711. }
  52712. if (this.browserGamepad.axes.length >= 4) {
  52713. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  52714. }
  52715. }
  52716. Gamepad.prototype.onleftstickchanged = function (callback) {
  52717. this._onleftstickchanged = callback;
  52718. };
  52719. Gamepad.prototype.onrightstickchanged = function (callback) {
  52720. this._onrightstickchanged = callback;
  52721. };
  52722. Object.defineProperty(Gamepad.prototype, "leftStick", {
  52723. get: function () {
  52724. return this._leftStick;
  52725. },
  52726. set: function (newValues) {
  52727. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  52728. this._onleftstickchanged(newValues);
  52729. }
  52730. this._leftStick = newValues;
  52731. },
  52732. enumerable: true,
  52733. configurable: true
  52734. });
  52735. Object.defineProperty(Gamepad.prototype, "rightStick", {
  52736. get: function () {
  52737. return this._rightStick;
  52738. },
  52739. set: function (newValues) {
  52740. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  52741. this._onrightstickchanged(newValues);
  52742. }
  52743. this._rightStick = newValues;
  52744. },
  52745. enumerable: true,
  52746. configurable: true
  52747. });
  52748. Gamepad.prototype.update = function () {
  52749. if (this._leftStick) {
  52750. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  52751. }
  52752. if (this._rightStick) {
  52753. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  52754. }
  52755. };
  52756. return Gamepad;
  52757. }());
  52758. BABYLON.Gamepad = Gamepad;
  52759. var GenericPad = (function (_super) {
  52760. __extends(GenericPad, _super);
  52761. function GenericPad(id, index, gamepad) {
  52762. _super.call(this, id, index, gamepad);
  52763. this.id = id;
  52764. this.index = index;
  52765. this.gamepad = gamepad;
  52766. this._buttons = new Array(gamepad.buttons.length);
  52767. }
  52768. GenericPad.prototype.onbuttondown = function (callback) {
  52769. this._onbuttondown = callback;
  52770. };
  52771. GenericPad.prototype.onbuttonup = function (callback) {
  52772. this._onbuttonup = callback;
  52773. };
  52774. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  52775. if (newValue !== currentValue) {
  52776. if (this._onbuttondown && newValue === 1) {
  52777. this._onbuttondown(buttonIndex);
  52778. }
  52779. if (this._onbuttonup && newValue === 0) {
  52780. this._onbuttonup(buttonIndex);
  52781. }
  52782. }
  52783. return newValue;
  52784. };
  52785. GenericPad.prototype.update = function () {
  52786. _super.prototype.update.call(this);
  52787. for (var index = 0; index < this._buttons.length; index++) {
  52788. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  52789. }
  52790. };
  52791. return GenericPad;
  52792. }(Gamepad));
  52793. BABYLON.GenericPad = GenericPad;
  52794. (function (Xbox360Button) {
  52795. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  52796. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  52797. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  52798. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  52799. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  52800. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  52801. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  52802. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  52803. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  52804. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  52805. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  52806. var Xbox360Button = BABYLON.Xbox360Button;
  52807. (function (Xbox360Dpad) {
  52808. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  52809. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  52810. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  52811. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  52812. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  52813. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  52814. var Xbox360Pad = (function (_super) {
  52815. __extends(Xbox360Pad, _super);
  52816. function Xbox360Pad() {
  52817. _super.apply(this, arguments);
  52818. this._leftTrigger = 0;
  52819. this._rightTrigger = 0;
  52820. this._buttonA = 0;
  52821. this._buttonB = 0;
  52822. this._buttonX = 0;
  52823. this._buttonY = 0;
  52824. this._buttonBack = 0;
  52825. this._buttonStart = 0;
  52826. this._buttonLB = 0;
  52827. this._buttonRB = 0;
  52828. this._buttonLeftStick = 0;
  52829. this._buttonRightStick = 0;
  52830. this._dPadUp = 0;
  52831. this._dPadDown = 0;
  52832. this._dPadLeft = 0;
  52833. this._dPadRight = 0;
  52834. }
  52835. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  52836. this._onlefttriggerchanged = callback;
  52837. };
  52838. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  52839. this._onrighttriggerchanged = callback;
  52840. };
  52841. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  52842. get: function () {
  52843. return this._leftTrigger;
  52844. },
  52845. set: function (newValue) {
  52846. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  52847. this._onlefttriggerchanged(newValue);
  52848. }
  52849. this._leftTrigger = newValue;
  52850. },
  52851. enumerable: true,
  52852. configurable: true
  52853. });
  52854. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  52855. get: function () {
  52856. return this._rightTrigger;
  52857. },
  52858. set: function (newValue) {
  52859. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  52860. this._onrighttriggerchanged(newValue);
  52861. }
  52862. this._rightTrigger = newValue;
  52863. },
  52864. enumerable: true,
  52865. configurable: true
  52866. });
  52867. Xbox360Pad.prototype.onbuttondown = function (callback) {
  52868. this._onbuttondown = callback;
  52869. };
  52870. Xbox360Pad.prototype.onbuttonup = function (callback) {
  52871. this._onbuttonup = callback;
  52872. };
  52873. Xbox360Pad.prototype.ondpaddown = function (callback) {
  52874. this._ondpaddown = callback;
  52875. };
  52876. Xbox360Pad.prototype.ondpadup = function (callback) {
  52877. this._ondpadup = callback;
  52878. };
  52879. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  52880. if (newValue !== currentValue) {
  52881. if (this._onbuttondown && newValue === 1) {
  52882. this._onbuttondown(buttonType);
  52883. }
  52884. if (this._onbuttonup && newValue === 0) {
  52885. this._onbuttonup(buttonType);
  52886. }
  52887. }
  52888. return newValue;
  52889. };
  52890. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  52891. if (newValue !== currentValue) {
  52892. if (this._ondpaddown && newValue === 1) {
  52893. this._ondpaddown(buttonType);
  52894. }
  52895. if (this._ondpadup && newValue === 0) {
  52896. this._ondpadup(buttonType);
  52897. }
  52898. }
  52899. return newValue;
  52900. };
  52901. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  52902. get: function () {
  52903. return this._buttonA;
  52904. },
  52905. set: function (value) {
  52906. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  52907. },
  52908. enumerable: true,
  52909. configurable: true
  52910. });
  52911. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  52912. get: function () {
  52913. return this._buttonB;
  52914. },
  52915. set: function (value) {
  52916. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  52917. },
  52918. enumerable: true,
  52919. configurable: true
  52920. });
  52921. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  52922. get: function () {
  52923. return this._buttonX;
  52924. },
  52925. set: function (value) {
  52926. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  52927. },
  52928. enumerable: true,
  52929. configurable: true
  52930. });
  52931. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  52932. get: function () {
  52933. return this._buttonY;
  52934. },
  52935. set: function (value) {
  52936. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  52937. },
  52938. enumerable: true,
  52939. configurable: true
  52940. });
  52941. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  52942. get: function () {
  52943. return this._buttonStart;
  52944. },
  52945. set: function (value) {
  52946. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  52947. },
  52948. enumerable: true,
  52949. configurable: true
  52950. });
  52951. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  52952. get: function () {
  52953. return this._buttonBack;
  52954. },
  52955. set: function (value) {
  52956. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  52957. },
  52958. enumerable: true,
  52959. configurable: true
  52960. });
  52961. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  52962. get: function () {
  52963. return this._buttonLB;
  52964. },
  52965. set: function (value) {
  52966. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  52967. },
  52968. enumerable: true,
  52969. configurable: true
  52970. });
  52971. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  52972. get: function () {
  52973. return this._buttonRB;
  52974. },
  52975. set: function (value) {
  52976. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  52977. },
  52978. enumerable: true,
  52979. configurable: true
  52980. });
  52981. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  52982. get: function () {
  52983. return this._buttonLeftStick;
  52984. },
  52985. set: function (value) {
  52986. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  52987. },
  52988. enumerable: true,
  52989. configurable: true
  52990. });
  52991. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  52992. get: function () {
  52993. return this._buttonRightStick;
  52994. },
  52995. set: function (value) {
  52996. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  52997. },
  52998. enumerable: true,
  52999. configurable: true
  53000. });
  53001. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  53002. get: function () {
  53003. return this._dPadUp;
  53004. },
  53005. set: function (value) {
  53006. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  53007. },
  53008. enumerable: true,
  53009. configurable: true
  53010. });
  53011. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  53012. get: function () {
  53013. return this._dPadDown;
  53014. },
  53015. set: function (value) {
  53016. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  53017. },
  53018. enumerable: true,
  53019. configurable: true
  53020. });
  53021. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  53022. get: function () {
  53023. return this._dPadLeft;
  53024. },
  53025. set: function (value) {
  53026. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  53027. },
  53028. enumerable: true,
  53029. configurable: true
  53030. });
  53031. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  53032. get: function () {
  53033. return this._dPadRight;
  53034. },
  53035. set: function (value) {
  53036. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  53037. },
  53038. enumerable: true,
  53039. configurable: true
  53040. });
  53041. Xbox360Pad.prototype.update = function () {
  53042. _super.prototype.update.call(this);
  53043. this.buttonA = this.browserGamepad.buttons[0].value;
  53044. this.buttonB = this.browserGamepad.buttons[1].value;
  53045. this.buttonX = this.browserGamepad.buttons[2].value;
  53046. this.buttonY = this.browserGamepad.buttons[3].value;
  53047. this.buttonLB = this.browserGamepad.buttons[4].value;
  53048. this.buttonRB = this.browserGamepad.buttons[5].value;
  53049. this.leftTrigger = this.browserGamepad.buttons[6].value;
  53050. this.rightTrigger = this.browserGamepad.buttons[7].value;
  53051. this.buttonBack = this.browserGamepad.buttons[8].value;
  53052. this.buttonStart = this.browserGamepad.buttons[9].value;
  53053. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  53054. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  53055. this.dPadUp = this.browserGamepad.buttons[12].value;
  53056. this.dPadDown = this.browserGamepad.buttons[13].value;
  53057. this.dPadLeft = this.browserGamepad.buttons[14].value;
  53058. this.dPadRight = this.browserGamepad.buttons[15].value;
  53059. };
  53060. return Xbox360Pad;
  53061. }(Gamepad));
  53062. BABYLON.Xbox360Pad = Xbox360Pad;
  53063. })(BABYLON || (BABYLON = {}));
  53064. var BABYLON;
  53065. (function (BABYLON) {
  53066. // We're mainly based on the logic defined into the FreeCamera code
  53067. var GamepadCamera = (function (_super) {
  53068. __extends(GamepadCamera, _super);
  53069. //-- end properties for backward compatibility for inputs
  53070. function GamepadCamera(name, position, scene) {
  53071. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  53072. _super.call(this, name, position, scene);
  53073. }
  53074. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  53075. //-- Begin properties for backward compatibility for inputs
  53076. get: function () {
  53077. var gamepad = this.inputs.attached["gamepad"];
  53078. if (gamepad)
  53079. return gamepad.gamepadAngularSensibility;
  53080. },
  53081. set: function (value) {
  53082. var gamepad = this.inputs.attached["gamepad"];
  53083. if (gamepad)
  53084. gamepad.gamepadAngularSensibility = value;
  53085. },
  53086. enumerable: true,
  53087. configurable: true
  53088. });
  53089. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  53090. get: function () {
  53091. var gamepad = this.inputs.attached["gamepad"];
  53092. if (gamepad)
  53093. return gamepad.gamepadMoveSensibility;
  53094. },
  53095. set: function (value) {
  53096. var gamepad = this.inputs.attached["gamepad"];
  53097. if (gamepad)
  53098. gamepad.gamepadMoveSensibility = value;
  53099. },
  53100. enumerable: true,
  53101. configurable: true
  53102. });
  53103. GamepadCamera.prototype.getTypeName = function () {
  53104. return "GamepadCamera";
  53105. };
  53106. return GamepadCamera;
  53107. }(BABYLON.UniversalCamera));
  53108. BABYLON.GamepadCamera = GamepadCamera;
  53109. })(BABYLON || (BABYLON = {}));
  53110. var BABYLON;
  53111. (function (BABYLON) {
  53112. var Analyser = (function () {
  53113. function Analyser(scene) {
  53114. this.SMOOTHING = 0.75;
  53115. this.FFT_SIZE = 512;
  53116. this.BARGRAPHAMPLITUDE = 256;
  53117. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  53118. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  53119. this._scene = scene;
  53120. this._audioEngine = BABYLON.Engine.audioEngine;
  53121. if (this._audioEngine.canUseWebAudio) {
  53122. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  53123. this._webAudioAnalyser.minDecibels = -140;
  53124. this._webAudioAnalyser.maxDecibels = 0;
  53125. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  53126. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  53127. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  53128. }
  53129. }
  53130. Analyser.prototype.getFrequencyBinCount = function () {
  53131. if (this._audioEngine.canUseWebAudio) {
  53132. return this._webAudioAnalyser.frequencyBinCount;
  53133. }
  53134. else {
  53135. return 0;
  53136. }
  53137. };
  53138. Analyser.prototype.getByteFrequencyData = function () {
  53139. if (this._audioEngine.canUseWebAudio) {
  53140. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53141. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53142. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  53143. }
  53144. return this._byteFreqs;
  53145. };
  53146. Analyser.prototype.getByteTimeDomainData = function () {
  53147. if (this._audioEngine.canUseWebAudio) {
  53148. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53149. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53150. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  53151. }
  53152. return this._byteTime;
  53153. };
  53154. Analyser.prototype.getFloatFrequencyData = function () {
  53155. if (this._audioEngine.canUseWebAudio) {
  53156. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53157. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53158. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  53159. }
  53160. return this._floatFreqs;
  53161. };
  53162. Analyser.prototype.drawDebugCanvas = function () {
  53163. var _this = this;
  53164. if (this._audioEngine.canUseWebAudio) {
  53165. if (!this._debugCanvas) {
  53166. this._debugCanvas = document.createElement("canvas");
  53167. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  53168. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  53169. this._debugCanvas.style.position = "absolute";
  53170. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  53171. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  53172. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  53173. document.body.appendChild(this._debugCanvas);
  53174. this._registerFunc = function () {
  53175. _this.drawDebugCanvas();
  53176. };
  53177. this._scene.registerBeforeRender(this._registerFunc);
  53178. }
  53179. if (this._registerFunc) {
  53180. var workingArray = this.getByteFrequencyData();
  53181. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  53182. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  53183. // Draw the frequency domain chart.
  53184. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  53185. var value = workingArray[i];
  53186. var percent = value / this.BARGRAPHAMPLITUDE;
  53187. var height = this.DEBUGCANVASSIZE.height * percent;
  53188. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  53189. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  53190. var hue = i / this.getFrequencyBinCount() * 360;
  53191. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  53192. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  53193. }
  53194. }
  53195. }
  53196. };
  53197. Analyser.prototype.stopDebugCanvas = function () {
  53198. if (this._debugCanvas) {
  53199. this._scene.unregisterBeforeRender(this._registerFunc);
  53200. this._registerFunc = null;
  53201. document.body.removeChild(this._debugCanvas);
  53202. this._debugCanvas = null;
  53203. this._debugCanvasContext = null;
  53204. }
  53205. };
  53206. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  53207. if (this._audioEngine.canUseWebAudio) {
  53208. inputAudioNode.connect(this._webAudioAnalyser);
  53209. this._webAudioAnalyser.connect(outputAudioNode);
  53210. }
  53211. };
  53212. Analyser.prototype.dispose = function () {
  53213. if (this._audioEngine.canUseWebAudio) {
  53214. this._webAudioAnalyser.disconnect();
  53215. }
  53216. };
  53217. return Analyser;
  53218. }());
  53219. BABYLON.Analyser = Analyser;
  53220. })(BABYLON || (BABYLON = {}));
  53221. var BABYLON;
  53222. (function (BABYLON) {
  53223. var DepthRenderer = (function () {
  53224. function DepthRenderer(scene, type) {
  53225. var _this = this;
  53226. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  53227. this._viewMatrix = BABYLON.Matrix.Zero();
  53228. this._projectionMatrix = BABYLON.Matrix.Zero();
  53229. this._transformMatrix = BABYLON.Matrix.Zero();
  53230. this._worldViewProjection = BABYLON.Matrix.Zero();
  53231. this._scene = scene;
  53232. var engine = scene.getEngine();
  53233. // Render target
  53234. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  53235. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53236. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53237. this._depthMap.refreshRate = 1;
  53238. this._depthMap.renderParticles = false;
  53239. this._depthMap.renderList = null;
  53240. // set default depth value to 1.0 (far away)
  53241. this._depthMap.onClearObservable.add(function (engine) {
  53242. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  53243. });
  53244. // Custom render function
  53245. var renderSubMesh = function (subMesh) {
  53246. var mesh = subMesh.getRenderingMesh();
  53247. var scene = _this._scene;
  53248. var engine = scene.getEngine();
  53249. // Culling
  53250. engine.setState(subMesh.getMaterial().backFaceCulling);
  53251. // Managing instances
  53252. var batch = mesh._getInstancesRenderList(subMesh._id);
  53253. if (batch.mustReturn) {
  53254. return;
  53255. }
  53256. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  53257. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  53258. engine.enableEffect(_this._effect);
  53259. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  53260. var material = subMesh.getMaterial();
  53261. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  53262. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  53263. // Alpha test
  53264. if (material && material.needAlphaTesting()) {
  53265. var alphaTexture = material.getAlphaTestTexture();
  53266. _this._effect.setTexture("diffuseSampler", alphaTexture);
  53267. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  53268. }
  53269. // Bones
  53270. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53271. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  53272. }
  53273. // Draw
  53274. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  53275. }
  53276. };
  53277. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  53278. var index;
  53279. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53280. renderSubMesh(opaqueSubMeshes.data[index]);
  53281. }
  53282. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53283. renderSubMesh(alphaTestSubMeshes.data[index]);
  53284. }
  53285. };
  53286. }
  53287. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  53288. var material = subMesh.getMaterial();
  53289. if (material.disableDepthWrite) {
  53290. return false;
  53291. }
  53292. var defines = [];
  53293. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53294. var mesh = subMesh.getMesh();
  53295. var scene = mesh.getScene();
  53296. // Alpha test
  53297. if (material && material.needAlphaTesting()) {
  53298. defines.push("#define ALPHATEST");
  53299. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53300. attribs.push(BABYLON.VertexBuffer.UVKind);
  53301. defines.push("#define UV1");
  53302. }
  53303. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53304. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53305. defines.push("#define UV2");
  53306. }
  53307. }
  53308. // Bones
  53309. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53310. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53311. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53312. if (mesh.numBoneInfluencers > 4) {
  53313. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53314. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53315. }
  53316. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53317. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53318. }
  53319. else {
  53320. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53321. }
  53322. // Instances
  53323. if (useInstances) {
  53324. defines.push("#define INSTANCES");
  53325. attribs.push("world0");
  53326. attribs.push("world1");
  53327. attribs.push("world2");
  53328. attribs.push("world3");
  53329. }
  53330. // Get correct effect
  53331. var join = defines.join("\n");
  53332. if (this._cachedDefines !== join) {
  53333. this._cachedDefines = join;
  53334. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  53335. }
  53336. return this._effect.isReady();
  53337. };
  53338. DepthRenderer.prototype.getDepthMap = function () {
  53339. return this._depthMap;
  53340. };
  53341. // Methods
  53342. DepthRenderer.prototype.dispose = function () {
  53343. this._depthMap.dispose();
  53344. };
  53345. return DepthRenderer;
  53346. }());
  53347. BABYLON.DepthRenderer = DepthRenderer;
  53348. })(BABYLON || (BABYLON = {}));
  53349. var BABYLON;
  53350. (function (BABYLON) {
  53351. var SSAORenderingPipeline = (function (_super) {
  53352. __extends(SSAORenderingPipeline, _super);
  53353. /**
  53354. * @constructor
  53355. * @param {string} name - The rendering pipeline name
  53356. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53357. * @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 }
  53358. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53359. */
  53360. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  53361. var _this = this;
  53362. _super.call(this, scene.getEngine(), name);
  53363. // Members
  53364. /**
  53365. * The PassPostProcess id in the pipeline that contains the original scene color
  53366. * @type {string}
  53367. */
  53368. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  53369. /**
  53370. * The SSAO PostProcess id in the pipeline
  53371. * @type {string}
  53372. */
  53373. this.SSAORenderEffect = "SSAORenderEffect";
  53374. /**
  53375. * The horizontal blur PostProcess id in the pipeline
  53376. * @type {string}
  53377. */
  53378. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  53379. /**
  53380. * The vertical blur PostProcess id in the pipeline
  53381. * @type {string}
  53382. */
  53383. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  53384. /**
  53385. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  53386. * @type {string}
  53387. */
  53388. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  53389. /**
  53390. * The output strength of the SSAO post-process. Default value is 1.0.
  53391. * @type {number}
  53392. */
  53393. this.totalStrength = 1.0;
  53394. /**
  53395. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  53396. * @type {number}
  53397. */
  53398. this.radius = 0.0001;
  53399. /**
  53400. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  53401. * Must not be equal to fallOff and superior to fallOff.
  53402. * Default value is 0.975
  53403. * @type {number}
  53404. */
  53405. this.area = 0.0075;
  53406. /**
  53407. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  53408. * Must not be equal to area and inferior to area.
  53409. * Default value is 0.0
  53410. * @type {number}
  53411. */
  53412. this.fallOff = 0.000001;
  53413. /**
  53414. * The base color of the SSAO post-process
  53415. * The final result is "base + ssao" between [0, 1]
  53416. * @type {number}
  53417. */
  53418. this.base = 0.5;
  53419. this._firstUpdate = true;
  53420. this._scene = scene;
  53421. // Set up assets
  53422. this._createRandomTexture();
  53423. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  53424. var ssaoRatio = ratio.ssaoRatio || ratio;
  53425. var combineRatio = ratio.combineRatio || ratio;
  53426. this._ratio = {
  53427. ssaoRatio: ssaoRatio,
  53428. combineRatio: combineRatio
  53429. };
  53430. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  53431. this._createSSAOPostProcess(ssaoRatio);
  53432. this._createBlurPostProcess(ssaoRatio);
  53433. this._createSSAOCombinePostProcess(combineRatio);
  53434. // Set up pipeline
  53435. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  53436. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  53437. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  53438. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  53439. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  53440. // Finish
  53441. scene.postProcessRenderPipelineManager.addPipeline(this);
  53442. if (cameras)
  53443. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53444. }
  53445. // Public Methods
  53446. /**
  53447. * Returns the horizontal blur PostProcess
  53448. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  53449. */
  53450. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  53451. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  53452. return null;
  53453. };
  53454. /**
  53455. * Returns the vertical blur PostProcess
  53456. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  53457. */
  53458. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  53459. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  53460. return null;
  53461. };
  53462. /**
  53463. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  53464. */
  53465. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  53466. if (disableDepthRender === void 0) { disableDepthRender = false; }
  53467. for (var i = 0; i < this._scene.cameras.length; i++) {
  53468. var camera = this._scene.cameras[i];
  53469. this._originalColorPostProcess.dispose(camera);
  53470. this._ssaoPostProcess.dispose(camera);
  53471. this._blurHPostProcess.dispose(camera);
  53472. this._blurVPostProcess.dispose(camera);
  53473. this._ssaoCombinePostProcess.dispose(camera);
  53474. }
  53475. this._randomTexture.dispose();
  53476. if (disableDepthRender)
  53477. this._scene.disableDepthRenderer();
  53478. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53479. };
  53480. // Private Methods
  53481. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  53482. var _this = this;
  53483. /*
  53484. var samplerOffsets = [
  53485. -8.0, -6.0, -4.0, -2.0,
  53486. 0.0,
  53487. 2.0, 4.0, 6.0, 8.0
  53488. ];
  53489. */
  53490. var samples = 16;
  53491. var samplerOffsets = [];
  53492. for (var i = -8; i < 8; i++) {
  53493. samplerOffsets.push(i * 2);
  53494. }
  53495. 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");
  53496. this._blurHPostProcess.onApply = function (effect) {
  53497. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  53498. effect.setTexture("depthSampler", _this._depthTexture);
  53499. if (_this._firstUpdate) {
  53500. effect.setArray("samplerOffsets", samplerOffsets);
  53501. }
  53502. };
  53503. 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");
  53504. this._blurVPostProcess.onApply = function (effect) {
  53505. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  53506. effect.setTexture("depthSampler", _this._depthTexture);
  53507. if (_this._firstUpdate) {
  53508. effect.setArray("samplerOffsets", samplerOffsets);
  53509. _this._firstUpdate = false;
  53510. }
  53511. };
  53512. };
  53513. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  53514. var _this = this;
  53515. var numSamples = 16;
  53516. var sampleSphere = [
  53517. 0.5381, 0.1856, -0.4319,
  53518. 0.1379, 0.2486, 0.4430,
  53519. 0.3371, 0.5679, -0.0057,
  53520. -0.6999, -0.0451, -0.0019,
  53521. 0.0689, -0.1598, -0.8547,
  53522. 0.0560, 0.0069, -0.1843,
  53523. -0.0146, 0.1402, 0.0762,
  53524. 0.0100, -0.1924, -0.0344,
  53525. -0.3577, -0.5301, -0.4358,
  53526. -0.3169, 0.1063, 0.0158,
  53527. 0.0103, -0.5869, 0.0046,
  53528. -0.0897, -0.4940, 0.3287,
  53529. 0.7119, -0.0154, -0.0918,
  53530. -0.0533, 0.0596, -0.5411,
  53531. 0.0352, -0.0631, 0.5460,
  53532. -0.4776, 0.2847, -0.0271
  53533. ];
  53534. var samplesFactor = 1.0 / numSamples;
  53535. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  53536. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  53537. "area", "fallOff", "base", "range", "viewport"
  53538. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  53539. var viewport = new BABYLON.Vector2(0, 0);
  53540. this._ssaoPostProcess.onApply = function (effect) {
  53541. if (_this._firstUpdate) {
  53542. effect.setArray3("sampleSphere", sampleSphere);
  53543. effect.setFloat("samplesFactor", samplesFactor);
  53544. effect.setFloat("randTextureTiles", 4.0);
  53545. }
  53546. effect.setFloat("totalStrength", _this.totalStrength);
  53547. effect.setFloat("radius", _this.radius);
  53548. effect.setFloat("area", _this.area);
  53549. effect.setFloat("fallOff", _this.fallOff);
  53550. effect.setFloat("base", _this.base);
  53551. effect.setTexture("textureSampler", _this._depthTexture);
  53552. effect.setTexture("randomSampler", _this._randomTexture);
  53553. };
  53554. };
  53555. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  53556. var _this = this;
  53557. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53558. this._ssaoCombinePostProcess.onApply = function (effect) {
  53559. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  53560. };
  53561. };
  53562. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  53563. var size = 512;
  53564. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  53565. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53566. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53567. var context = this._randomTexture.getContext();
  53568. var rand = function (min, max) {
  53569. return Math.random() * (max - min) + min;
  53570. };
  53571. var randVector = BABYLON.Vector3.Zero();
  53572. for (var x = 0; x < size; x++) {
  53573. for (var y = 0; y < size; y++) {
  53574. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  53575. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  53576. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  53577. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  53578. context.fillRect(x, y, 1, 1);
  53579. }
  53580. }
  53581. this._randomTexture.update(false);
  53582. };
  53583. __decorate([
  53584. BABYLON.serialize()
  53585. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  53586. __decorate([
  53587. BABYLON.serialize()
  53588. ], SSAORenderingPipeline.prototype, "radius", void 0);
  53589. __decorate([
  53590. BABYLON.serialize()
  53591. ], SSAORenderingPipeline.prototype, "area", void 0);
  53592. __decorate([
  53593. BABYLON.serialize()
  53594. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  53595. __decorate([
  53596. BABYLON.serialize()
  53597. ], SSAORenderingPipeline.prototype, "base", void 0);
  53598. __decorate([
  53599. BABYLON.serialize()
  53600. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  53601. return SSAORenderingPipeline;
  53602. }(BABYLON.PostProcessRenderPipeline));
  53603. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  53604. })(BABYLON || (BABYLON = {}));
  53605. var BABYLON;
  53606. (function (BABYLON) {
  53607. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  53608. var VolumetricLightScatteringPostProcess = (function (_super) {
  53609. __extends(VolumetricLightScatteringPostProcess, _super);
  53610. /**
  53611. * @constructor
  53612. * @param {string} name - The post-process name
  53613. * @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)
  53614. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  53615. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  53616. * @param {number} samples - The post-process quality, default 100
  53617. * @param {number} samplingMode - The post-process filtering mode
  53618. * @param {BABYLON.Engine} engine - The babylon engine
  53619. * @param {boolean} reusable - If the post-process is reusable
  53620. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  53621. */
  53622. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  53623. var _this = this;
  53624. if (samples === void 0) { samples = 100; }
  53625. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  53626. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  53627. this._screenCoordinates = BABYLON.Vector2.Zero();
  53628. /**
  53629. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  53630. * @type {Vector3}
  53631. */
  53632. this.customMeshPosition = BABYLON.Vector3.Zero();
  53633. /**
  53634. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  53635. * @type {boolean}
  53636. */
  53637. this.useCustomMeshPosition = false;
  53638. /**
  53639. * If the post-process should inverse the light scattering direction
  53640. * @type {boolean}
  53641. */
  53642. this.invert = true;
  53643. /**
  53644. * Array containing the excluded meshes not rendered in the internal pass
  53645. */
  53646. this.excludedMeshes = new Array();
  53647. /**
  53648. * Controls the overall intensity of the post-process
  53649. * @type {number}
  53650. */
  53651. this.exposure = 0.3;
  53652. /**
  53653. * Dissipates each sample's contribution in range [0, 1]
  53654. * @type {number}
  53655. */
  53656. this.decay = 0.96815;
  53657. /**
  53658. * Controls the overall intensity of each sample
  53659. * @type {number}
  53660. */
  53661. this.weight = 0.58767;
  53662. /**
  53663. * Controls the density of each sample
  53664. * @type {number}
  53665. */
  53666. this.density = 0.926;
  53667. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  53668. var engine = scene.getEngine();
  53669. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  53670. // Configure mesh
  53671. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  53672. // Configure
  53673. this._createPass(scene, ratio.passRatio || ratio);
  53674. this.onActivate = function (camera) {
  53675. if (!_this.isSupported) {
  53676. _this.dispose(camera);
  53677. }
  53678. _this.onActivate = null;
  53679. };
  53680. this.onApplyObservable.add(function (effect) {
  53681. _this._updateMeshScreenCoordinates(scene);
  53682. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  53683. effect.setFloat("exposure", _this.exposure);
  53684. effect.setFloat("decay", _this.decay);
  53685. effect.setFloat("weight", _this.weight);
  53686. effect.setFloat("density", _this.density);
  53687. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  53688. });
  53689. }
  53690. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  53691. get: function () {
  53692. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  53693. return false;
  53694. },
  53695. set: function (useDiffuseColor) {
  53696. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  53697. },
  53698. enumerable: true,
  53699. configurable: true
  53700. });
  53701. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  53702. var mesh = subMesh.getMesh();
  53703. // Render this.mesh as default
  53704. if (mesh === this.mesh) {
  53705. return mesh.material.isReady(mesh);
  53706. }
  53707. var defines = [];
  53708. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53709. var material = subMesh.getMaterial();
  53710. var needUV = false;
  53711. // Alpha test
  53712. if (material) {
  53713. if (material.needAlphaTesting()) {
  53714. defines.push("#define ALPHATEST");
  53715. }
  53716. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53717. attribs.push(BABYLON.VertexBuffer.UVKind);
  53718. defines.push("#define UV1");
  53719. }
  53720. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53721. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53722. defines.push("#define UV2");
  53723. }
  53724. }
  53725. // Bones
  53726. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53727. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53728. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53729. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53730. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53731. }
  53732. else {
  53733. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53734. }
  53735. // Instances
  53736. if (useInstances) {
  53737. defines.push("#define INSTANCES");
  53738. attribs.push("world0");
  53739. attribs.push("world1");
  53740. attribs.push("world2");
  53741. attribs.push("world3");
  53742. }
  53743. // Get correct effect
  53744. var join = defines.join("\n");
  53745. if (this._cachedDefines !== join) {
  53746. this._cachedDefines = join;
  53747. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  53748. }
  53749. return this._volumetricLightScatteringPass.isReady();
  53750. };
  53751. /**
  53752. * Sets the new light position for light scattering effect
  53753. * @param {BABYLON.Vector3} The new custom light position
  53754. */
  53755. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  53756. this.customMeshPosition = position;
  53757. };
  53758. /**
  53759. * Returns the light position for light scattering effect
  53760. * @return {BABYLON.Vector3} The custom light position
  53761. */
  53762. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  53763. return this.customMeshPosition;
  53764. };
  53765. /**
  53766. * Disposes the internal assets and detaches the post-process from the camera
  53767. */
  53768. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  53769. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  53770. if (rttIndex !== -1) {
  53771. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  53772. }
  53773. this._volumetricLightScatteringRTT.dispose();
  53774. _super.prototype.dispose.call(this, camera);
  53775. };
  53776. /**
  53777. * Returns the render target texture used by the post-process
  53778. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  53779. */
  53780. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  53781. return this._volumetricLightScatteringRTT;
  53782. };
  53783. // Private methods
  53784. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  53785. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  53786. return true;
  53787. }
  53788. return false;
  53789. };
  53790. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  53791. var _this = this;
  53792. var engine = scene.getEngine();
  53793. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53794. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53795. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53796. this._volumetricLightScatteringRTT.renderList = null;
  53797. this._volumetricLightScatteringRTT.renderParticles = false;
  53798. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  53799. // Custom render function for submeshes
  53800. var renderSubMesh = function (subMesh) {
  53801. var mesh = subMesh.getRenderingMesh();
  53802. if (_this._meshExcluded(mesh)) {
  53803. return;
  53804. }
  53805. var scene = mesh.getScene();
  53806. var engine = scene.getEngine();
  53807. // Culling
  53808. engine.setState(subMesh.getMaterial().backFaceCulling);
  53809. // Managing instances
  53810. var batch = mesh._getInstancesRenderList(subMesh._id);
  53811. if (batch.mustReturn) {
  53812. return;
  53813. }
  53814. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  53815. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  53816. var effect = _this._volumetricLightScatteringPass;
  53817. if (mesh === _this.mesh) {
  53818. effect = subMesh.getMaterial().getEffect();
  53819. }
  53820. engine.enableEffect(effect);
  53821. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  53822. if (mesh === _this.mesh) {
  53823. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  53824. }
  53825. else {
  53826. var material = subMesh.getMaterial();
  53827. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  53828. // Alpha test
  53829. if (material && material.needAlphaTesting()) {
  53830. var alphaTexture = material.getAlphaTestTexture();
  53831. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  53832. if (alphaTexture) {
  53833. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  53834. }
  53835. }
  53836. // Bones
  53837. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53838. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  53839. }
  53840. }
  53841. // Draw
  53842. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  53843. }
  53844. };
  53845. // Render target texture callbacks
  53846. var savedSceneClearColor;
  53847. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  53848. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  53849. savedSceneClearColor = scene.clearColor;
  53850. scene.clearColor = sceneClearColor;
  53851. });
  53852. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  53853. scene.clearColor = savedSceneClearColor;
  53854. });
  53855. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  53856. var engine = scene.getEngine();
  53857. var index;
  53858. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53859. renderSubMesh(opaqueSubMeshes.data[index]);
  53860. }
  53861. engine.setAlphaTesting(true);
  53862. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53863. renderSubMesh(alphaTestSubMeshes.data[index]);
  53864. }
  53865. engine.setAlphaTesting(false);
  53866. if (transparentSubMeshes.length) {
  53867. // Sort sub meshes
  53868. for (index = 0; index < transparentSubMeshes.length; index++) {
  53869. var submesh = transparentSubMeshes.data[index];
  53870. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  53871. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  53872. }
  53873. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  53874. sortedArray.sort(function (a, b) {
  53875. // Alpha index first
  53876. if (a._alphaIndex > b._alphaIndex) {
  53877. return 1;
  53878. }
  53879. if (a._alphaIndex < b._alphaIndex) {
  53880. return -1;
  53881. }
  53882. // Then distance to camera
  53883. if (a._distanceToCamera < b._distanceToCamera) {
  53884. return 1;
  53885. }
  53886. if (a._distanceToCamera > b._distanceToCamera) {
  53887. return -1;
  53888. }
  53889. return 0;
  53890. });
  53891. // Render sub meshes
  53892. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53893. for (index = 0; index < sortedArray.length; index++) {
  53894. renderSubMesh(sortedArray[index]);
  53895. }
  53896. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53897. }
  53898. };
  53899. };
  53900. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  53901. var transform = scene.getTransformMatrix();
  53902. var meshPosition;
  53903. if (this.useCustomMeshPosition) {
  53904. meshPosition = this.customMeshPosition;
  53905. }
  53906. else if (this.attachedNode) {
  53907. meshPosition = this.attachedNode.position;
  53908. }
  53909. else {
  53910. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  53911. }
  53912. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  53913. this._screenCoordinates.x = pos.x / this._viewPort.width;
  53914. this._screenCoordinates.y = pos.y / this._viewPort.height;
  53915. if (this.invert)
  53916. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  53917. };
  53918. // Static methods
  53919. /**
  53920. * Creates a default mesh for the Volumeric Light Scattering post-process
  53921. * @param {string} The mesh name
  53922. * @param {BABYLON.Scene} The scene where to create the mesh
  53923. * @return {BABYLON.Mesh} the default mesh
  53924. */
  53925. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  53926. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  53927. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  53928. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  53929. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  53930. mesh.material = material;
  53931. return mesh;
  53932. };
  53933. __decorate([
  53934. BABYLON.serializeAsVector3()
  53935. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  53936. __decorate([
  53937. BABYLON.serialize()
  53938. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  53939. __decorate([
  53940. BABYLON.serialize()
  53941. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  53942. __decorate([
  53943. BABYLON.serializeAsMeshReference()
  53944. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  53945. __decorate([
  53946. BABYLON.serialize()
  53947. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  53948. __decorate([
  53949. BABYLON.serialize()
  53950. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  53951. __decorate([
  53952. BABYLON.serialize()
  53953. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  53954. __decorate([
  53955. BABYLON.serialize()
  53956. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  53957. __decorate([
  53958. BABYLON.serialize()
  53959. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  53960. return VolumetricLightScatteringPostProcess;
  53961. }(BABYLON.PostProcess));
  53962. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  53963. })(BABYLON || (BABYLON = {}));
  53964. // BABYLON.JS Chromatic Aberration GLSL Shader
  53965. // Author: Olivier Guyot
  53966. // Separates very slightly R, G and B colors on the edges of the screen
  53967. // Inspired by Francois Tarlier & Martins Upitis
  53968. var BABYLON;
  53969. (function (BABYLON) {
  53970. var LensRenderingPipeline = (function (_super) {
  53971. __extends(LensRenderingPipeline, _super);
  53972. /**
  53973. * @constructor
  53974. *
  53975. * Effect parameters are as follow:
  53976. * {
  53977. * chromatic_aberration: number; // from 0 to x (1 for realism)
  53978. * edge_blur: number; // from 0 to x (1 for realism)
  53979. * distortion: number; // from 0 to x (1 for realism)
  53980. * grain_amount: number; // from 0 to 1
  53981. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  53982. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  53983. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  53984. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  53985. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  53986. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  53987. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  53988. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  53989. * }
  53990. * Note: if an effect parameter is unset, effect is disabled
  53991. *
  53992. * @param {string} name - The rendering pipeline name
  53993. * @param {object} parameters - An object containing all parameters (see above)
  53994. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53995. * @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)
  53996. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53997. */
  53998. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  53999. var _this = this;
  54000. if (ratio === void 0) { ratio = 1.0; }
  54001. _super.call(this, scene.getEngine(), name);
  54002. // Lens effects can be of the following:
  54003. // - chromatic aberration (slight shift of RGB colors)
  54004. // - blur on the edge of the lens
  54005. // - lens distortion
  54006. // - depth-of-field blur & highlights enhancing
  54007. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  54008. // - grain effect (noise or custom texture)
  54009. // Two additional texture samplers are needed:
  54010. // - depth map (for depth-of-field)
  54011. // - grain texture
  54012. /**
  54013. * The chromatic aberration PostProcess id in the pipeline
  54014. * @type {string}
  54015. */
  54016. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  54017. /**
  54018. * The highlights enhancing PostProcess id in the pipeline
  54019. * @type {string}
  54020. */
  54021. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  54022. /**
  54023. * The depth-of-field PostProcess id in the pipeline
  54024. * @type {string}
  54025. */
  54026. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  54027. this._scene = scene;
  54028. // Fetch texture samplers
  54029. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  54030. if (parameters.grain_texture) {
  54031. this._grainTexture = parameters.grain_texture;
  54032. }
  54033. else {
  54034. this._createGrainTexture();
  54035. }
  54036. // save parameters
  54037. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  54038. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  54039. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  54040. this._distortion = parameters.distortion ? parameters.distortion : 0;
  54041. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  54042. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  54043. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  54044. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  54045. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  54046. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  54047. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  54048. // Create effects
  54049. this._createChromaticAberrationPostProcess(ratio);
  54050. this._createHighlightsPostProcess(ratio);
  54051. this._createDepthOfFieldPostProcess(ratio / 4);
  54052. // Set up pipeline
  54053. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  54054. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  54055. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  54056. if (this._highlightsGain === -1) {
  54057. this._disableEffect(this.HighlightsEnhancingEffect, null);
  54058. }
  54059. // Finish
  54060. scene.postProcessRenderPipelineManager.addPipeline(this);
  54061. if (cameras) {
  54062. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54063. }
  54064. }
  54065. // public methods (self explanatory)
  54066. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  54067. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  54068. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  54069. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  54070. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  54071. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  54072. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  54073. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  54074. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  54075. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  54076. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  54077. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  54078. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  54079. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  54080. };
  54081. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  54082. this._highlightsPostProcess.updateEffect();
  54083. };
  54084. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  54085. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  54086. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  54087. this._highlightsGain = amount;
  54088. };
  54089. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  54090. if (this._highlightsGain === -1) {
  54091. this._highlightsGain = 1.0;
  54092. }
  54093. this._highlightsThreshold = amount;
  54094. };
  54095. LensRenderingPipeline.prototype.disableHighlights = function () {
  54096. this._highlightsGain = -1;
  54097. };
  54098. /**
  54099. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  54100. */
  54101. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  54102. if (disableDepthRender === void 0) { disableDepthRender = false; }
  54103. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54104. this._chromaticAberrationPostProcess = undefined;
  54105. this._highlightsPostProcess = undefined;
  54106. this._depthOfFieldPostProcess = undefined;
  54107. this._grainTexture.dispose();
  54108. if (disableDepthRender)
  54109. this._scene.disableDepthRenderer();
  54110. };
  54111. // colors shifting and distortion
  54112. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  54113. var _this = this;
  54114. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  54115. [], // samplers
  54116. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  54117. this._chromaticAberrationPostProcess.onApply = function (effect) {
  54118. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  54119. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54120. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54121. };
  54122. };
  54123. // highlights enhancing
  54124. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  54125. var _this = this;
  54126. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  54127. [], // samplers
  54128. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  54129. this._highlightsPostProcess.onApply = function (effect) {
  54130. effect.setFloat('gain', _this._highlightsGain);
  54131. effect.setFloat('threshold', _this._highlightsThreshold);
  54132. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  54133. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54134. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54135. };
  54136. };
  54137. // colors shifting and distortion
  54138. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  54139. var _this = this;
  54140. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  54141. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  54142. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  54143. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  54144. this._depthOfFieldPostProcess.onApply = function (effect) {
  54145. effect.setTexture("depthSampler", _this._depthTexture);
  54146. effect.setTexture("grainSampler", _this._grainTexture);
  54147. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  54148. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  54149. effect.setFloat('grain_amount', _this._grainAmount);
  54150. effect.setBool('blur_noise', _this._blurNoise);
  54151. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54152. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54153. effect.setFloat('distortion', _this._distortion);
  54154. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  54155. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  54156. effect.setFloat('aperture', _this._dofAperture);
  54157. effect.setFloat('darken', _this._dofDarken);
  54158. effect.setFloat('edge_blur', _this._edgeBlur);
  54159. effect.setBool('highlights', (_this._highlightsGain !== -1));
  54160. effect.setFloat('near', _this._scene.activeCamera.minZ);
  54161. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  54162. };
  54163. };
  54164. // creates a black and white random noise texture, 512x512
  54165. LensRenderingPipeline.prototype._createGrainTexture = function () {
  54166. var size = 512;
  54167. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  54168. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  54169. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  54170. var context = this._grainTexture.getContext();
  54171. var rand = function (min, max) {
  54172. return Math.random() * (max - min) + min;
  54173. };
  54174. var value;
  54175. for (var x = 0; x < size; x++) {
  54176. for (var y = 0; y < size; y++) {
  54177. value = Math.floor(rand(0.42, 0.58) * 255);
  54178. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  54179. context.fillRect(x, y, 1, 1);
  54180. }
  54181. }
  54182. this._grainTexture.update(false);
  54183. };
  54184. return LensRenderingPipeline;
  54185. }(BABYLON.PostProcessRenderPipeline));
  54186. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  54187. })(BABYLON || (BABYLON = {}));
  54188. //
  54189. // This post-process allows the modification of rendered colors by using
  54190. // a 'look-up table' (LUT). This effect is also called Color Grading.
  54191. //
  54192. // The object needs to be provided an url to a texture containing the color
  54193. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  54194. // Use an image editing software to tweak the LUT to match your needs.
  54195. //
  54196. // For an example of a color LUT, see here:
  54197. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  54198. // For explanations on color grading, see here:
  54199. // http://udn.epicgames.com/Three/ColorGrading.html
  54200. //
  54201. var BABYLON;
  54202. (function (BABYLON) {
  54203. var ColorCorrectionPostProcess = (function (_super) {
  54204. __extends(ColorCorrectionPostProcess, _super);
  54205. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  54206. var _this = this;
  54207. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  54208. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  54209. this._colorTableTexture.anisotropicFilteringLevel = 1;
  54210. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54211. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54212. this.onApply = function (effect) {
  54213. effect.setTexture("colorTable", _this._colorTableTexture);
  54214. };
  54215. }
  54216. return ColorCorrectionPostProcess;
  54217. }(BABYLON.PostProcess));
  54218. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  54219. })(BABYLON || (BABYLON = {}));
  54220. var BABYLON;
  54221. (function (BABYLON) {
  54222. var AnaglyphFreeCamera = (function (_super) {
  54223. __extends(AnaglyphFreeCamera, _super);
  54224. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  54225. _super.call(this, name, position, scene);
  54226. this.interaxialDistance = interaxialDistance;
  54227. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54228. }
  54229. AnaglyphFreeCamera.prototype.getTypeName = function () {
  54230. return "AnaglyphFreeCamera";
  54231. };
  54232. return AnaglyphFreeCamera;
  54233. }(BABYLON.FreeCamera));
  54234. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  54235. var AnaglyphArcRotateCamera = (function (_super) {
  54236. __extends(AnaglyphArcRotateCamera, _super);
  54237. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  54238. _super.call(this, name, alpha, beta, radius, target, scene);
  54239. this.interaxialDistance = interaxialDistance;
  54240. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54241. }
  54242. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  54243. return "AnaglyphArcRotateCamera";
  54244. };
  54245. return AnaglyphArcRotateCamera;
  54246. }(BABYLON.ArcRotateCamera));
  54247. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  54248. var AnaglyphGamepadCamera = (function (_super) {
  54249. __extends(AnaglyphGamepadCamera, _super);
  54250. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  54251. _super.call(this, name, position, scene);
  54252. this.interaxialDistance = interaxialDistance;
  54253. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54254. }
  54255. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  54256. return "AnaglyphGamepadCamera";
  54257. };
  54258. return AnaglyphGamepadCamera;
  54259. }(BABYLON.GamepadCamera));
  54260. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  54261. var AnaglyphUniversalCamera = (function (_super) {
  54262. __extends(AnaglyphUniversalCamera, _super);
  54263. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  54264. _super.call(this, name, position, scene);
  54265. this.interaxialDistance = interaxialDistance;
  54266. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54267. }
  54268. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  54269. return "AnaglyphUniversalCamera";
  54270. };
  54271. return AnaglyphUniversalCamera;
  54272. }(BABYLON.UniversalCamera));
  54273. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  54274. var StereoscopicFreeCamera = (function (_super) {
  54275. __extends(StereoscopicFreeCamera, _super);
  54276. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  54277. _super.call(this, name, position, scene);
  54278. this.interaxialDistance = interaxialDistance;
  54279. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  54280. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  54281. }
  54282. StereoscopicFreeCamera.prototype.getTypeName = function () {
  54283. return "StereoscopicFreeCamera";
  54284. };
  54285. return StereoscopicFreeCamera;
  54286. }(BABYLON.FreeCamera));
  54287. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  54288. var StereoscopicArcRotateCamera = (function (_super) {
  54289. __extends(StereoscopicArcRotateCamera, _super);
  54290. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  54291. _super.call(this, name, alpha, beta, radius, target, scene);
  54292. this.interaxialDistance = interaxialDistance;
  54293. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  54294. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  54295. }
  54296. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  54297. return "StereoscopicArcRotateCamera";
  54298. };
  54299. return StereoscopicArcRotateCamera;
  54300. }(BABYLON.ArcRotateCamera));
  54301. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  54302. var StereoscopicGamepadCamera = (function (_super) {
  54303. __extends(StereoscopicGamepadCamera, _super);
  54304. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  54305. _super.call(this, name, position, scene);
  54306. this.interaxialDistance = interaxialDistance;
  54307. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  54308. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  54309. }
  54310. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  54311. return "StereoscopicGamepadCamera";
  54312. };
  54313. return StereoscopicGamepadCamera;
  54314. }(BABYLON.GamepadCamera));
  54315. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  54316. var StereoscopicUniversalCamera = (function (_super) {
  54317. __extends(StereoscopicUniversalCamera, _super);
  54318. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  54319. _super.call(this, name, position, scene);
  54320. this.interaxialDistance = interaxialDistance;
  54321. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  54322. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  54323. }
  54324. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  54325. return "StereoscopicUniversalCamera";
  54326. };
  54327. return StereoscopicUniversalCamera;
  54328. }(BABYLON.UniversalCamera));
  54329. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  54330. })(BABYLON || (BABYLON = {}));
  54331. var BABYLON;
  54332. (function (BABYLON) {
  54333. var HDRRenderingPipeline = (function (_super) {
  54334. __extends(HDRRenderingPipeline, _super);
  54335. /**
  54336. * @constructor
  54337. * @param {string} name - The rendering pipeline name
  54338. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54339. * @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)
  54340. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  54341. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54342. */
  54343. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  54344. var _this = this;
  54345. if (originalPostProcess === void 0) { originalPostProcess = null; }
  54346. _super.call(this, scene.getEngine(), name);
  54347. /**
  54348. * Public members
  54349. */
  54350. // Gaussian Blur
  54351. /**
  54352. * Gaussian blur coefficient
  54353. * @type {number}
  54354. */
  54355. this.gaussCoeff = 0.3;
  54356. /**
  54357. * Gaussian blur mean
  54358. * @type {number}
  54359. */
  54360. this.gaussMean = 1.0;
  54361. /**
  54362. * Gaussian blur standard deviation
  54363. * @type {number}
  54364. */
  54365. this.gaussStandDev = 0.8;
  54366. /**
  54367. * Gaussian blur multiplier. Multiplies the blur effect
  54368. * @type {number}
  54369. */
  54370. this.gaussMultiplier = 4.0;
  54371. // HDR
  54372. /**
  54373. * Exposure, controls the overall intensity of the pipeline
  54374. * @type {number}
  54375. */
  54376. this.exposure = 1.0;
  54377. /**
  54378. * Minimum luminance that the post-process can output. Luminance is >= 0
  54379. * @type {number}
  54380. */
  54381. this.minimumLuminance = 1.0;
  54382. /**
  54383. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  54384. * @type {number}
  54385. */
  54386. this.maximumLuminance = 1e20;
  54387. /**
  54388. * Increase rate for luminance: eye adaptation speed to dark
  54389. * @type {number}
  54390. */
  54391. this.luminanceIncreaserate = 0.5;
  54392. /**
  54393. * Decrease rate for luminance: eye adaptation speed to bright
  54394. * @type {number}
  54395. */
  54396. this.luminanceDecreaseRate = 0.5;
  54397. // Bright pass
  54398. /**
  54399. * Minimum luminance needed to compute HDR
  54400. * @type {number}
  54401. */
  54402. this.brightThreshold = 0.8;
  54403. this._needUpdate = true;
  54404. this._scene = scene;
  54405. // Bright pass
  54406. this._createBrightPassPostProcess(scene, ratio);
  54407. // Down sample X4
  54408. this._createDownSampleX4PostProcess(scene, ratio);
  54409. // Create gaussian blur post-processes
  54410. this._createGaussianBlurPostProcess(scene, ratio);
  54411. // Texture adder
  54412. this._createTextureAdderPostProcess(scene, ratio);
  54413. // Luminance generator
  54414. this._createLuminanceGeneratorPostProcess(scene);
  54415. // HDR
  54416. this._createHDRPostProcess(scene, ratio);
  54417. // Pass postprocess
  54418. if (originalPostProcess === null) {
  54419. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  54420. }
  54421. else {
  54422. this._originalPostProcess = originalPostProcess;
  54423. }
  54424. // Configure pipeline
  54425. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  54426. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  54427. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  54428. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  54429. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  54430. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  54431. var addDownSamplerPostProcess = function (id) {
  54432. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  54433. };
  54434. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  54435. addDownSamplerPostProcess(i);
  54436. }
  54437. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  54438. // Finish
  54439. scene.postProcessRenderPipelineManager.addPipeline(this);
  54440. if (cameras !== null) {
  54441. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54442. }
  54443. this.update();
  54444. }
  54445. /**
  54446. * Tells the pipeline to update its post-processes
  54447. */
  54448. HDRRenderingPipeline.prototype.update = function () {
  54449. this._needUpdate = true;
  54450. };
  54451. /**
  54452. * Returns the current calculated luminance
  54453. */
  54454. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  54455. return this._hdrCurrentLuminance;
  54456. };
  54457. /**
  54458. * Returns the currently drawn luminance
  54459. */
  54460. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  54461. return this._hdrOutputLuminance;
  54462. };
  54463. /**
  54464. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  54465. */
  54466. HDRRenderingPipeline.prototype.dispose = function () {
  54467. this._originalPostProcess = undefined;
  54468. this._brightPassPostProcess = undefined;
  54469. this._downSampleX4PostProcess = undefined;
  54470. this._guassianBlurHPostProcess = undefined;
  54471. this._guassianBlurVPostProcess = undefined;
  54472. this._textureAdderPostProcess = undefined;
  54473. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  54474. this._downSamplePostProcesses[i] = undefined;
  54475. }
  54476. this._hdrPostProcess = undefined;
  54477. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54478. };
  54479. /**
  54480. * Creates the HDR post-process and computes the luminance adaptation
  54481. */
  54482. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  54483. var _this = this;
  54484. var hdrLastLuminance = 0.0;
  54485. this._hdrOutputLuminance = -1.0;
  54486. this._hdrCurrentLuminance = 1.0;
  54487. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  54488. this._hdrPostProcess.onApply = function (effect) {
  54489. if (_this._hdrOutputLuminance < 0.0) {
  54490. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  54491. }
  54492. else {
  54493. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  54494. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  54495. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  54496. }
  54497. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  54498. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  54499. }
  54500. else {
  54501. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  54502. }
  54503. }
  54504. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  54505. hdrLastLuminance += scene.getEngine().getDeltaTime();
  54506. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  54507. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  54508. effect.setFloat("exposure", _this.exposure);
  54509. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  54510. _this._needUpdate = false;
  54511. };
  54512. };
  54513. /**
  54514. * Texture Adder post-process
  54515. */
  54516. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  54517. var _this = this;
  54518. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  54519. this._textureAdderPostProcess.onApply = function (effect) {
  54520. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  54521. };
  54522. };
  54523. /**
  54524. * Down sample X4 post-process
  54525. */
  54526. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  54527. var _this = this;
  54528. var downSampleX4Offsets = new Array(32);
  54529. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  54530. this._downSampleX4PostProcess.onApply = function (effect) {
  54531. if (_this._needUpdate) {
  54532. var id = 0;
  54533. for (var i = -2; i < 2; i++) {
  54534. for (var j = -2; j < 2; j++) {
  54535. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  54536. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  54537. id += 2;
  54538. }
  54539. }
  54540. }
  54541. effect.setArray2("dsOffsets", downSampleX4Offsets);
  54542. };
  54543. };
  54544. /**
  54545. * Bright pass post-process
  54546. */
  54547. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  54548. var _this = this;
  54549. var brightOffsets = new Array(8);
  54550. var brightPassCallback = function (effect) {
  54551. if (_this._needUpdate) {
  54552. var sU = (1.0 / _this._brightPassPostProcess.width);
  54553. var sV = (1.0 / _this._brightPassPostProcess.height);
  54554. brightOffsets[0] = -0.5 * sU;
  54555. brightOffsets[1] = 0.5 * sV;
  54556. brightOffsets[2] = 0.5 * sU;
  54557. brightOffsets[3] = 0.5 * sV;
  54558. brightOffsets[4] = -0.5 * sU;
  54559. brightOffsets[5] = -0.5 * sV;
  54560. brightOffsets[6] = 0.5 * sU;
  54561. brightOffsets[7] = -0.5 * sV;
  54562. }
  54563. effect.setArray2("dsOffsets", brightOffsets);
  54564. effect.setFloat("brightThreshold", _this.brightThreshold);
  54565. };
  54566. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  54567. this._brightPassPostProcess.onApply = brightPassCallback;
  54568. };
  54569. /**
  54570. * Luminance generator. Creates the luminance post-process and down sample post-processes
  54571. */
  54572. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  54573. var _this = this;
  54574. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  54575. var luminanceOffsets = new Array(8);
  54576. var downSampleOffsets = new Array(18);
  54577. var halfDestPixelSize;
  54578. this._downSamplePostProcesses = new Array(lumSteps);
  54579. // Utils for luminance
  54580. var luminanceUpdateSourceOffsets = function (width, height) {
  54581. var sU = (1.0 / width);
  54582. var sV = (1.0 / height);
  54583. luminanceOffsets[0] = -0.5 * sU;
  54584. luminanceOffsets[1] = 0.5 * sV;
  54585. luminanceOffsets[2] = 0.5 * sU;
  54586. luminanceOffsets[3] = 0.5 * sV;
  54587. luminanceOffsets[4] = -0.5 * sU;
  54588. luminanceOffsets[5] = -0.5 * sV;
  54589. luminanceOffsets[6] = 0.5 * sU;
  54590. luminanceOffsets[7] = -0.5 * sV;
  54591. };
  54592. var luminanceUpdateDestOffsets = function (width, height) {
  54593. var id = 0;
  54594. for (var x = -1; x < 2; x++) {
  54595. for (var y = -1; y < 2; y++) {
  54596. downSampleOffsets[id] = (x) / width;
  54597. downSampleOffsets[id + 1] = (y) / height;
  54598. id += 2;
  54599. }
  54600. }
  54601. };
  54602. // Luminance callback
  54603. var luminanceCallback = function (effect) {
  54604. if (_this._needUpdate) {
  54605. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  54606. }
  54607. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  54608. effect.setArray2("lumOffsets", luminanceOffsets);
  54609. };
  54610. // Down sample callbacks
  54611. var downSampleCallback = function (indice) {
  54612. var i = indice;
  54613. return function (effect) {
  54614. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  54615. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  54616. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  54617. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  54618. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  54619. effect.setArray2("dsOffsets", downSampleOffsets);
  54620. };
  54621. };
  54622. var downSampleAfterRenderCallback = function (effect) {
  54623. // Unpack result
  54624. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  54625. 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);
  54626. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  54627. };
  54628. // Create luminance post-process
  54629. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  54630. 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);
  54631. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  54632. // Create down sample post-processes
  54633. for (var i = lumSteps - 2; i >= 0; i--) {
  54634. var length = Math.pow(3, i);
  54635. ratio = { width: length, height: length };
  54636. var defines = "#define DOWN_SAMPLE\n";
  54637. if (i === 0) {
  54638. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  54639. }
  54640. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  54641. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  54642. if (i === 0) {
  54643. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  54644. }
  54645. }
  54646. };
  54647. /**
  54648. * Gaussian blur post-processes. Horizontal and Vertical
  54649. */
  54650. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  54651. var _this = this;
  54652. var blurOffsetsW = new Array(9);
  54653. var blurOffsetsH = new Array(9);
  54654. var blurWeights = new Array(9);
  54655. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  54656. // Utils for gaussian blur
  54657. var calculateBlurOffsets = function (height) {
  54658. var lastOutputDimensions = {
  54659. width: scene.getEngine().getRenderWidth(),
  54660. height: scene.getEngine().getRenderHeight()
  54661. };
  54662. for (var i = 0; i < 9; i++) {
  54663. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  54664. if (height) {
  54665. blurOffsetsH[i] = value;
  54666. }
  54667. else {
  54668. blurOffsetsW[i] = value;
  54669. }
  54670. }
  54671. };
  54672. var calculateWeights = function () {
  54673. var x = 0.0;
  54674. for (var i = 0; i < 9; i++) {
  54675. x = (i - 4.0) / 4.0;
  54676. 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));
  54677. }
  54678. };
  54679. // Callback
  54680. var gaussianBlurCallback = function (height) {
  54681. return function (effect) {
  54682. if (_this._needUpdate) {
  54683. calculateWeights();
  54684. calculateBlurOffsets(height);
  54685. }
  54686. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  54687. effect.setArray("blurWeights", blurWeights);
  54688. effect.setFloat("multiplier", _this.gaussMultiplier);
  54689. };
  54690. };
  54691. // Create horizontal gaussian blur post-processes
  54692. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  54693. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  54694. // Create vertical gaussian blur post-process
  54695. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  54696. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  54697. };
  54698. // Luminance generator
  54699. HDRRenderingPipeline.LUM_STEPS = 6;
  54700. return HDRRenderingPipeline;
  54701. }(BABYLON.PostProcessRenderPipeline));
  54702. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  54703. })(BABYLON || (BABYLON = {}));
  54704. var BABYLON;
  54705. (function (BABYLON) {
  54706. var FaceAdjacencies = (function () {
  54707. function FaceAdjacencies() {
  54708. this.edges = new Array();
  54709. this.edgesConnectedCount = 0;
  54710. }
  54711. return FaceAdjacencies;
  54712. }());
  54713. var EdgesRenderer = (function () {
  54714. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  54715. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  54716. if (epsilon === void 0) { epsilon = 0.95; }
  54717. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  54718. this.edgesWidthScalerForOrthographic = 1000.0;
  54719. this.edgesWidthScalerForPerspective = 50.0;
  54720. this._linesPositions = new Array();
  54721. this._linesNormals = new Array();
  54722. this._linesIndices = new Array();
  54723. this._buffers = {};
  54724. this._checkVerticesInsteadOfIndices = false;
  54725. this._source = source;
  54726. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  54727. this._epsilon = epsilon;
  54728. this._prepareRessources();
  54729. this._generateEdgesLines();
  54730. }
  54731. EdgesRenderer.prototype._prepareRessources = function () {
  54732. if (this._lineShader) {
  54733. return;
  54734. }
  54735. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  54736. attributes: ["position", "normal"],
  54737. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  54738. });
  54739. this._lineShader.disableDepthWrite = true;
  54740. this._lineShader.backFaceCulling = false;
  54741. };
  54742. EdgesRenderer.prototype.dispose = function () {
  54743. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  54744. if (buffer) {
  54745. buffer.dispose();
  54746. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  54747. }
  54748. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  54749. if (buffer) {
  54750. buffer.dispose();
  54751. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  54752. }
  54753. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  54754. this._lineShader.dispose();
  54755. };
  54756. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  54757. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  54758. return 0;
  54759. }
  54760. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  54761. return 1;
  54762. }
  54763. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  54764. return 2;
  54765. }
  54766. return -1;
  54767. };
  54768. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  54769. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  54770. return 0;
  54771. }
  54772. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  54773. return 1;
  54774. }
  54775. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  54776. return 2;
  54777. }
  54778. return -1;
  54779. };
  54780. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  54781. var needToCreateLine;
  54782. if (edge === undefined) {
  54783. needToCreateLine = true;
  54784. }
  54785. else {
  54786. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  54787. needToCreateLine = dotProduct < this._epsilon;
  54788. }
  54789. if (needToCreateLine) {
  54790. var offset = this._linesPositions.length / 3;
  54791. var normal = p0.subtract(p1);
  54792. normal.normalize();
  54793. // Positions
  54794. this._linesPositions.push(p0.x);
  54795. this._linesPositions.push(p0.y);
  54796. this._linesPositions.push(p0.z);
  54797. this._linesPositions.push(p0.x);
  54798. this._linesPositions.push(p0.y);
  54799. this._linesPositions.push(p0.z);
  54800. this._linesPositions.push(p1.x);
  54801. this._linesPositions.push(p1.y);
  54802. this._linesPositions.push(p1.z);
  54803. this._linesPositions.push(p1.x);
  54804. this._linesPositions.push(p1.y);
  54805. this._linesPositions.push(p1.z);
  54806. // Normals
  54807. this._linesNormals.push(p1.x);
  54808. this._linesNormals.push(p1.y);
  54809. this._linesNormals.push(p1.z);
  54810. this._linesNormals.push(-1);
  54811. this._linesNormals.push(p1.x);
  54812. this._linesNormals.push(p1.y);
  54813. this._linesNormals.push(p1.z);
  54814. this._linesNormals.push(1);
  54815. this._linesNormals.push(p0.x);
  54816. this._linesNormals.push(p0.y);
  54817. this._linesNormals.push(p0.z);
  54818. this._linesNormals.push(-1);
  54819. this._linesNormals.push(p0.x);
  54820. this._linesNormals.push(p0.y);
  54821. this._linesNormals.push(p0.z);
  54822. this._linesNormals.push(1);
  54823. // Indices
  54824. this._linesIndices.push(offset);
  54825. this._linesIndices.push(offset + 1);
  54826. this._linesIndices.push(offset + 2);
  54827. this._linesIndices.push(offset);
  54828. this._linesIndices.push(offset + 2);
  54829. this._linesIndices.push(offset + 3);
  54830. }
  54831. };
  54832. EdgesRenderer.prototype._generateEdgesLines = function () {
  54833. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54834. var indices = this._source.getIndices();
  54835. // First let's find adjacencies
  54836. var adjacencies = new Array();
  54837. var faceNormals = new Array();
  54838. var index;
  54839. var faceAdjacencies;
  54840. // Prepare faces
  54841. for (index = 0; index < indices.length; index += 3) {
  54842. faceAdjacencies = new FaceAdjacencies();
  54843. var p0Index = indices[index];
  54844. var p1Index = indices[index + 1];
  54845. var p2Index = indices[index + 2];
  54846. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  54847. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  54848. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  54849. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  54850. faceNormal.normalize();
  54851. faceNormals.push(faceNormal);
  54852. adjacencies.push(faceAdjacencies);
  54853. }
  54854. // Scan
  54855. for (index = 0; index < adjacencies.length; index++) {
  54856. faceAdjacencies = adjacencies[index];
  54857. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  54858. var otherFaceAdjacencies = adjacencies[otherIndex];
  54859. if (faceAdjacencies.edgesConnectedCount === 3) {
  54860. break;
  54861. }
  54862. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  54863. continue;
  54864. }
  54865. var otherP0 = indices[otherIndex * 3];
  54866. var otherP1 = indices[otherIndex * 3 + 1];
  54867. var otherP2 = indices[otherIndex * 3 + 2];
  54868. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  54869. var otherEdgeIndex;
  54870. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  54871. continue;
  54872. }
  54873. switch (edgeIndex) {
  54874. case 0:
  54875. if (this._checkVerticesInsteadOfIndices) {
  54876. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  54877. }
  54878. else {
  54879. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  54880. }
  54881. break;
  54882. case 1:
  54883. if (this._checkVerticesInsteadOfIndices) {
  54884. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  54885. }
  54886. else {
  54887. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  54888. }
  54889. break;
  54890. case 2:
  54891. if (this._checkVerticesInsteadOfIndices) {
  54892. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  54893. }
  54894. else {
  54895. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  54896. }
  54897. break;
  54898. }
  54899. if (otherEdgeIndex === -1) {
  54900. continue;
  54901. }
  54902. faceAdjacencies.edges[edgeIndex] = otherIndex;
  54903. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  54904. faceAdjacencies.edgesConnectedCount++;
  54905. otherFaceAdjacencies.edgesConnectedCount++;
  54906. if (faceAdjacencies.edgesConnectedCount === 3) {
  54907. break;
  54908. }
  54909. }
  54910. }
  54911. }
  54912. // Create lines
  54913. for (index = 0; index < adjacencies.length; index++) {
  54914. // 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
  54915. var current = adjacencies[index];
  54916. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  54917. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  54918. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  54919. }
  54920. // Merge into a single mesh
  54921. var engine = this._source.getScene().getEngine();
  54922. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  54923. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  54924. this._ib = engine.createIndexBuffer(this._linesIndices);
  54925. this._indicesCount = this._linesIndices.length;
  54926. };
  54927. EdgesRenderer.prototype.render = function () {
  54928. if (!this._lineShader.isReady()) {
  54929. return;
  54930. }
  54931. var scene = this._source.getScene();
  54932. var engine = scene.getEngine();
  54933. this._lineShader._preBind();
  54934. // VBOs
  54935. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  54936. scene.resetCachedMaterial();
  54937. this._lineShader.setColor4("color", this._source.edgesColor);
  54938. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  54939. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  54940. }
  54941. else {
  54942. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  54943. }
  54944. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  54945. this._lineShader.bind(this._source.getWorldMatrix());
  54946. // Draw order
  54947. engine.draw(true, 0, this._indicesCount);
  54948. this._lineShader.unbind();
  54949. engine.setDepthWrite(true);
  54950. };
  54951. return EdgesRenderer;
  54952. }());
  54953. BABYLON.EdgesRenderer = EdgesRenderer;
  54954. })(BABYLON || (BABYLON = {}));
  54955. var BABYLON;
  54956. (function (BABYLON) {
  54957. (function (TonemappingOperator) {
  54958. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  54959. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  54960. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  54961. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  54962. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  54963. var TonemappingOperator = BABYLON.TonemappingOperator;
  54964. ;
  54965. var TonemapPostProcess = (function (_super) {
  54966. __extends(TonemapPostProcess, _super);
  54967. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  54968. var _this = this;
  54969. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  54970. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54971. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  54972. this._operator = _operator;
  54973. this.exposureAdjustment = exposureAdjustment;
  54974. var defines = "#define ";
  54975. if (this._operator === TonemappingOperator.Hable)
  54976. defines += "HABLE_TONEMAPPING";
  54977. else if (this._operator === TonemappingOperator.Reinhard)
  54978. defines += "REINHARD_TONEMAPPING";
  54979. else if (this._operator === TonemappingOperator.HejiDawson)
  54980. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  54981. else if (this._operator === TonemappingOperator.Photographic)
  54982. defines += "PHOTOGRAPHIC_TONEMAPPING";
  54983. //sadly a second call to create the effect.
  54984. this.updateEffect(defines);
  54985. this.onApply = function (effect) {
  54986. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  54987. };
  54988. }
  54989. return TonemapPostProcess;
  54990. }(BABYLON.PostProcess));
  54991. BABYLON.TonemapPostProcess = TonemapPostProcess;
  54992. })(BABYLON || (BABYLON = {}));
  54993. var BABYLON;
  54994. (function (BABYLON) {
  54995. var ReflectionProbe = (function () {
  54996. function ReflectionProbe(name, size, scene, generateMipMaps) {
  54997. var _this = this;
  54998. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54999. this.name = name;
  55000. this._viewMatrix = BABYLON.Matrix.Identity();
  55001. this._target = BABYLON.Vector3.Zero();
  55002. this._add = BABYLON.Vector3.Zero();
  55003. this.invertYAxis = false;
  55004. this.position = BABYLON.Vector3.Zero();
  55005. this._scene = scene;
  55006. this._scene.reflectionProbes.push(this);
  55007. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  55008. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  55009. switch (faceIndex) {
  55010. case 0:
  55011. _this._add.copyFromFloats(1, 0, 0);
  55012. break;
  55013. case 1:
  55014. _this._add.copyFromFloats(-1, 0, 0);
  55015. break;
  55016. case 2:
  55017. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  55018. break;
  55019. case 3:
  55020. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  55021. break;
  55022. case 4:
  55023. _this._add.copyFromFloats(0, 0, 1);
  55024. break;
  55025. case 5:
  55026. _this._add.copyFromFloats(0, 0, -1);
  55027. break;
  55028. }
  55029. if (_this._attachedMesh) {
  55030. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  55031. }
  55032. _this.position.addToRef(_this._add, _this._target);
  55033. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  55034. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  55035. });
  55036. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  55037. scene.updateTransformMatrix(true);
  55038. });
  55039. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  55040. }
  55041. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  55042. get: function () {
  55043. return this._renderTargetTexture.refreshRate;
  55044. },
  55045. set: function (value) {
  55046. this._renderTargetTexture.refreshRate = value;
  55047. },
  55048. enumerable: true,
  55049. configurable: true
  55050. });
  55051. ReflectionProbe.prototype.getScene = function () {
  55052. return this._scene;
  55053. };
  55054. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  55055. get: function () {
  55056. return this._renderTargetTexture;
  55057. },
  55058. enumerable: true,
  55059. configurable: true
  55060. });
  55061. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  55062. get: function () {
  55063. return this._renderTargetTexture.renderList;
  55064. },
  55065. enumerable: true,
  55066. configurable: true
  55067. });
  55068. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  55069. this._attachedMesh = mesh;
  55070. };
  55071. ReflectionProbe.prototype.dispose = function () {
  55072. var index = this._scene.reflectionProbes.indexOf(this);
  55073. if (index !== -1) {
  55074. // Remove from the scene if found
  55075. this._scene.reflectionProbes.splice(index, 1);
  55076. }
  55077. if (this._renderTargetTexture) {
  55078. this._renderTargetTexture.dispose();
  55079. this._renderTargetTexture = null;
  55080. }
  55081. };
  55082. return ReflectionProbe;
  55083. }());
  55084. BABYLON.ReflectionProbe = ReflectionProbe;
  55085. })(BABYLON || (BABYLON = {}));
  55086. var BABYLON;
  55087. (function (BABYLON) {
  55088. var SolidParticle = (function () {
  55089. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  55090. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  55091. this.position = BABYLON.Vector3.Zero(); // position
  55092. this.rotation = BABYLON.Vector3.Zero(); // rotation
  55093. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  55094. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  55095. this.velocity = BABYLON.Vector3.Zero(); // velocity
  55096. this.alive = true; // alive
  55097. this.isVisible = true; // visibility
  55098. this.idx = particleIndex;
  55099. this._pos = positionIndex;
  55100. this._model = model;
  55101. this.shapeId = shapeId;
  55102. this.idxInShape = idxInShape;
  55103. }
  55104. Object.defineProperty(SolidParticle.prototype, "scale", {
  55105. //legacy support, changed scale to scaling
  55106. get: function () {
  55107. return this.scaling;
  55108. },
  55109. set: function (scale) {
  55110. this.scaling = scale;
  55111. },
  55112. enumerable: true,
  55113. configurable: true
  55114. });
  55115. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  55116. //legacy support, changed quaternion to rotationQuaternion
  55117. get: function () {
  55118. return this.rotationQuaternion;
  55119. },
  55120. set: function (q) {
  55121. this.rotationQuaternion = q;
  55122. },
  55123. enumerable: true,
  55124. configurable: true
  55125. });
  55126. return SolidParticle;
  55127. }());
  55128. BABYLON.SolidParticle = SolidParticle;
  55129. var ModelShape = (function () {
  55130. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  55131. this.shapeID = id;
  55132. this._shape = shape;
  55133. this._shapeUV = shapeUV;
  55134. this._positionFunction = posFunction;
  55135. this._vertexFunction = vtxFunction;
  55136. }
  55137. return ModelShape;
  55138. }());
  55139. BABYLON.ModelShape = ModelShape;
  55140. })(BABYLON || (BABYLON = {}));
  55141. var BABYLON;
  55142. (function (BABYLON) {
  55143. /**
  55144. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  55145. */
  55146. var SolidParticleSystem = (function () {
  55147. /**
  55148. * Creates a SPS (Solid Particle System) object.
  55149. * `name` (String) is the SPS name, this will be the underlying mesh name.
  55150. * `scene` (Scene) is the scene in which the SPS is added.
  55151. * `updatable` (default true) : if the SPS must be updatable or immutable.
  55152. * `isPickable` (default false) : if the solid particles must be pickable.
  55153. */
  55154. function SolidParticleSystem(name, scene, options) {
  55155. // public members
  55156. /**
  55157. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  55158. * Example : var p = SPS.particles[i];
  55159. */
  55160. this.particles = new Array();
  55161. /**
  55162. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  55163. */
  55164. this.nbParticles = 0;
  55165. /**
  55166. * If the particles must ever face the camera (default false). Useful for planar particles.
  55167. */
  55168. this.billboard = false;
  55169. /**
  55170. * This a counter ofr your own usage. It's not set by any SPS functions.
  55171. */
  55172. this.counter = 0;
  55173. /**
  55174. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  55175. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  55176. */
  55177. this.vars = {};
  55178. this._positions = new Array();
  55179. this._indices = new Array();
  55180. this._normals = new Array();
  55181. this._colors = new Array();
  55182. this._uvs = new Array();
  55183. this._index = 0; // indices index
  55184. this._updatable = true;
  55185. this._pickable = false;
  55186. this._isVisibilityBoxLocked = false;
  55187. this._alwaysVisible = false;
  55188. this._shapeCounter = 0;
  55189. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  55190. this._color = new BABYLON.Color4(0, 0, 0, 0);
  55191. this._computeParticleColor = true;
  55192. this._computeParticleTexture = true;
  55193. this._computeParticleRotation = true;
  55194. this._computeParticleVertex = false;
  55195. this._computeBoundingBox = false;
  55196. this._cam_axisZ = BABYLON.Vector3.Zero();
  55197. this._cam_axisY = BABYLON.Vector3.Zero();
  55198. this._cam_axisX = BABYLON.Vector3.Zero();
  55199. this._axisX = BABYLON.Axis.X;
  55200. this._axisY = BABYLON.Axis.Y;
  55201. this._axisZ = BABYLON.Axis.Z;
  55202. this._fakeCamPos = BABYLON.Vector3.Zero();
  55203. this._rotMatrix = new BABYLON.Matrix();
  55204. this._invertMatrix = new BABYLON.Matrix();
  55205. this._rotated = BABYLON.Vector3.Zero();
  55206. this._quaternion = new BABYLON.Quaternion();
  55207. this._vertex = BABYLON.Vector3.Zero();
  55208. this._normal = BABYLON.Vector3.Zero();
  55209. this._yaw = 0.0;
  55210. this._pitch = 0.0;
  55211. this._roll = 0.0;
  55212. this._halfroll = 0.0;
  55213. this._halfpitch = 0.0;
  55214. this._halfyaw = 0.0;
  55215. this._sinRoll = 0.0;
  55216. this._cosRoll = 0.0;
  55217. this._sinPitch = 0.0;
  55218. this._cosPitch = 0.0;
  55219. this._sinYaw = 0.0;
  55220. this._cosYaw = 0.0;
  55221. this._w = 0.0;
  55222. this._minimum = BABYLON.Tmp.Vector3[0];
  55223. this._maximum = BABYLON.Tmp.Vector3[1];
  55224. this.name = name;
  55225. this._scene = scene;
  55226. this._camera = scene.activeCamera;
  55227. this._pickable = options ? options.isPickable : false;
  55228. if (options && options.updatable) {
  55229. this._updatable = options.updatable;
  55230. }
  55231. else {
  55232. this._updatable = true;
  55233. }
  55234. if (this._pickable) {
  55235. this.pickedParticles = [];
  55236. }
  55237. }
  55238. /**
  55239. * Builds the SPS underlying mesh. Returns a standard Mesh.
  55240. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  55241. */
  55242. SolidParticleSystem.prototype.buildMesh = function () {
  55243. if (this.nbParticles === 0) {
  55244. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  55245. this.addShape(triangle, 1);
  55246. triangle.dispose();
  55247. }
  55248. this._positions32 = new Float32Array(this._positions);
  55249. this._uvs32 = new Float32Array(this._uvs);
  55250. this._colors32 = new Float32Array(this._colors);
  55251. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  55252. this._normals32 = new Float32Array(this._normals);
  55253. this._fixedNormal32 = new Float32Array(this._normals);
  55254. var vertexData = new BABYLON.VertexData();
  55255. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  55256. vertexData.indices = this._indices;
  55257. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  55258. if (this._uvs32) {
  55259. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  55260. ;
  55261. }
  55262. if (this._colors32) {
  55263. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  55264. }
  55265. var mesh = new BABYLON.Mesh(this.name, this._scene);
  55266. vertexData.applyToMesh(mesh, this._updatable);
  55267. this.mesh = mesh;
  55268. this.mesh.isPickable = this._pickable;
  55269. // free memory
  55270. this._positions = null;
  55271. this._normals = null;
  55272. this._uvs = null;
  55273. this._colors = null;
  55274. if (!this._updatable) {
  55275. this.particles.length = 0;
  55276. }
  55277. return mesh;
  55278. };
  55279. /**
  55280. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  55281. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  55282. * Thus the particles generated from `digest()` have their property `position` set yet.
  55283. * `mesh` ( Mesh ) is the mesh to be digested
  55284. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  55285. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  55286. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  55287. */
  55288. SolidParticleSystem.prototype.digest = function (mesh, options) {
  55289. var size = (options && options.facetNb) || 1;
  55290. var number = (options && options.number);
  55291. var delta = (options && options.delta) || 0;
  55292. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55293. var meshInd = mesh.getIndices();
  55294. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55295. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55296. var f = 0; // facet counter
  55297. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  55298. // compute size from number
  55299. if (number) {
  55300. number = (number > totalFacets) ? totalFacets : number;
  55301. size = Math.round(totalFacets / number);
  55302. delta = 0;
  55303. }
  55304. else {
  55305. size = (size > totalFacets) ? totalFacets : size;
  55306. }
  55307. var facetPos = []; // submesh positions
  55308. var facetInd = []; // submesh indices
  55309. var facetUV = []; // submesh UV
  55310. var facetCol = []; // submesh colors
  55311. var barycenter = BABYLON.Tmp.Vector3[0];
  55312. var rand;
  55313. var sizeO = size;
  55314. while (f < totalFacets) {
  55315. size = sizeO + Math.floor((1 + delta) * Math.random());
  55316. if (f > totalFacets - size) {
  55317. size = totalFacets - f;
  55318. }
  55319. // reset temp arrays
  55320. facetPos.length = 0;
  55321. facetInd.length = 0;
  55322. facetUV.length = 0;
  55323. facetCol.length = 0;
  55324. // iterate over "size" facets
  55325. var fi = 0;
  55326. for (var j = f * 3; j < (f + size) * 3; j++) {
  55327. facetInd.push(fi);
  55328. var i = meshInd[j];
  55329. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  55330. if (meshUV) {
  55331. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  55332. }
  55333. if (meshCol) {
  55334. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  55335. }
  55336. fi++;
  55337. }
  55338. // create a model shape for each single particle
  55339. var idx = this.nbParticles;
  55340. var shape = this._posToShape(facetPos);
  55341. var shapeUV = this._uvsToShapeUV(facetUV);
  55342. // compute the barycenter of the shape
  55343. var v;
  55344. for (v = 0; v < shape.length; v++) {
  55345. barycenter.addInPlace(shape[v]);
  55346. }
  55347. barycenter.scaleInPlace(1 / shape.length);
  55348. // shift the shape from its barycenter to the origin
  55349. for (v = 0; v < shape.length; v++) {
  55350. shape[v].subtractInPlace(barycenter);
  55351. }
  55352. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  55353. // add the particle in the SPS
  55354. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  55355. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  55356. // initialize the particle position
  55357. this.particles[this.nbParticles].position.addInPlace(barycenter);
  55358. this._index += shape.length;
  55359. idx++;
  55360. this.nbParticles++;
  55361. this._shapeCounter++;
  55362. f += size;
  55363. }
  55364. return this;
  55365. };
  55366. //reset copy
  55367. SolidParticleSystem.prototype._resetCopy = function () {
  55368. this._copy.position.x = 0;
  55369. this._copy.position.y = 0;
  55370. this._copy.position.z = 0;
  55371. this._copy.rotation.x = 0;
  55372. this._copy.rotation.y = 0;
  55373. this._copy.rotation.z = 0;
  55374. this._copy.rotationQuaternion = null;
  55375. this._copy.scaling.x = 1;
  55376. this._copy.scaling.y = 1;
  55377. this._copy.scaling.z = 1;
  55378. this._copy.uvs.x = 0;
  55379. this._copy.uvs.y = 0;
  55380. this._copy.uvs.z = 1;
  55381. this._copy.uvs.w = 1;
  55382. this._copy.color = null;
  55383. };
  55384. // _meshBuilder : inserts the shape model in the global SPS mesh
  55385. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  55386. var i;
  55387. var u = 0;
  55388. var c = 0;
  55389. this._resetCopy();
  55390. if (options && options.positionFunction) {
  55391. options.positionFunction(this._copy, idx, idxInShape);
  55392. }
  55393. if (this._copy.rotationQuaternion) {
  55394. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  55395. }
  55396. else {
  55397. this._yaw = this._copy.rotation.y;
  55398. this._pitch = this._copy.rotation.x;
  55399. this._roll = this._copy.rotation.z;
  55400. this._quaternionRotationYPR();
  55401. }
  55402. this._quaternionToRotationMatrix();
  55403. for (i = 0; i < shape.length; i++) {
  55404. this._vertex.x = shape[i].x;
  55405. this._vertex.y = shape[i].y;
  55406. this._vertex.z = shape[i].z;
  55407. if (options && options.vertexFunction) {
  55408. options.vertexFunction(this._copy, this._vertex, i);
  55409. }
  55410. this._vertex.x *= this._copy.scaling.x;
  55411. this._vertex.y *= this._copy.scaling.y;
  55412. this._vertex.z *= this._copy.scaling.z;
  55413. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  55414. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  55415. if (meshUV) {
  55416. 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);
  55417. u += 2;
  55418. }
  55419. if (this._copy.color) {
  55420. this._color = this._copy.color;
  55421. }
  55422. else if (meshCol && meshCol[c] !== undefined) {
  55423. this._color.r = meshCol[c];
  55424. this._color.g = meshCol[c + 1];
  55425. this._color.b = meshCol[c + 2];
  55426. this._color.a = meshCol[c + 3];
  55427. }
  55428. else {
  55429. this._color.r = 1;
  55430. this._color.g = 1;
  55431. this._color.b = 1;
  55432. this._color.a = 1;
  55433. }
  55434. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  55435. c += 4;
  55436. }
  55437. for (i = 0; i < meshInd.length; i++) {
  55438. indices.push(p + meshInd[i]);
  55439. }
  55440. if (this._pickable) {
  55441. var nbfaces = meshInd.length / 3;
  55442. for (i = 0; i < nbfaces; i++) {
  55443. this.pickedParticles.push({ idx: idx, faceId: i });
  55444. }
  55445. }
  55446. };
  55447. // returns a shape array from positions array
  55448. SolidParticleSystem.prototype._posToShape = function (positions) {
  55449. var shape = [];
  55450. for (var i = 0; i < positions.length; i += 3) {
  55451. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  55452. }
  55453. return shape;
  55454. };
  55455. // returns a shapeUV array from a Vector4 uvs
  55456. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  55457. var shapeUV = [];
  55458. if (uvs) {
  55459. for (var i = 0; i < uvs.length; i++)
  55460. shapeUV.push(uvs[i]);
  55461. }
  55462. return shapeUV;
  55463. };
  55464. // adds a new particle object in the particles array
  55465. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  55466. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  55467. };
  55468. /**
  55469. * Adds some particles to the SPS from the model shape. Returns the shape id.
  55470. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  55471. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  55472. * `nb` (positive integer) the number of particles to be created from this model
  55473. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  55474. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  55475. */
  55476. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  55477. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55478. var meshInd = mesh.getIndices();
  55479. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55480. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55481. var shape = this._posToShape(meshPos);
  55482. var shapeUV = this._uvsToShapeUV(meshUV);
  55483. var posfunc = options ? options.positionFunction : null;
  55484. var vtxfunc = options ? options.vertexFunction : null;
  55485. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  55486. // particles
  55487. var idx = this.nbParticles;
  55488. for (var i = 0; i < nb; i++) {
  55489. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  55490. if (this._updatable) {
  55491. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  55492. }
  55493. this._index += shape.length;
  55494. idx++;
  55495. }
  55496. this.nbParticles += nb;
  55497. this._shapeCounter++;
  55498. return this._shapeCounter - 1;
  55499. };
  55500. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  55501. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  55502. this._resetCopy();
  55503. if (particle._model._positionFunction) {
  55504. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  55505. }
  55506. if (this._copy.rotationQuaternion) {
  55507. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  55508. }
  55509. else {
  55510. this._yaw = this._copy.rotation.y;
  55511. this._pitch = this._copy.rotation.x;
  55512. this._roll = this._copy.rotation.z;
  55513. this._quaternionRotationYPR();
  55514. }
  55515. this._quaternionToRotationMatrix();
  55516. this._shape = particle._model._shape;
  55517. for (var pt = 0; pt < this._shape.length; pt++) {
  55518. this._vertex.x = this._shape[pt].x;
  55519. this._vertex.y = this._shape[pt].y;
  55520. this._vertex.z = this._shape[pt].z;
  55521. if (particle._model._vertexFunction) {
  55522. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  55523. }
  55524. this._vertex.x *= this._copy.scaling.x;
  55525. this._vertex.y *= this._copy.scaling.y;
  55526. this._vertex.z *= this._copy.scaling.z;
  55527. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  55528. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  55529. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  55530. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  55531. }
  55532. particle.position.x = 0;
  55533. particle.position.y = 0;
  55534. particle.position.z = 0;
  55535. particle.rotation.x = 0;
  55536. particle.rotation.y = 0;
  55537. particle.rotation.z = 0;
  55538. particle.rotationQuaternion = null;
  55539. particle.scaling.x = 1;
  55540. particle.scaling.y = 1;
  55541. particle.scaling.z = 1;
  55542. };
  55543. /**
  55544. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  55545. */
  55546. SolidParticleSystem.prototype.rebuildMesh = function () {
  55547. for (var p = 0; p < this.particles.length; p++) {
  55548. this._rebuildParticle(this.particles[p]);
  55549. }
  55550. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  55551. };
  55552. /**
  55553. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  55554. * This method calls `updateParticle()` for each particle of the SPS.
  55555. * For an animated SPS, it is usually called within the render loop.
  55556. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  55557. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  55558. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  55559. */
  55560. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  55561. if (start === void 0) { start = 0; }
  55562. if (end === void 0) { end = this.nbParticles - 1; }
  55563. if (update === void 0) { update = true; }
  55564. if (!this._updatable) {
  55565. return;
  55566. }
  55567. // custom beforeUpdate
  55568. this.beforeUpdateParticles(start, end, update);
  55569. this._cam_axisX.x = 1;
  55570. this._cam_axisX.y = 0;
  55571. this._cam_axisX.z = 0;
  55572. this._cam_axisY.x = 0;
  55573. this._cam_axisY.y = 1;
  55574. this._cam_axisY.z = 0;
  55575. this._cam_axisZ.x = 0;
  55576. this._cam_axisZ.y = 0;
  55577. this._cam_axisZ.z = 1;
  55578. // if the particles will always face the camera
  55579. if (this.billboard) {
  55580. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  55581. this._yaw = this.mesh.rotation.y;
  55582. this._pitch = this.mesh.rotation.x;
  55583. this._roll = this.mesh.rotation.z;
  55584. this._quaternionRotationYPR();
  55585. this._quaternionToRotationMatrix();
  55586. this._rotMatrix.invertToRef(this._invertMatrix);
  55587. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  55588. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  55589. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  55590. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  55591. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  55592. this._cam_axisY.normalize();
  55593. this._cam_axisX.normalize();
  55594. this._cam_axisZ.normalize();
  55595. }
  55596. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  55597. var idx = 0;
  55598. var index = 0;
  55599. var colidx = 0;
  55600. var colorIndex = 0;
  55601. var uvidx = 0;
  55602. var uvIndex = 0;
  55603. var pt = 0;
  55604. if (this._computeBoundingBox) {
  55605. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  55606. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  55607. }
  55608. // particle loop
  55609. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  55610. for (var p = start; p <= end; p++) {
  55611. this._particle = this.particles[p];
  55612. this._shape = this._particle._model._shape;
  55613. this._shapeUV = this._particle._model._shapeUV;
  55614. // call to custom user function to update the particle properties
  55615. this.updateParticle(this._particle);
  55616. if (this._particle.isVisible) {
  55617. // particle rotation matrix
  55618. if (this.billboard) {
  55619. this._particle.rotation.x = 0.0;
  55620. this._particle.rotation.y = 0.0;
  55621. }
  55622. if (this._computeParticleRotation) {
  55623. if (this._particle.rotationQuaternion) {
  55624. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  55625. }
  55626. else {
  55627. this._yaw = this._particle.rotation.y;
  55628. this._pitch = this._particle.rotation.x;
  55629. this._roll = this._particle.rotation.z;
  55630. this._quaternionRotationYPR();
  55631. }
  55632. this._quaternionToRotationMatrix();
  55633. }
  55634. // particle vertex loop
  55635. for (pt = 0; pt < this._shape.length; pt++) {
  55636. idx = index + pt * 3;
  55637. colidx = colorIndex + pt * 4;
  55638. uvidx = uvIndex + pt * 2;
  55639. this._vertex.x = this._shape[pt].x;
  55640. this._vertex.y = this._shape[pt].y;
  55641. this._vertex.z = this._shape[pt].z;
  55642. if (this._computeParticleVertex) {
  55643. this.updateParticleVertex(this._particle, this._vertex, pt);
  55644. }
  55645. // positions
  55646. this._vertex.x *= this._particle.scaling.x;
  55647. this._vertex.y *= this._particle.scaling.y;
  55648. this._vertex.z *= this._particle.scaling.z;
  55649. 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];
  55650. 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;
  55651. 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;
  55652. 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;
  55653. 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;
  55654. 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;
  55655. 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;
  55656. if (this._computeBoundingBox) {
  55657. if (this._positions32[idx] < this._minimum.x) {
  55658. this._minimum.x = this._positions32[idx];
  55659. }
  55660. if (this._positions32[idx] > this._maximum.x) {
  55661. this._maximum.x = this._positions32[idx];
  55662. }
  55663. if (this._positions32[idx + 1] < this._minimum.y) {
  55664. this._minimum.y = this._positions32[idx + 1];
  55665. }
  55666. if (this._positions32[idx + 1] > this._maximum.y) {
  55667. this._maximum.y = this._positions32[idx + 1];
  55668. }
  55669. if (this._positions32[idx + 2] < this._minimum.z) {
  55670. this._minimum.z = this._positions32[idx + 2];
  55671. }
  55672. if (this._positions32[idx + 2] > this._maximum.z) {
  55673. this._maximum.z = this._positions32[idx + 2];
  55674. }
  55675. }
  55676. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  55677. if (!this._computeParticleVertex && !this.billboard) {
  55678. this._normal.x = this._fixedNormal32[idx];
  55679. this._normal.y = this._fixedNormal32[idx + 1];
  55680. this._normal.z = this._fixedNormal32[idx + 2];
  55681. 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];
  55682. 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;
  55683. 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;
  55684. 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;
  55685. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  55686. 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;
  55687. 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;
  55688. }
  55689. if (this._computeParticleColor) {
  55690. this._colors32[colidx] = this._particle.color.r;
  55691. this._colors32[colidx + 1] = this._particle.color.g;
  55692. this._colors32[colidx + 2] = this._particle.color.b;
  55693. this._colors32[colidx + 3] = this._particle.color.a;
  55694. }
  55695. if (this._computeParticleTexture) {
  55696. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  55697. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  55698. }
  55699. }
  55700. }
  55701. else {
  55702. for (pt = 0; pt < this._shape.length; pt++) {
  55703. idx = index + pt * 3;
  55704. colidx = colorIndex + pt * 4;
  55705. uvidx = uvIndex + pt * 2;
  55706. this._positions32[idx] = this._camera.position.x;
  55707. this._positions32[idx + 1] = this._camera.position.y;
  55708. this._positions32[idx + 2] = this._camera.position.z;
  55709. this._normals32[idx] = 0.0;
  55710. this._normals32[idx + 1] = 0.0;
  55711. this._normals32[idx + 2] = 0.0;
  55712. if (this._computeParticleColor) {
  55713. this._colors32[colidx] = this._particle.color.r;
  55714. this._colors32[colidx + 1] = this._particle.color.g;
  55715. this._colors32[colidx + 2] = this._particle.color.b;
  55716. this._colors32[colidx + 3] = this._particle.color.a;
  55717. }
  55718. if (this._computeParticleTexture) {
  55719. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  55720. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  55721. }
  55722. }
  55723. }
  55724. // increment indexes for the next particle
  55725. index = idx + 3;
  55726. colorIndex = colidx + 4;
  55727. uvIndex = uvidx + 2;
  55728. }
  55729. // if the VBO must be updated
  55730. if (update) {
  55731. if (this._computeParticleColor) {
  55732. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  55733. }
  55734. if (this._computeParticleTexture) {
  55735. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  55736. }
  55737. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  55738. if (!this.mesh.areNormalsFrozen) {
  55739. if (this._computeParticleVertex || this.billboard) {
  55740. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  55741. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  55742. for (var i = 0; i < this._normals32.length; i++) {
  55743. this._fixedNormal32[i] = this._normals32[i];
  55744. }
  55745. }
  55746. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  55747. }
  55748. }
  55749. if (this._computeBoundingBox) {
  55750. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  55751. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  55752. }
  55753. this.afterUpdateParticles(start, end, update);
  55754. };
  55755. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  55756. this._halfroll = this._roll * 0.5;
  55757. this._halfpitch = this._pitch * 0.5;
  55758. this._halfyaw = this._yaw * 0.5;
  55759. this._sinRoll = Math.sin(this._halfroll);
  55760. this._cosRoll = Math.cos(this._halfroll);
  55761. this._sinPitch = Math.sin(this._halfpitch);
  55762. this._cosPitch = Math.cos(this._halfpitch);
  55763. this._sinYaw = Math.sin(this._halfyaw);
  55764. this._cosYaw = Math.cos(this._halfyaw);
  55765. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  55766. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  55767. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  55768. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  55769. };
  55770. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  55771. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  55772. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  55773. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  55774. this._rotMatrix.m[3] = 0;
  55775. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  55776. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  55777. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  55778. this._rotMatrix.m[7] = 0;
  55779. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  55780. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  55781. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  55782. this._rotMatrix.m[11] = 0;
  55783. this._rotMatrix.m[12] = 0;
  55784. this._rotMatrix.m[13] = 0;
  55785. this._rotMatrix.m[14] = 0;
  55786. this._rotMatrix.m[15] = 1.0;
  55787. };
  55788. /**
  55789. * Disposes the SPS
  55790. */
  55791. SolidParticleSystem.prototype.dispose = function () {
  55792. this.mesh.dispose();
  55793. this.vars = null;
  55794. // drop references to internal big arrays for the GC
  55795. this._positions = null;
  55796. this._indices = null;
  55797. this._normals = null;
  55798. this._uvs = null;
  55799. this._colors = null;
  55800. this._positions32 = null;
  55801. this._normals32 = null;
  55802. this._fixedNormal32 = null;
  55803. this._uvs32 = null;
  55804. this._colors32 = null;
  55805. this.pickedParticles = null;
  55806. };
  55807. /**
  55808. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  55809. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55810. */
  55811. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  55812. if (!this._isVisibilityBoxLocked) {
  55813. this.mesh.refreshBoundingInfo();
  55814. }
  55815. };
  55816. /**
  55817. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  55818. * @param size the size (float) of the visibility box
  55819. * note : this doesn't lock the SPS mesh bounding box.
  55820. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55821. */
  55822. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  55823. var vis = size / 2;
  55824. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  55825. };
  55826. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  55827. // getter and setter
  55828. get: function () {
  55829. return this._alwaysVisible;
  55830. },
  55831. /**
  55832. * Sets the SPS as always visible or not
  55833. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55834. */
  55835. set: function (val) {
  55836. this._alwaysVisible = val;
  55837. this.mesh.alwaysSelectAsActiveMesh = val;
  55838. },
  55839. enumerable: true,
  55840. configurable: true
  55841. });
  55842. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  55843. get: function () {
  55844. return this._isVisibilityBoxLocked;
  55845. },
  55846. /**
  55847. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  55848. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55849. */
  55850. set: function (val) {
  55851. this._isVisibilityBoxLocked = val;
  55852. this.mesh.getBoundingInfo().isLocked = val;
  55853. },
  55854. enumerable: true,
  55855. configurable: true
  55856. });
  55857. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  55858. // getters
  55859. get: function () {
  55860. return this._computeParticleRotation;
  55861. },
  55862. // Optimizer setters
  55863. /**
  55864. * Tells to `setParticles()` to compute the particle rotations or not.
  55865. * Default value : true. The SPS is faster when it's set to false.
  55866. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  55867. */
  55868. set: function (val) {
  55869. this._computeParticleRotation = val;
  55870. },
  55871. enumerable: true,
  55872. configurable: true
  55873. });
  55874. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  55875. get: function () {
  55876. return this._computeParticleColor;
  55877. },
  55878. /**
  55879. * Tells to `setParticles()` to compute the particle colors or not.
  55880. * Default value : true. The SPS is faster when it's set to false.
  55881. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  55882. */
  55883. set: function (val) {
  55884. this._computeParticleColor = val;
  55885. },
  55886. enumerable: true,
  55887. configurable: true
  55888. });
  55889. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  55890. get: function () {
  55891. return this._computeParticleTexture;
  55892. },
  55893. /**
  55894. * Tells to `setParticles()` to compute the particle textures or not.
  55895. * Default value : true. The SPS is faster when it's set to false.
  55896. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  55897. */
  55898. set: function (val) {
  55899. this._computeParticleTexture = val;
  55900. },
  55901. enumerable: true,
  55902. configurable: true
  55903. });
  55904. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  55905. get: function () {
  55906. return this._computeParticleVertex;
  55907. },
  55908. /**
  55909. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  55910. * Default value : false. The SPS is faster when it's set to false.
  55911. * Note : the particle custom vertex positions aren't stored values.
  55912. */
  55913. set: function (val) {
  55914. this._computeParticleVertex = val;
  55915. },
  55916. enumerable: true,
  55917. configurable: true
  55918. });
  55919. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  55920. get: function () {
  55921. return this._computeBoundingBox;
  55922. },
  55923. /**
  55924. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  55925. */
  55926. set: function (val) {
  55927. this._computeBoundingBox = val;
  55928. },
  55929. enumerable: true,
  55930. configurable: true
  55931. });
  55932. // =======================================================================
  55933. // Particle behavior logic
  55934. // these following methods may be overwritten by the user to fit his needs
  55935. /**
  55936. * This function does nothing. It may be overwritten to set all the particle first values.
  55937. * The SPS doesn't call this function, you may have to call it by your own.
  55938. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55939. */
  55940. SolidParticleSystem.prototype.initParticles = function () {
  55941. };
  55942. /**
  55943. * This function does nothing. It may be overwritten to recycle a particle.
  55944. * The SPS doesn't call this function, you may have to call it by your own.
  55945. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55946. */
  55947. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  55948. return particle;
  55949. };
  55950. /**
  55951. * Updates a particle : this function should be overwritten by the user.
  55952. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  55953. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55954. * ex : just set a particle position or velocity and recycle conditions
  55955. */
  55956. SolidParticleSystem.prototype.updateParticle = function (particle) {
  55957. return particle;
  55958. };
  55959. /**
  55960. * Updates a vertex of a particle : it can be overwritten by the user.
  55961. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  55962. * @param particle the current particle
  55963. * @param vertex the current index of the current particle
  55964. * @param pt the index of the current vertex in the particle shape
  55965. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  55966. * ex : just set a vertex particle position
  55967. */
  55968. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  55969. return vertex;
  55970. };
  55971. /**
  55972. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  55973. * This does nothing and may be overwritten by the user.
  55974. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55975. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55976. * @param update the boolean update value actually passed to setParticles()
  55977. */
  55978. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  55979. };
  55980. /**
  55981. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  55982. * This will be passed three parameters.
  55983. * This does nothing and may be overwritten by the user.
  55984. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55985. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55986. * @param update the boolean update value actually passed to setParticles()
  55987. */
  55988. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  55989. };
  55990. return SolidParticleSystem;
  55991. }());
  55992. BABYLON.SolidParticleSystem = SolidParticleSystem;
  55993. })(BABYLON || (BABYLON = {}));
  55994. var BABYLON;
  55995. (function (BABYLON) {
  55996. var Internals;
  55997. (function (Internals) {
  55998. var FileFaceOrientation = (function () {
  55999. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  56000. this.name = name;
  56001. this.worldAxisForNormal = worldAxisForNormal;
  56002. this.worldAxisForFileX = worldAxisForFileX;
  56003. this.worldAxisForFileY = worldAxisForFileY;
  56004. }
  56005. return FileFaceOrientation;
  56006. }());
  56007. ;
  56008. /**
  56009. * Helper class dealing with the extraction of spherical polynomial dataArray
  56010. * from a cube map.
  56011. */
  56012. var CubeMapToSphericalPolynomialTools = (function () {
  56013. function CubeMapToSphericalPolynomialTools() {
  56014. }
  56015. /**
  56016. * Converts a cubemap to the according Spherical Polynomial data.
  56017. * This extracts the first 3 orders only as they are the only one used in the lighting.
  56018. *
  56019. * @param cubeInfo The Cube map to extract the information from.
  56020. * @return The Spherical Polynomial data.
  56021. */
  56022. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  56023. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  56024. var totalSolidAngle = 0.0;
  56025. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  56026. var du = 2.0 / cubeInfo.size;
  56027. var dv = du;
  56028. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  56029. var minUV = du * 0.5 - 1.0;
  56030. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56031. var fileFace = this.FileFaces[faceIndex];
  56032. var dataArray = cubeInfo[fileFace.name];
  56033. var v = minUV;
  56034. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  56035. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  56036. // Because SP is still linear, so summation is fine in that basis.
  56037. for (var y = 0; y < cubeInfo.size; y++) {
  56038. var u = minUV;
  56039. for (var x = 0; x < cubeInfo.size; x++) {
  56040. // World direction (not normalised)
  56041. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  56042. worldDirection.normalize();
  56043. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  56044. if (1) {
  56045. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  56046. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  56047. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  56048. var color = new BABYLON.Color3(r, g, b);
  56049. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  56050. }
  56051. else {
  56052. if (faceIndex == 0) {
  56053. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  56054. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  56055. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  56056. }
  56057. else if (faceIndex == 1) {
  56058. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  56059. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  56060. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  56061. }
  56062. else if (faceIndex == 2) {
  56063. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  56064. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  56065. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  56066. }
  56067. else if (faceIndex == 3) {
  56068. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  56069. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  56070. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  56071. }
  56072. else if (faceIndex == 4) {
  56073. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  56074. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  56075. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  56076. }
  56077. else if (faceIndex == 5) {
  56078. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  56079. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  56080. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  56081. }
  56082. 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]);
  56083. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  56084. }
  56085. totalSolidAngle += deltaSolidAngle;
  56086. u += du;
  56087. }
  56088. v += dv;
  56089. }
  56090. }
  56091. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  56092. var correction = correctSolidAngle / totalSolidAngle;
  56093. sphericalHarmonics.scale(correction);
  56094. // Additionally scale by pi -- audit needed
  56095. sphericalHarmonics.scale(1.0 / Math.PI);
  56096. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  56097. };
  56098. CubeMapToSphericalPolynomialTools.FileFaces = [
  56099. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  56100. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  56101. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  56102. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  56103. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  56104. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  56105. ];
  56106. return CubeMapToSphericalPolynomialTools;
  56107. }());
  56108. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  56109. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56110. })(BABYLON || (BABYLON = {}));
  56111. var BABYLON;
  56112. (function (BABYLON) {
  56113. var Internals;
  56114. (function (Internals) {
  56115. /**
  56116. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  56117. */
  56118. var PanoramaToCubeMapTools = (function () {
  56119. function PanoramaToCubeMapTools() {
  56120. }
  56121. /**
  56122. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  56123. *
  56124. * @param float32Array The source data.
  56125. * @param inputWidth The width of the input panorama.
  56126. * @param inputhHeight The height of the input panorama.
  56127. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  56128. * @return The cubemap data
  56129. */
  56130. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  56131. if (!float32Array) {
  56132. throw "ConvertPanoramaToCubemap: input cannot be null";
  56133. }
  56134. if (float32Array.length != inputWidth * inputHeight * 3) {
  56135. throw "ConvertPanoramaToCubemap: input size is wrong";
  56136. }
  56137. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  56138. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  56139. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  56140. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  56141. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  56142. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  56143. return {
  56144. front: textureFront,
  56145. back: textureBack,
  56146. left: textureLeft,
  56147. right: textureRight,
  56148. up: textureUp,
  56149. down: textureDown,
  56150. size: size
  56151. };
  56152. };
  56153. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  56154. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  56155. var textureArray = new Float32Array(buffer);
  56156. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  56157. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  56158. var dy = 1 / texSize;
  56159. var fy = 0;
  56160. for (var y = 0; y < texSize; y++) {
  56161. var xv1 = faceData[0];
  56162. var xv2 = faceData[2];
  56163. for (var x = 0; x < texSize; x++) {
  56164. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  56165. v.normalize();
  56166. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  56167. // 3 channels per pixels
  56168. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  56169. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  56170. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  56171. xv1 = xv1.add(rotDX1);
  56172. xv2 = xv2.add(rotDX2);
  56173. }
  56174. fy += dy;
  56175. }
  56176. return textureArray;
  56177. };
  56178. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  56179. var theta = Math.atan2(vDir.z, vDir.x);
  56180. var phi = Math.acos(vDir.y);
  56181. while (theta < -Math.PI)
  56182. theta += 2 * Math.PI;
  56183. while (theta > Math.PI)
  56184. theta -= 2 * Math.PI;
  56185. var dx = theta / Math.PI;
  56186. var dy = phi / Math.PI;
  56187. // recenter.
  56188. dx = dx * 0.5 + 0.5;
  56189. var px = Math.round(dx * inputWidth);
  56190. if (px < 0)
  56191. px = 0;
  56192. else if (px >= inputWidth)
  56193. px = inputWidth - 1;
  56194. var py = Math.round(dy * inputHeight);
  56195. if (py < 0)
  56196. py = 0;
  56197. else if (py >= inputHeight)
  56198. py = inputHeight - 1;
  56199. var inputY = (inputHeight - py - 1);
  56200. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  56201. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  56202. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  56203. return {
  56204. r: r,
  56205. g: g,
  56206. b: b
  56207. };
  56208. };
  56209. PanoramaToCubeMapTools.FACE_FRONT = [
  56210. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56211. new BABYLON.Vector3(1.0, -1.0, -1.0),
  56212. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  56213. new BABYLON.Vector3(1.0, 1.0, -1.0)
  56214. ];
  56215. PanoramaToCubeMapTools.FACE_BACK = [
  56216. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56217. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56218. new BABYLON.Vector3(1.0, 1.0, 1.0),
  56219. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  56220. ];
  56221. PanoramaToCubeMapTools.FACE_RIGHT = [
  56222. new BABYLON.Vector3(1.0, -1.0, -1.0),
  56223. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56224. new BABYLON.Vector3(1.0, 1.0, -1.0),
  56225. new BABYLON.Vector3(1.0, 1.0, 1.0)
  56226. ];
  56227. PanoramaToCubeMapTools.FACE_LEFT = [
  56228. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56229. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56230. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  56231. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  56232. ];
  56233. PanoramaToCubeMapTools.FACE_DOWN = [
  56234. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  56235. new BABYLON.Vector3(1.0, 1.0, -1.0),
  56236. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  56237. new BABYLON.Vector3(1.0, 1.0, 1.0)
  56238. ];
  56239. PanoramaToCubeMapTools.FACE_UP = [
  56240. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56241. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56242. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56243. new BABYLON.Vector3(1.0, -1.0, -1.0)
  56244. ];
  56245. return PanoramaToCubeMapTools;
  56246. }());
  56247. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  56248. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56249. })(BABYLON || (BABYLON = {}));
  56250. var BABYLON;
  56251. (function (BABYLON) {
  56252. var Internals;
  56253. (function (Internals) {
  56254. ;
  56255. /**
  56256. * This groups tools to convert HDR texture to native colors array.
  56257. */
  56258. var HDRTools = (function () {
  56259. function HDRTools() {
  56260. }
  56261. HDRTools.Ldexp = function (mantissa, exponent) {
  56262. if (exponent > 1023) {
  56263. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  56264. }
  56265. if (exponent < -1074) {
  56266. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  56267. }
  56268. return mantissa * Math.pow(2, exponent);
  56269. };
  56270. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  56271. if (exponent > 0) {
  56272. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  56273. float32array[index + 0] = red * exponent;
  56274. float32array[index + 1] = green * exponent;
  56275. float32array[index + 2] = blue * exponent;
  56276. }
  56277. else {
  56278. float32array[index + 0] = 0;
  56279. float32array[index + 1] = 0;
  56280. float32array[index + 2] = 0;
  56281. }
  56282. };
  56283. HDRTools.readStringLine = function (uint8array, startIndex) {
  56284. var line = "";
  56285. var character = "";
  56286. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  56287. character = String.fromCharCode(uint8array[i]);
  56288. if (character == "\n") {
  56289. break;
  56290. }
  56291. line += character;
  56292. }
  56293. return line;
  56294. };
  56295. /**
  56296. * Reads header information from an RGBE texture stored in a native array.
  56297. * More information on this format are available here:
  56298. * https://en.wikipedia.org/wiki/RGBE_image_format
  56299. *
  56300. * @param uint8array The binary file stored in native array.
  56301. * @return The header information.
  56302. */
  56303. HDRTools.RGBE_ReadHeader = function (uint8array) {
  56304. var height = 0;
  56305. var width = 0;
  56306. var line = this.readStringLine(uint8array, 0);
  56307. if (line[0] != '#' || line[1] != '?') {
  56308. throw "Bad HDR Format.";
  56309. }
  56310. var endOfHeader = false;
  56311. var findFormat = false;
  56312. var lineIndex = 0;
  56313. do {
  56314. lineIndex += (line.length + 1);
  56315. line = this.readStringLine(uint8array, lineIndex);
  56316. if (line == "FORMAT=32-bit_rle_rgbe") {
  56317. findFormat = true;
  56318. }
  56319. else if (line.length == 0) {
  56320. endOfHeader = true;
  56321. }
  56322. } while (!endOfHeader);
  56323. if (!findFormat) {
  56324. throw "HDR Bad header format, unsupported FORMAT";
  56325. }
  56326. lineIndex += (line.length + 1);
  56327. line = this.readStringLine(uint8array, lineIndex);
  56328. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  56329. var match = sizeRegexp.exec(line);
  56330. // TODO. Support +Y and -X if needed.
  56331. if (match.length < 3) {
  56332. throw "HDR Bad header format, no size";
  56333. }
  56334. width = parseInt(match[2]);
  56335. height = parseInt(match[1]);
  56336. if (width < 8 || width > 0x7fff) {
  56337. throw "HDR Bad header format, unsupported size";
  56338. }
  56339. lineIndex += (line.length + 1);
  56340. return {
  56341. height: height,
  56342. width: width,
  56343. dataPosition: lineIndex
  56344. };
  56345. };
  56346. /**
  56347. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  56348. * This RGBE texture needs to store the information as a panorama.
  56349. *
  56350. * More information on this format are available here:
  56351. * https://en.wikipedia.org/wiki/RGBE_image_format
  56352. *
  56353. * @param buffer The binary file stored in an array buffer.
  56354. * @param size The expected size of the extracted cubemap.
  56355. * @return The Cube Map information.
  56356. */
  56357. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  56358. var uint8array = new Uint8Array(buffer);
  56359. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  56360. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  56361. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  56362. return cubeMapData;
  56363. };
  56364. /**
  56365. * Returns the pixels data extracted from an RGBE texture.
  56366. * This pixels will be stored left to right up to down in the R G B order in one array.
  56367. *
  56368. * More information on this format are available here:
  56369. * https://en.wikipedia.org/wiki/RGBE_image_format
  56370. *
  56371. * @param uint8array The binary file stored in an array buffer.
  56372. * @param hdrInfo The header information of the file.
  56373. * @return The pixels data in RGB right to left up to down order.
  56374. */
  56375. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  56376. // Keep for multi format supports.
  56377. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  56378. };
  56379. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  56380. var num_scanlines = hdrInfo.height;
  56381. var scanline_width = hdrInfo.width;
  56382. var a, b, c, d, count;
  56383. var dataIndex = hdrInfo.dataPosition;
  56384. var index = 0, endIndex = 0, i = 0;
  56385. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  56386. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  56387. // 3 channels of 4 bytes per pixel in float.
  56388. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  56389. var resultArray = new Float32Array(resultBuffer);
  56390. // read in each successive scanline
  56391. while (num_scanlines > 0) {
  56392. a = uint8array[dataIndex++];
  56393. b = uint8array[dataIndex++];
  56394. c = uint8array[dataIndex++];
  56395. d = uint8array[dataIndex++];
  56396. if (a != 2 || b != 2 || (c & 0x80)) {
  56397. // this file is not run length encoded
  56398. throw "HDR Bad header format, not RLE";
  56399. }
  56400. if (((c << 8) | d) != scanline_width) {
  56401. throw "HDR Bad header format, wrong scan line width";
  56402. }
  56403. index = 0;
  56404. // read each of the four channels for the scanline into the buffer
  56405. for (i = 0; i < 4; i++) {
  56406. endIndex = (i + 1) * scanline_width;
  56407. while (index < endIndex) {
  56408. a = uint8array[dataIndex++];
  56409. b = uint8array[dataIndex++];
  56410. if (a > 128) {
  56411. // a run of the same value
  56412. count = a - 128;
  56413. if ((count == 0) || (count > endIndex - index)) {
  56414. throw "HDR Bad Format, bad scanline data (run)";
  56415. }
  56416. while (count-- > 0) {
  56417. scanLineArray[index++] = b;
  56418. }
  56419. }
  56420. else {
  56421. // a non-run
  56422. count = a;
  56423. if ((count == 0) || (count > endIndex - index)) {
  56424. throw "HDR Bad Format, bad scanline data (non-run)";
  56425. }
  56426. scanLineArray[index++] = b;
  56427. if (--count > 0) {
  56428. for (var j = 0; j < count; j++) {
  56429. scanLineArray[index++] = uint8array[dataIndex++];
  56430. }
  56431. }
  56432. }
  56433. }
  56434. }
  56435. // now convert data from buffer into floats
  56436. for (i = 0; i < scanline_width; i++) {
  56437. a = scanLineArray[i];
  56438. b = scanLineArray[i + scanline_width];
  56439. c = scanLineArray[i + 2 * scanline_width];
  56440. d = scanLineArray[i + 3 * scanline_width];
  56441. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  56442. }
  56443. num_scanlines--;
  56444. }
  56445. return resultArray;
  56446. };
  56447. return HDRTools;
  56448. }());
  56449. Internals.HDRTools = HDRTools;
  56450. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56451. })(BABYLON || (BABYLON = {}));
  56452. //_______________________________________________________________
  56453. // Extracted from CubeMapGen:
  56454. // https://code.google.com/archive/p/cubemapgen/
  56455. //
  56456. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  56457. //_______________________________________________________________
  56458. var BABYLON;
  56459. (function (BABYLON) {
  56460. var Internals;
  56461. (function (Internals) {
  56462. /**
  56463. * The bounding box information used during the conversion process.
  56464. */
  56465. var CMGBoundinBox = (function () {
  56466. function CMGBoundinBox() {
  56467. this.min = new BABYLON.Vector3(0, 0, 0);
  56468. this.max = new BABYLON.Vector3(0, 0, 0);
  56469. this.clear();
  56470. }
  56471. CMGBoundinBox.prototype.clear = function () {
  56472. this.min.x = CMGBoundinBox.MAX;
  56473. this.min.y = CMGBoundinBox.MAX;
  56474. this.min.z = CMGBoundinBox.MAX;
  56475. this.max.x = CMGBoundinBox.MIN;
  56476. this.max.y = CMGBoundinBox.MIN;
  56477. this.max.z = CMGBoundinBox.MIN;
  56478. };
  56479. CMGBoundinBox.prototype.augment = function (x, y, z) {
  56480. this.min.x = Math.min(this.min.x, x);
  56481. this.min.y = Math.min(this.min.y, y);
  56482. this.min.z = Math.min(this.min.z, z);
  56483. this.max.x = Math.max(this.max.x, x);
  56484. this.max.y = Math.max(this.max.y, y);
  56485. this.max.z = Math.max(this.max.z, z);
  56486. };
  56487. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  56488. this.min.x = Math.max(this.min.x, x);
  56489. this.min.y = Math.max(this.min.y, y);
  56490. this.min.z = Math.max(this.min.z, z);
  56491. };
  56492. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  56493. this.max.x = Math.min(this.max.x, x);
  56494. this.max.y = Math.min(this.max.y, y);
  56495. this.max.z = Math.min(this.max.z, z);
  56496. };
  56497. CMGBoundinBox.prototype.empty = function () {
  56498. if ((this.min.x > this.max.y) ||
  56499. (this.min.y > this.max.y) ||
  56500. (this.min.z > this.max.y)) {
  56501. return true;
  56502. }
  56503. else {
  56504. return false;
  56505. }
  56506. };
  56507. CMGBoundinBox.MAX = Number.MAX_VALUE;
  56508. CMGBoundinBox.MIN = Number.MIN_VALUE;
  56509. return CMGBoundinBox;
  56510. }());
  56511. /**
  56512. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  56513. * required by the glossinees of a material.
  56514. *
  56515. * This only supports the cosine drop power as well as Warp fixup generation method.
  56516. *
  56517. * This is using the process from CubeMapGen described here:
  56518. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  56519. */
  56520. var PMREMGenerator = (function () {
  56521. /**
  56522. * Constructor of the generator.
  56523. *
  56524. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  56525. * @param inputSize The size of the cubemap faces
  56526. * @param outputSize The size of the output cubemap faces
  56527. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  56528. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  56529. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  56530. * @param specularPower The max specular level of the desired cubemap
  56531. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  56532. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  56533. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  56534. */
  56535. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  56536. this.input = input;
  56537. this.inputSize = inputSize;
  56538. this.outputSize = outputSize;
  56539. this.maxNumMipLevels = maxNumMipLevels;
  56540. this.numChannels = numChannels;
  56541. this.isFloat = isFloat;
  56542. this.specularPower = specularPower;
  56543. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  56544. this.excludeBase = excludeBase;
  56545. this.fixup = fixup;
  56546. this._outputSurface = [];
  56547. this._numMipLevels = 0;
  56548. }
  56549. /**
  56550. * Launches the filter process and return the result.
  56551. *
  56552. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  56553. */
  56554. PMREMGenerator.prototype.filterCubeMap = function () {
  56555. // Init cubemap processor
  56556. this.init();
  56557. // Filters the cubemap
  56558. this.filterCubeMapMipChain();
  56559. // Returns the filtered mips.
  56560. return this._outputSurface;
  56561. };
  56562. PMREMGenerator.prototype.init = function () {
  56563. var i;
  56564. var j;
  56565. var mipLevelSize;
  56566. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  56567. if (this.maxNumMipLevels == 0) {
  56568. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  56569. }
  56570. //first miplevel size
  56571. mipLevelSize = this.outputSize;
  56572. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  56573. for (j = 0; j < this.maxNumMipLevels; j++) {
  56574. this._outputSurface.length++;
  56575. this._outputSurface[j] = [];
  56576. //Iterate over faces for output images
  56577. for (i = 0; i < 6; i++) {
  56578. this._outputSurface[j].length++;
  56579. // Initializes a new array for the output.
  56580. if (this.isFloat) {
  56581. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  56582. }
  56583. else {
  56584. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  56585. }
  56586. }
  56587. //next mip level is half size
  56588. mipLevelSize >>= 1;
  56589. this._numMipLevels++;
  56590. //terminate if mip chain becomes too small
  56591. if (mipLevelSize == 0) {
  56592. this.maxNumMipLevels = j;
  56593. return;
  56594. }
  56595. }
  56596. };
  56597. //--------------------------------------------------------------------------------------
  56598. //Cube map filtering and mip chain generation.
  56599. // the cube map filtereing is specified using a number of parameters:
  56600. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  56601. // indicates the region of the hemisphere to filter over for each tap.
  56602. //
  56603. // Note that the top mip level is also a filtered version of the original input images
  56604. // as well in order to create mip chains for diffuse environment illumination.
  56605. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  56606. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  56607. //
  56608. // Then the mip angle used to genreate the next level of the mip chain from the first level
  56609. // is a_InitialMipAngle
  56610. //
  56611. // The angle for the subsequent levels of the mip chain are specified by their parents
  56612. // filtering angle and a per-level scale and bias
  56613. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  56614. //
  56615. //--------------------------------------------------------------------------------------
  56616. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  56617. // First, take count of the lighting model to modify SpecularPower
  56618. // 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;
  56619. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  56620. //Cone angle start (for generating subsequent mip levels)
  56621. var currentSpecularPower = this.specularPower;
  56622. //Build filter lookup tables based on the source miplevel size
  56623. this.precomputeFilterLookupTables(this.inputSize);
  56624. // Note that we need to filter the first level before generating mipmap
  56625. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  56626. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  56627. // TODO : Write a function to copy and scale the base mipmap in output
  56628. // I am just lazy here and just put a high specular power value, and do some if.
  56629. if (this.excludeBase && (levelIndex == 0)) {
  56630. // 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).
  56631. currentSpecularPower = 100000.0;
  56632. }
  56633. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  56634. var srcCubeImage = this.input;
  56635. var dstCubeImage = this._outputSurface[levelIndex];
  56636. var dstSize = this.outputSize >> levelIndex;
  56637. // Compute required angle.
  56638. var angle = this.getBaseFilterAngle(currentSpecularPower);
  56639. // filter cube surfaces
  56640. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  56641. // fix seams
  56642. if (this.fixup) {
  56643. this.fixupCubeEdges(dstCubeImage, dstSize);
  56644. }
  56645. // Decrease the specular power to generate the mipmap chain
  56646. // TODO : Use another method for Exclude (see first comment at start of the function
  56647. if (this.excludeBase && (levelIndex == 0)) {
  56648. currentSpecularPower = this.specularPower;
  56649. }
  56650. currentSpecularPower *= this.cosinePowerDropPerMip;
  56651. }
  56652. };
  56653. //--------------------------------------------------------------------------------------
  56654. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  56655. // It allow to optimize the texel to access base on the specular power.
  56656. //--------------------------------------------------------------------------------------
  56657. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  56658. // We want to find the alpha such that:
  56659. // cos(alpha)^cosinePower = epsilon
  56660. // That's: acos(epsilon^(1/cosinePower))
  56661. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  56662. var angle = 180.0;
  56663. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  56664. angle *= 180.0 / Math.PI; // Convert to degree
  56665. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  56666. return angle;
  56667. };
  56668. //--------------------------------------------------------------------------------------
  56669. //Builds the following lookup tables prior to filtering:
  56670. // -normalizer cube map
  56671. // -tap weight lookup table
  56672. //
  56673. //--------------------------------------------------------------------------------------
  56674. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  56675. var srcTexelAngle;
  56676. var iCubeFace;
  56677. //clear pre-existing normalizer cube map
  56678. this._normCubeMap = [];
  56679. //Normalized vectors per cubeface and per-texel solid angle
  56680. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  56681. };
  56682. //--------------------------------------------------------------------------------------
  56683. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  56684. //
  56685. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  56686. //
  56687. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  56688. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  56689. // below
  56690. //--------------------------------------------------------------------------------------
  56691. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  56692. var iCubeFace;
  56693. var u;
  56694. var v;
  56695. //iterate over cube faces
  56696. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  56697. //First three channels for norm cube, and last channel for solid angle
  56698. this._normCubeMap.push(new Float32Array(size * size * 4));
  56699. //fast texture walk, build normalizer cube map
  56700. var facesData = this.input[iCubeFace];
  56701. for (v = 0; v < size; v++) {
  56702. for (u = 0; u < size; u++) {
  56703. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  56704. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  56705. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  56706. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  56707. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  56708. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  56709. }
  56710. }
  56711. }
  56712. };
  56713. //--------------------------------------------------------------------------------------
  56714. // Convert cubemap face texel coordinates and face idx to 3D vector
  56715. // note the U and V coords are integer coords and range from 0 to size-1
  56716. // this routine can be used to generate a normalizer cube map
  56717. //--------------------------------------------------------------------------------------
  56718. // SL BEGIN
  56719. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  56720. var nvcU;
  56721. var nvcV;
  56722. var tempVec;
  56723. // Change from original AMD code
  56724. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  56725. // + 0.5f is for texel center addressing
  56726. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  56727. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  56728. // warp fixup
  56729. if (fixup && size > 1) {
  56730. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  56731. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  56732. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  56733. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  56734. }
  56735. // Get current vector
  56736. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  56737. // U contribution
  56738. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  56739. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  56740. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  56741. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  56742. // V contribution and Sum
  56743. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  56744. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  56745. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  56746. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  56747. //add face axis
  56748. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  56749. PMREMGenerator._vectorTemp.x += faceAxis[0];
  56750. PMREMGenerator._vectorTemp.y += faceAxis[1];
  56751. PMREMGenerator._vectorTemp.z += faceAxis[2];
  56752. //normalize vector
  56753. PMREMGenerator._vectorTemp.normalize();
  56754. return PMREMGenerator._vectorTemp;
  56755. };
  56756. //--------------------------------------------------------------------------------------
  56757. // Convert 3D vector to cubemap face texel coordinates and face idx
  56758. // note the U and V coords are integer coords and range from 0 to size-1
  56759. // this routine can be used to generate a normalizer cube map
  56760. //
  56761. // returns face IDX and texel coords
  56762. //--------------------------------------------------------------------------------------
  56763. // SL BEGIN
  56764. /*
  56765. Mapping Texture Coordinates to Cube Map Faces
  56766. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  56767. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  56768. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  56769. map arrangement in Pixar's RenderMan package.
  56770. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  56771. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  56772. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  56773. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  56774. the major axis direction). The target column in the table below explains how the major axis direction
  56775. maps to the 2D image of a particular cube map target.
  56776. major axis
  56777. direction target sc tc ma
  56778. ---------- --------------------------------- --- --- ---
  56779. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  56780. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  56781. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  56782. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  56783. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  56784. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  56785. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  56786. an updated (s,t) is calculated as follows
  56787. s = ( sc/|ma| + 1 ) / 2
  56788. t = ( tc/|ma| + 1 ) / 2
  56789. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  56790. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  56791. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  56792. */
  56793. // Note this method return U and V in range from 0 to size-1
  56794. // SL END
  56795. // Store the information in vector3 for convenience (faceindex, u, v)
  56796. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  56797. var maxCoord;
  56798. var faceIdx;
  56799. //absolute value 3
  56800. var absX = Math.abs(x);
  56801. var absY = Math.abs(y);
  56802. var absZ = Math.abs(z);
  56803. if (absX >= absY && absX >= absZ) {
  56804. maxCoord = absX;
  56805. if (x >= 0) {
  56806. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  56807. }
  56808. else {
  56809. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  56810. }
  56811. }
  56812. else if (absY >= absX && absY >= absZ) {
  56813. maxCoord = absY;
  56814. if (y >= 0) {
  56815. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  56816. }
  56817. else {
  56818. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  56819. }
  56820. }
  56821. else {
  56822. maxCoord = absZ;
  56823. if (z >= 0) {
  56824. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  56825. }
  56826. else {
  56827. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  56828. }
  56829. }
  56830. //divide through by max coord so face vector lies on cube face
  56831. var scale = 1 / maxCoord;
  56832. x *= scale;
  56833. y *= scale;
  56834. z *= scale;
  56835. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  56836. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  56837. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  56838. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  56839. // Modify original AMD code to return value from 0 to Size - 1
  56840. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  56841. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  56842. PMREMGenerator._vectorTemp.x = faceIdx;
  56843. PMREMGenerator._vectorTemp.y = u;
  56844. PMREMGenerator._vectorTemp.z = v;
  56845. return PMREMGenerator._vectorTemp;
  56846. };
  56847. //--------------------------------------------------------------------------------------
  56848. //Original code from Ignacio CastaÒo
  56849. // This formula is from Manne ÷hrstrˆm's thesis.
  56850. // Take two coordiantes in the range [-1, 1] that define a portion of a
  56851. // cube face and return the area of the projection of that portion on the
  56852. // surface of the sphere.
  56853. //--------------------------------------------------------------------------------------
  56854. PMREMGenerator.prototype.areaElement = function (x, y) {
  56855. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  56856. };
  56857. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  56858. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  56859. // (+ 0.5f is for texel center addressing)
  56860. u = (2.0 * (u + 0.5) / size) - 1.0;
  56861. v = (2.0 * (v + 0.5) / size) - 1.0;
  56862. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  56863. var invResolution = 1.0 / size;
  56864. // U and V are the -1..1 texture coordinate on the current face.
  56865. // Get projected area for this texel
  56866. var x0 = u - invResolution;
  56867. var y0 = v - invResolution;
  56868. var x1 = u + invResolution;
  56869. var y1 = v + invResolution;
  56870. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  56871. return solidAngle;
  56872. };
  56873. //--------------------------------------------------------------------------------------
  56874. //The key to the speed of these filtering routines is to quickly define a per-face
  56875. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  56876. // Later these pixels are selectively processed based on their dot products to see if
  56877. // they reside within the filtering cone.
  56878. //
  56879. //This is done by computing the smallest per-texel angle to get a conservative estimate
  56880. // of the number of texels needed to be covered in width and height order to filter the
  56881. // region. the bounding box for the center taps face is defined first, and if the
  56882. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  56883. // defined next
  56884. //--------------------------------------------------------------------------------------
  56885. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  56886. // note that pixels within these regions may be rejected
  56887. // based on the anlge
  56888. var iCubeFace;
  56889. var u;
  56890. var v;
  56891. // bounding box per face to specify region to process
  56892. var filterExtents = [];
  56893. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  56894. filterExtents.push(new CMGBoundinBox());
  56895. }
  56896. // min angle a src texel can cover (in degrees)
  56897. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  56898. // angle about center tap to define filter cone
  56899. // filter angle is 1/2 the cone angle
  56900. var filterAngle = filterConeAngle / 2.0;
  56901. //ensure filter angle is larger than a texel
  56902. if (filterAngle < srcTexelAngle) {
  56903. filterAngle = srcTexelAngle;
  56904. }
  56905. //ensure filter cone is always smaller than the hemisphere
  56906. if (filterAngle > 90.0) {
  56907. filterAngle = 90.0;
  56908. }
  56909. // the maximum number of texels in 1D the filter cone angle will cover
  56910. // used to determine bounding box size for filter extents
  56911. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  56912. // ensure conservative region always covers at least one texel
  56913. if (filterSize < 1) {
  56914. filterSize = 1;
  56915. }
  56916. // dotProdThresh threshold based on cone angle to determine whether or not taps
  56917. // reside within the cone angle
  56918. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  56919. // process required faces
  56920. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  56921. //iterate over dst cube map face texel
  56922. for (v = 0; v < dstSize; v++) {
  56923. for (u = 0; u < dstSize; u++) {
  56924. //get center tap direction
  56925. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  56926. //clear old per-face filter extents
  56927. this.clearFilterExtents(filterExtents);
  56928. //define per-face filter extents
  56929. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  56930. //perform filtering of src faces using filter extents
  56931. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  56932. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  56933. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  56934. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  56935. }
  56936. }
  56937. }
  56938. };
  56939. //--------------------------------------------------------------------------------------
  56940. //Clear filter extents for the 6 cube map faces
  56941. //--------------------------------------------------------------------------------------
  56942. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  56943. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  56944. filterExtents[iCubeFaces].clear();
  56945. }
  56946. };
  56947. //--------------------------------------------------------------------------------------
  56948. //Define per-face bounding box filter extents
  56949. //
  56950. // These define conservative texel regions in each of the faces the filter can possibly
  56951. // process. When the pixels in the regions are actually processed, the dot product
  56952. // between the tap vector and the center tap vector is used to determine the weight of
  56953. // the tap and whether or not the tap is within the cone.
  56954. //
  56955. //--------------------------------------------------------------------------------------
  56956. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  56957. //neighboring face and bleed over amount, and width of BBOX for
  56958. // left, right, top, and bottom edges of this face
  56959. var bleedOverAmount = [0, 0, 0, 0];
  56960. var bleedOverBBoxMin = [0, 0, 0, 0];
  56961. var bleedOverBBoxMax = [0, 0, 0, 0];
  56962. var neighborFace;
  56963. var neighborEdge;
  56964. var oppositeFaceIdx;
  56965. //get face idx, and u, v info from center tap dir
  56966. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  56967. var faceIdx = result.x;
  56968. var u = result.y;
  56969. var v = result.z;
  56970. //define bbox size within face
  56971. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  56972. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  56973. filterExtents[faceIdx].clampMin(0, 0, 0);
  56974. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  56975. //u and v extent in face corresponding to center tap
  56976. var minU = filterExtents[faceIdx].min.x;
  56977. var minV = filterExtents[faceIdx].min.y;
  56978. var maxU = filterExtents[faceIdx].max.x;
  56979. var maxV = filterExtents[faceIdx].max.y;
  56980. //bleed over amounts for face across u=0 edge (left)
  56981. bleedOverAmount[0] = (bboxSize - u);
  56982. bleedOverBBoxMin[0] = minV;
  56983. bleedOverBBoxMax[0] = maxV;
  56984. //bleed over amounts for face across u=1 edge (right)
  56985. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  56986. bleedOverBBoxMin[1] = minV;
  56987. bleedOverBBoxMax[1] = maxV;
  56988. //bleed over to face across v=0 edge (up)
  56989. bleedOverAmount[2] = (bboxSize - v);
  56990. bleedOverBBoxMin[2] = minU;
  56991. bleedOverBBoxMax[2] = maxU;
  56992. //bleed over to face across v=1 edge (down)
  56993. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  56994. bleedOverBBoxMin[3] = minU;
  56995. bleedOverBBoxMax[3] = maxU;
  56996. //compute bleed over regions in neighboring faces
  56997. for (var i = 0; i < 4; i++) {
  56998. if (bleedOverAmount[i] > 0) {
  56999. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  57000. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  57001. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  57002. // be flipped: the cases are
  57003. // if a left edge mates with a left or bottom edge on the neighbor
  57004. // if a top edge mates with a top or right edge on the neighbor
  57005. // if a right edge mates with a right or top edge on the neighbor
  57006. // if a bottom edge mates with a bottom or left edge on the neighbor
  57007. //Seeing as the edges are enumerated as follows
  57008. // left =0
  57009. // right =1
  57010. // top =2
  57011. // bottom =3
  57012. //
  57013. // so if the edge enums are the same, or the sum of the enums == 3,
  57014. // the bbox needs to be flipped
  57015. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  57016. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  57017. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  57018. }
  57019. //The way the bounding box is extended onto the neighboring face
  57020. // depends on which edge of neighboring face abuts with this one
  57021. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  57022. case PMREMGenerator.CP_EDGE_LEFT:
  57023. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  57024. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  57025. break;
  57026. case PMREMGenerator.CP_EDGE_RIGHT:
  57027. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  57028. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  57029. break;
  57030. case PMREMGenerator.CP_EDGE_TOP:
  57031. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  57032. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  57033. break;
  57034. case PMREMGenerator.CP_EDGE_BOTTOM:
  57035. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  57036. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  57037. break;
  57038. }
  57039. //clamp filter extents in non-center tap faces to remain within surface
  57040. filterExtents[neighborFace].clampMin(0, 0, 0);
  57041. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  57042. }
  57043. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  57044. // from the center tap face, then process the opposite face entirely for now.
  57045. //Note that the cases in which this happens, what usually happens is that
  57046. // more than one edge bleeds onto the opposite face, and the bounding box
  57047. // encompasses the entire cube map face.
  57048. if (bleedOverAmount[i] > srcSize) {
  57049. //determine opposite face
  57050. switch (faceIdx) {
  57051. case PMREMGenerator.CP_FACE_X_POS:
  57052. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  57053. break;
  57054. case PMREMGenerator.CP_FACE_X_NEG:
  57055. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  57056. break;
  57057. case PMREMGenerator.CP_FACE_Y_POS:
  57058. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  57059. break;
  57060. case PMREMGenerator.CP_FACE_Y_NEG:
  57061. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  57062. break;
  57063. case PMREMGenerator.CP_FACE_Z_POS:
  57064. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  57065. break;
  57066. case PMREMGenerator.CP_FACE_Z_NEG:
  57067. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  57068. break;
  57069. default:
  57070. break;
  57071. }
  57072. //just encompass entire face for now
  57073. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  57074. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  57075. }
  57076. }
  57077. };
  57078. //--------------------------------------------------------------------------------------
  57079. //ProcessFilterExtents
  57080. // Process bounding box in each cube face
  57081. //
  57082. //--------------------------------------------------------------------------------------
  57083. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  57084. //accumulators are 64-bit floats in order to have the precision needed
  57085. // over a summation of a large number of pixels
  57086. var dstAccum = [0, 0, 0, 0];
  57087. var weightAccum = 0;
  57088. var k = 0;
  57089. var nSrcChannels = this.numChannels;
  57090. // norm cube map and srcCubeMap have same face width
  57091. var faceWidth = srcSize;
  57092. //amount to add to pointer to move to next scanline in images
  57093. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  57094. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  57095. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  57096. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  57097. // iterate over cubefaces
  57098. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  57099. //if bbox is non empty
  57100. if (!filterExtents[iFaceIdx].empty()) {
  57101. var uStart = filterExtents[iFaceIdx].min.x;
  57102. var vStart = filterExtents[iFaceIdx].min.y;
  57103. var uEnd = filterExtents[iFaceIdx].max.x;
  57104. var vEnd = filterExtents[iFaceIdx].max.y;
  57105. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  57106. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  57107. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  57108. for (var v = vStart; v <= vEnd; v++) {
  57109. var normCubeRowWalk = 0;
  57110. var srcCubeRowWalk = 0;
  57111. for (var u = uStart; u <= uEnd; u++) {
  57112. //pointer to direction in cube map associated with texel
  57113. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  57114. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  57115. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  57116. //check dot product to see if texel is within cone
  57117. var tapDotProd = texelVectX * centerTapDir.x +
  57118. texelVectY * centerTapDir.y +
  57119. texelVectZ * centerTapDir.z;
  57120. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  57121. //solid angle stored in 4th channel of normalizer/solid angle cube map
  57122. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  57123. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  57124. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  57125. // so just adding one to specularpower do the trick.
  57126. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  57127. //iterate over channels
  57128. for (k = 0; k < nSrcChannels; k++) {
  57129. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  57130. srcCubeRowWalk++;
  57131. }
  57132. weightAccum += weight; //accumulate weight
  57133. }
  57134. else {
  57135. //step across source pixel
  57136. srcCubeRowWalk += nSrcChannels;
  57137. }
  57138. normCubeRowWalk += 4; // 4 channels per norm cube map.
  57139. }
  57140. startIndexNormCubeMap += normCubePitch;
  57141. startIndexSrcCubeMap += srcCubePitch;
  57142. }
  57143. }
  57144. }
  57145. //divide through by weights if weight is non zero
  57146. if (weightAccum != 0.0) {
  57147. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  57148. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  57149. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  57150. if (this.numChannels > 3) {
  57151. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  57152. }
  57153. }
  57154. else {
  57155. // otherwise sample nearest
  57156. // get face idx and u, v texel coordinate in face
  57157. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  57158. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  57159. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  57160. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  57161. if (this.numChannels > 3) {
  57162. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  57163. }
  57164. }
  57165. return PMREMGenerator._vectorTemp;
  57166. };
  57167. //--------------------------------------------------------------------------------------
  57168. // Fixup cube edges
  57169. //
  57170. // average texels on cube map faces across the edges
  57171. // WARP/BENT Method Only.
  57172. //--------------------------------------------------------------------------------------
  57173. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  57174. var k;
  57175. var j;
  57176. var i;
  57177. var iFace;
  57178. var iCorner = 0;
  57179. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  57180. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  57181. // note that if functionality to filter across the three texels for each corner, then
  57182. //indexed by corner and face idx. the array contains the face the start points belongs to.
  57183. var cornerPtr = [
  57184. [[], [], []],
  57185. [[], [], []],
  57186. [[], [], []],
  57187. [[], [], []],
  57188. [[], [], []],
  57189. [[], [], []],
  57190. [[], [], []],
  57191. [[], [], []]
  57192. ];
  57193. //if there is no fixup, or fixup width = 0, do nothing
  57194. if (cubeMapSize < 1) {
  57195. return;
  57196. }
  57197. //special case 1x1 cubemap, average face colors
  57198. if (cubeMapSize == 1) {
  57199. //iterate over channels
  57200. for (k = 0; k < this.numChannels; k++) {
  57201. var accum = 0.0;
  57202. //iterate over faces to accumulate face colors
  57203. for (iFace = 0; iFace < 6; iFace++) {
  57204. accum += cubeMap[iFace][k];
  57205. }
  57206. //compute average over 6 face colors
  57207. accum /= 6.0;
  57208. //iterate over faces to distribute face colors
  57209. for (iFace = 0; iFace < 6; iFace++) {
  57210. cubeMap[iFace][k] = accum;
  57211. }
  57212. }
  57213. return;
  57214. }
  57215. //iterate over faces to collect list of corner texel pointers
  57216. for (iFace = 0; iFace < 6; iFace++) {
  57217. //the 4 corner pointers for this face
  57218. faceCornerStartIndicies[0] = [iFace, 0];
  57219. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  57220. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  57221. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  57222. //iterate over face corners to collect cube corner pointers
  57223. for (iCorner = 0; iCorner < 4; iCorner++) {
  57224. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  57225. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  57226. cornerNumPtrs[corner]++;
  57227. }
  57228. }
  57229. //iterate over corners to average across corner tap values
  57230. for (iCorner = 0; iCorner < 8; iCorner++) {
  57231. for (k = 0; k < this.numChannels; k++) {
  57232. var cornerTapAccum = 0.0;
  57233. //iterate over corner texels and average results
  57234. for (i = 0; i < 3; i++) {
  57235. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  57236. }
  57237. //divide by 3 to compute average of corner tap values
  57238. cornerTapAccum *= (1.0 / 3.0);
  57239. //iterate over corner texels and average results
  57240. for (i = 0; i < 3; i++) {
  57241. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  57242. }
  57243. }
  57244. }
  57245. //iterate over the twelve edges of the cube to average across edges
  57246. for (i = 0; i < 12; i++) {
  57247. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  57248. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  57249. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  57250. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  57251. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  57252. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  57253. var edgeWalk = 0;
  57254. var neighborEdgeWalk = 0;
  57255. //Determine walking pointers based on edge type
  57256. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  57257. switch (edge) {
  57258. case PMREMGenerator.CP_EDGE_LEFT:
  57259. // no change to faceEdgeStartPtr
  57260. edgeWalk = this.numChannels * cubeMapSize;
  57261. break;
  57262. case PMREMGenerator.CP_EDGE_RIGHT:
  57263. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  57264. edgeWalk = this.numChannels * cubeMapSize;
  57265. break;
  57266. case PMREMGenerator.CP_EDGE_TOP:
  57267. // no change to faceEdgeStartPtr
  57268. edgeWalk = this.numChannels;
  57269. break;
  57270. case PMREMGenerator.CP_EDGE_BOTTOM:
  57271. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  57272. edgeWalk = this.numChannels;
  57273. break;
  57274. }
  57275. //For certain types of edge abutments, the neighbor edge walk needs to
  57276. // be flipped: the cases are
  57277. // if a left edge mates with a left or bottom edge on the neighbor
  57278. // if a top edge mates with a top or right edge on the neighbor
  57279. // if a right edge mates with a right or top edge on the neighbor
  57280. // if a bottom edge mates with a bottom or left edge on the neighbor
  57281. //Seeing as the edges are enumerated as follows
  57282. // left =0
  57283. // right =1
  57284. // top =2
  57285. // bottom =3
  57286. //
  57287. //If the edge enums are the same, or the sum of the enums == 3,
  57288. // the neighbor edge walk needs to be flipped
  57289. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  57290. switch (neighborEdge) {
  57291. case PMREMGenerator.CP_EDGE_LEFT:
  57292. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  57293. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  57294. break;
  57295. case PMREMGenerator.CP_EDGE_RIGHT:
  57296. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  57297. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  57298. break;
  57299. case PMREMGenerator.CP_EDGE_TOP:
  57300. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  57301. neighborEdgeWalk = -this.numChannels;
  57302. break;
  57303. case PMREMGenerator.CP_EDGE_BOTTOM:
  57304. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  57305. neighborEdgeWalk = -this.numChannels;
  57306. break;
  57307. }
  57308. }
  57309. else {
  57310. //swapped direction neighbor edge walk
  57311. switch (neighborEdge) {
  57312. case PMREMGenerator.CP_EDGE_LEFT:
  57313. //no change to neighborEdgeStartPtr for this case since it points
  57314. // to the upper left corner already
  57315. neighborEdgeWalk = this.numChannels * cubeMapSize;
  57316. break;
  57317. case PMREMGenerator.CP_EDGE_RIGHT:
  57318. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  57319. neighborEdgeWalk = this.numChannels * cubeMapSize;
  57320. break;
  57321. case PMREMGenerator.CP_EDGE_TOP:
  57322. //no change to neighborEdgeStartPtr for this case since it points
  57323. // to the upper left corner already
  57324. neighborEdgeWalk = this.numChannels;
  57325. break;
  57326. case PMREMGenerator.CP_EDGE_BOTTOM:
  57327. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  57328. neighborEdgeWalk = this.numChannels;
  57329. break;
  57330. }
  57331. }
  57332. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  57333. //nearby neighborhood
  57334. //step ahead one texel on edge
  57335. edgeStartIndex += edgeWalk;
  57336. neighborEdgeStartIndex += neighborEdgeWalk;
  57337. // note that this loop does not process the corner texels, since they have already been
  57338. // averaged across faces across earlier
  57339. for (j = 1; j < (cubeMapSize - 1); j++) {
  57340. //for each set of taps along edge, average them
  57341. // and rewrite the results into the edges
  57342. for (k = 0; k < this.numChannels; k++) {
  57343. var edgeTap = cubeMap[face][edgeStartIndex + k];
  57344. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  57345. //compute average of tap intensity values
  57346. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  57347. //propagate average of taps to edge taps
  57348. cubeMap[face][edgeStartIndex + k] = avgTap;
  57349. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  57350. }
  57351. edgeStartIndex += edgeWalk;
  57352. neighborEdgeStartIndex += neighborEdgeWalk;
  57353. }
  57354. }
  57355. };
  57356. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  57357. PMREMGenerator.CP_UDIR = 0;
  57358. PMREMGenerator.CP_VDIR = 1;
  57359. PMREMGenerator.CP_FACEAXIS = 2;
  57360. //used to index cube faces
  57361. PMREMGenerator.CP_FACE_X_POS = 0;
  57362. PMREMGenerator.CP_FACE_X_NEG = 1;
  57363. PMREMGenerator.CP_FACE_Y_POS = 2;
  57364. PMREMGenerator.CP_FACE_Y_NEG = 3;
  57365. PMREMGenerator.CP_FACE_Z_POS = 4;
  57366. PMREMGenerator.CP_FACE_Z_NEG = 5;
  57367. //used to index image edges
  57368. // NOTE.. the actual number corresponding to the edge is important
  57369. // do not change these, or the code will break
  57370. //
  57371. // CP_EDGE_LEFT is u = 0
  57372. // CP_EDGE_RIGHT is u = width-1
  57373. // CP_EDGE_TOP is v = 0
  57374. // CP_EDGE_BOTTOM is v = height-1
  57375. PMREMGenerator.CP_EDGE_LEFT = 0;
  57376. PMREMGenerator.CP_EDGE_RIGHT = 1;
  57377. PMREMGenerator.CP_EDGE_TOP = 2;
  57378. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  57379. //corners of CUBE map (P or N specifys if it corresponds to the
  57380. // positive or negative direction each of X, Y, and Z
  57381. PMREMGenerator.CP_CORNER_NNN = 0;
  57382. PMREMGenerator.CP_CORNER_NNP = 1;
  57383. PMREMGenerator.CP_CORNER_NPN = 2;
  57384. PMREMGenerator.CP_CORNER_NPP = 3;
  57385. PMREMGenerator.CP_CORNER_PNN = 4;
  57386. PMREMGenerator.CP_CORNER_PNP = 5;
  57387. PMREMGenerator.CP_CORNER_PPN = 6;
  57388. PMREMGenerator.CP_CORNER_PPP = 7;
  57389. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  57390. //3x2 matrices that map cube map indexing vectors in 3d
  57391. // (after face selection and divide through by the
  57392. // _ABSOLUTE VALUE_ of the max coord)
  57393. // into NVC space
  57394. //Note this currently assumes the D3D cube face ordering and orientation
  57395. PMREMGenerator._sgFace2DMapping = [
  57396. //XPOS face
  57397. [[0, 0, -1],
  57398. [0, -1, 0],
  57399. [1, 0, 0]],
  57400. //XNEG face
  57401. [[0, 0, 1],
  57402. [0, -1, 0],
  57403. [-1, 0, 0]],
  57404. //YPOS face
  57405. [[1, 0, 0],
  57406. [0, 0, 1],
  57407. [0, 1, 0]],
  57408. //YNEG face
  57409. [[1, 0, 0],
  57410. [0, 0, -1],
  57411. [0, -1, 0]],
  57412. //ZPOS face
  57413. [[1, 0, 0],
  57414. [0, -1, 0],
  57415. [0, 0, 1]],
  57416. //ZNEG face
  57417. [[-1, 0, 0],
  57418. [0, -1, 0],
  57419. [0, 0, -1]],
  57420. ];
  57421. //------------------------------------------------------------------------------
  57422. // D3D cube map face specification
  57423. // mapping from 3D x,y,z cube map lookup coordinates
  57424. // to 2D within face u,v coordinates
  57425. //
  57426. // --------------------> U direction
  57427. // | (within-face texture space)
  57428. // | _____
  57429. // | | |
  57430. // | | +Y |
  57431. // | _____|_____|_____ _____
  57432. // | | | | | |
  57433. // | | -X | +Z | +X | -Z |
  57434. // | |_____|_____|_____|_____|
  57435. // | | |
  57436. // | | -Y |
  57437. // | |_____|
  57438. // |
  57439. // v V direction
  57440. // (within-face texture space)
  57441. //------------------------------------------------------------------------------
  57442. //Information about neighbors and how texture coorrdinates change across faces
  57443. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  57444. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  57445. //Note this currently assumes the D3D cube face ordering and orientation
  57446. PMREMGenerator._sgCubeNgh = [
  57447. //XPOS face
  57448. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  57449. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  57450. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  57451. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  57452. //XNEG face
  57453. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  57454. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  57455. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  57456. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  57457. //YPOS face
  57458. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  57459. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  57460. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  57461. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  57462. //YNEG face
  57463. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  57464. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57465. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57466. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  57467. //ZPOS face
  57468. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  57469. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  57470. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57471. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  57472. //ZNEG face
  57473. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  57474. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  57475. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  57476. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  57477. ];
  57478. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  57479. // this table is used to average over the edges.
  57480. PMREMGenerator._sgCubeEdgeList = [
  57481. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  57482. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  57483. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  57484. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57485. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  57486. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  57487. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  57488. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  57489. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  57490. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57491. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  57492. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  57493. ];
  57494. //Information about which of the 8 cube corners are correspond to the
  57495. // the 4 corners in each cube face
  57496. // the order is upper left, upper right, lower left, lower right
  57497. PMREMGenerator._sgCubeCornerList = [
  57498. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  57499. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  57500. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  57501. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  57502. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  57503. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  57504. ];
  57505. return PMREMGenerator;
  57506. }());
  57507. Internals.PMREMGenerator = PMREMGenerator;
  57508. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57509. })(BABYLON || (BABYLON = {}));
  57510. var BABYLON;
  57511. (function (BABYLON) {
  57512. /**
  57513. * This represents a texture coming from an HDR input.
  57514. *
  57515. * The only supported format is currently panorama picture stored in RGBE format.
  57516. * Example of such files can be found on HDRLib: http://hdrlib.com/
  57517. */
  57518. var HDRCubeTexture = (function (_super) {
  57519. __extends(HDRCubeTexture, _super);
  57520. /**
  57521. * Instantiates an HDRTexture from the following parameters.
  57522. *
  57523. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  57524. * @param scene The scene the texture will be used in
  57525. * @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.
  57526. * @param noMipmap Forces to not generate the mipmap if true
  57527. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  57528. * @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)
  57529. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  57530. */
  57531. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  57532. if (noMipmap === void 0) { noMipmap = false; }
  57533. if (generateHarmonics === void 0) { generateHarmonics = true; }
  57534. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  57535. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  57536. _super.call(this, scene);
  57537. this._useInGammaSpace = false;
  57538. this._generateHarmonics = true;
  57539. this._isBABYLONPreprocessed = false;
  57540. /**
  57541. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  57542. */
  57543. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57544. /**
  57545. * The spherical polynomial data extracted from the texture.
  57546. */
  57547. this.sphericalPolynomial = null;
  57548. /**
  57549. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  57550. * This is usefull at run time to apply the good shader.
  57551. */
  57552. this.isPMREM = false;
  57553. if (!url) {
  57554. return;
  57555. }
  57556. this.name = url;
  57557. this.url = url;
  57558. this.hasAlpha = false;
  57559. this.isCube = true;
  57560. this._textureMatrix = BABYLON.Matrix.Identity();
  57561. if (size) {
  57562. this._isBABYLONPreprocessed = false;
  57563. this._noMipmap = noMipmap;
  57564. this._size = size;
  57565. this._useInGammaSpace = useInGammaSpace;
  57566. this._usePMREMGenerator = usePMREMGenerator &&
  57567. scene.getEngine().getCaps().textureLOD &&
  57568. this.getScene().getEngine().getCaps().textureFloat &&
  57569. !this._useInGammaSpace;
  57570. }
  57571. else {
  57572. this._isBABYLONPreprocessed = true;
  57573. this._noMipmap = false;
  57574. this._useInGammaSpace = false;
  57575. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  57576. this.getScene().getEngine().getCaps().textureFloat &&
  57577. !this._useInGammaSpace;
  57578. }
  57579. this.isPMREM = this._usePMREMGenerator;
  57580. this._texture = this._getFromCache(url, this._noMipmap);
  57581. if (!this._texture) {
  57582. if (!scene.useDelayedTextureLoading) {
  57583. this.loadTexture();
  57584. }
  57585. else {
  57586. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57587. }
  57588. }
  57589. }
  57590. /**
  57591. * Occurs when the file is a preprocessed .babylon.hdr file.
  57592. */
  57593. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  57594. var _this = this;
  57595. var mipLevels = 0;
  57596. var floatArrayView = null;
  57597. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  57598. var mips = [];
  57599. var startIndex = 30;
  57600. for (var level = 0; level < mipLevels; level++) {
  57601. mips.push([]);
  57602. // Fill each pixel of the mip level.
  57603. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  57604. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57605. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  57606. mips[level].push(faceData);
  57607. startIndex += faceSize;
  57608. }
  57609. }
  57610. return mips;
  57611. } : null;
  57612. var callback = function (buffer) {
  57613. // Create Native Array Views
  57614. var intArrayView = new Int32Array(buffer);
  57615. floatArrayView = new Float32Array(buffer);
  57616. // Fill header.
  57617. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  57618. _this._size = intArrayView[1]; // CubeMap max mip face size.
  57619. // Update Texture Information.
  57620. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  57621. // Fill polynomial information.
  57622. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  57623. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  57624. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  57625. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  57626. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  57627. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  57628. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  57629. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  57630. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  57631. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  57632. // Fill pixel data.
  57633. mipLevels = intArrayView[29]; // Number of mip levels.
  57634. var startIndex = 30;
  57635. var data = [];
  57636. var faceSize = Math.pow(_this._size, 2) * 3;
  57637. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57638. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  57639. startIndex += faceSize;
  57640. }
  57641. var results = [];
  57642. var byteArray = null;
  57643. // Push each faces.
  57644. for (var k = 0; k < 6; k++) {
  57645. var dataFace = null;
  57646. // If special cases.
  57647. if (!mipmapGenerator) {
  57648. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  57649. dataFace = data[j];
  57650. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  57651. // 3 channels of 1 bytes per pixel in bytes.
  57652. var byteBuffer = new ArrayBuffer(faceSize);
  57653. byteArray = new Uint8Array(byteBuffer);
  57654. }
  57655. for (var i = 0; i < _this._size * _this._size; i++) {
  57656. // Put in gamma space if requested.
  57657. if (_this._useInGammaSpace) {
  57658. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  57659. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  57660. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  57661. }
  57662. // Convert to int texture for fallback.
  57663. if (byteArray) {
  57664. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  57665. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  57666. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  57667. // May use luminance instead if the result is not accurate.
  57668. var max = Math.max(Math.max(r, g), b);
  57669. if (max > 255) {
  57670. var scale = 255 / max;
  57671. r *= scale;
  57672. g *= scale;
  57673. b *= scale;
  57674. }
  57675. byteArray[(i * 3) + 0] = r;
  57676. byteArray[(i * 3) + 1] = g;
  57677. byteArray[(i * 3) + 2] = b;
  57678. }
  57679. }
  57680. }
  57681. else {
  57682. dataFace = data[k];
  57683. }
  57684. // Fill the array accordingly.
  57685. if (byteArray) {
  57686. results.push(byteArray);
  57687. }
  57688. else {
  57689. results.push(dataFace);
  57690. }
  57691. }
  57692. return results;
  57693. };
  57694. 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);
  57695. };
  57696. /**
  57697. * Occurs when the file is raw .hdr file.
  57698. */
  57699. HDRCubeTexture.prototype.loadHDRTexture = function () {
  57700. var _this = this;
  57701. var callback = function (buffer) {
  57702. // Extract the raw linear data.
  57703. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  57704. // Generate harmonics if needed.
  57705. if (_this._generateHarmonics) {
  57706. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  57707. }
  57708. var results = [];
  57709. var byteArray = null;
  57710. // Push each faces.
  57711. for (var j = 0; j < 6; j++) {
  57712. // Create uintarray fallback.
  57713. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  57714. // 3 channels of 1 bytes per pixel in bytes.
  57715. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  57716. byteArray = new Uint8Array(byteBuffer);
  57717. }
  57718. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  57719. // If special cases.
  57720. if (_this._useInGammaSpace || byteArray) {
  57721. for (var i = 0; i < _this._size * _this._size; i++) {
  57722. // Put in gamma space if requested.
  57723. if (_this._useInGammaSpace) {
  57724. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  57725. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  57726. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  57727. }
  57728. // Convert to int texture for fallback.
  57729. if (byteArray) {
  57730. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  57731. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  57732. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  57733. // May use luminance instead if the result is not accurate.
  57734. var max = Math.max(Math.max(r, g), b);
  57735. if (max > 255) {
  57736. var scale = 255 / max;
  57737. r *= scale;
  57738. g *= scale;
  57739. b *= scale;
  57740. }
  57741. byteArray[(i * 3) + 0] = r;
  57742. byteArray[(i * 3) + 1] = g;
  57743. byteArray[(i * 3) + 2] = b;
  57744. }
  57745. }
  57746. }
  57747. if (byteArray) {
  57748. results.push(byteArray);
  57749. }
  57750. else {
  57751. results.push(dataFace);
  57752. }
  57753. }
  57754. return results;
  57755. };
  57756. var mipmapGenerator = null;
  57757. if (!this._noMipmap &&
  57758. this._usePMREMGenerator) {
  57759. mipmapGenerator = function (data) {
  57760. // Custom setup of the generator matching with the PBR shader values.
  57761. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  57762. return generator.filterCubeMap();
  57763. };
  57764. }
  57765. 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);
  57766. };
  57767. /**
  57768. * Starts the loading process of the texture.
  57769. */
  57770. HDRCubeTexture.prototype.loadTexture = function () {
  57771. if (this._isBABYLONPreprocessed) {
  57772. this.loadBabylonTexture();
  57773. }
  57774. else {
  57775. this.loadHDRTexture();
  57776. }
  57777. };
  57778. HDRCubeTexture.prototype.clone = function () {
  57779. var size = this._isBABYLONPreprocessed ? null : this._size;
  57780. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  57781. // Base texture
  57782. newTexture.level = this.level;
  57783. newTexture.wrapU = this.wrapU;
  57784. newTexture.wrapV = this.wrapV;
  57785. newTexture.coordinatesIndex = this.coordinatesIndex;
  57786. newTexture.coordinatesMode = this.coordinatesMode;
  57787. return newTexture;
  57788. };
  57789. // Methods
  57790. HDRCubeTexture.prototype.delayLoad = function () {
  57791. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57792. return;
  57793. }
  57794. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57795. this._texture = this._getFromCache(this.url, this._noMipmap);
  57796. if (!this._texture) {
  57797. this.loadTexture();
  57798. }
  57799. };
  57800. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  57801. return this._textureMatrix;
  57802. };
  57803. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57804. var texture = null;
  57805. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  57806. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  57807. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  57808. texture.name = parsedTexture.name;
  57809. texture.hasAlpha = parsedTexture.hasAlpha;
  57810. texture.level = parsedTexture.level;
  57811. texture.coordinatesMode = parsedTexture.coordinatesMode;
  57812. }
  57813. return texture;
  57814. };
  57815. HDRCubeTexture.prototype.serialize = function () {
  57816. if (!this.name) {
  57817. return null;
  57818. }
  57819. var serializationObject = {};
  57820. serializationObject.name = this.name;
  57821. serializationObject.hasAlpha = this.hasAlpha;
  57822. serializationObject.isCube = true;
  57823. serializationObject.level = this.level;
  57824. serializationObject.size = this._size;
  57825. serializationObject.coordinatesMode = this.coordinatesMode;
  57826. serializationObject.useInGammaSpace = this._useInGammaSpace;
  57827. serializationObject.generateHarmonics = this._generateHarmonics;
  57828. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  57829. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  57830. return serializationObject;
  57831. };
  57832. /**
  57833. * Saves as a file the data contained in the texture in a binary format.
  57834. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  57835. * as the spherical used in the lighting.
  57836. * @param url The HDR file url.
  57837. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  57838. * @param onError Method called if any error happens during download.
  57839. * @return The packed binary data.
  57840. */
  57841. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  57842. if (onError === void 0) { onError = null; }
  57843. var callback = function (buffer) {
  57844. var data = new Blob([buffer], { type: 'application/octet-stream' });
  57845. // Returns a URL you can use as a href.
  57846. var objUrl = window.URL.createObjectURL(data);
  57847. // Simulates a link to it and click to dowload.
  57848. var a = document.createElement("a");
  57849. document.body.appendChild(a);
  57850. a.style.display = "none";
  57851. a.href = objUrl;
  57852. a.download = "envmap.babylon.hdr";
  57853. a.click();
  57854. };
  57855. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  57856. };
  57857. /**
  57858. * Serializes the data contained in the texture in a binary format.
  57859. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  57860. * as the spherical used in the lighting.
  57861. * @param url The HDR file url.
  57862. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  57863. * @param onError Method called if any error happens during download.
  57864. * @return The packed binary data.
  57865. */
  57866. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  57867. if (onError === void 0) { onError = null; }
  57868. // Needs the url tho create the texture.
  57869. if (!url) {
  57870. return null;
  57871. }
  57872. // Check Power of two size.
  57873. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  57874. return null;
  57875. }
  57876. var getDataCallback = function (dataBuffer) {
  57877. // Extract the raw linear data.
  57878. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  57879. // Generate harmonics if needed.
  57880. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  57881. // Generate seamless faces
  57882. var mipGeneratorArray = [];
  57883. // Data are known to be in +X +Y +Z -X -Y -Z
  57884. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  57885. mipGeneratorArray.push(cubeData.right); // +X
  57886. mipGeneratorArray.push(cubeData.left); // -X
  57887. mipGeneratorArray.push(cubeData.up); // +Y
  57888. mipGeneratorArray.push(cubeData.down); // -Y
  57889. mipGeneratorArray.push(cubeData.front); // +Z
  57890. mipGeneratorArray.push(cubeData.back); // -Z
  57891. // Custom setup of the generator matching with the PBR shader values.
  57892. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  57893. var mippedData = generator.filterCubeMap();
  57894. // Compute required byte length.
  57895. var byteLength = 1 * 4; // Raw Data Version int32.
  57896. byteLength += 4; // CubeMap max mip face size int32.
  57897. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  57898. // Add data size.
  57899. byteLength += 4; // Number of mip levels int32.
  57900. for (var level = 0; level < mippedData.length; level++) {
  57901. var mipSize = size >> level;
  57902. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  57903. }
  57904. // Prepare binary structure.
  57905. var buffer = new ArrayBuffer(byteLength);
  57906. var intArrayView = new Int32Array(buffer);
  57907. var floatArrayView = new Float32Array(buffer);
  57908. // Fill header.
  57909. intArrayView[0] = 1; // Version 1.
  57910. intArrayView[1] = size; // CubeMap max mip face size.
  57911. // Fill polynomial information.
  57912. sphericalPolynomial.x.toArray(floatArrayView, 2);
  57913. sphericalPolynomial.y.toArray(floatArrayView, 5);
  57914. sphericalPolynomial.z.toArray(floatArrayView, 8);
  57915. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  57916. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  57917. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  57918. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  57919. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  57920. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  57921. // Fill pixel data.
  57922. intArrayView[29] = mippedData.length; // Number of mip levels.
  57923. var startIndex = 30;
  57924. for (var level = 0; level < mippedData.length; level++) {
  57925. // Fill each pixel of the mip level.
  57926. var faceSize = Math.pow(size >> level, 2) * 3;
  57927. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57928. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  57929. startIndex += faceSize;
  57930. }
  57931. }
  57932. // Callback.
  57933. callback(buffer);
  57934. };
  57935. // Download and process.
  57936. BABYLON.Tools.LoadFile(url, function (data) {
  57937. getDataCallback(data);
  57938. }, null, null, true, onError);
  57939. };
  57940. HDRCubeTexture._facesMapping = [
  57941. "right",
  57942. "up",
  57943. "front",
  57944. "left",
  57945. "down",
  57946. "back"
  57947. ];
  57948. return HDRCubeTexture;
  57949. }(BABYLON.BaseTexture));
  57950. BABYLON.HDRCubeTexture = HDRCubeTexture;
  57951. })(BABYLON || (BABYLON = {}));
  57952. var BABYLON;
  57953. (function (BABYLON) {
  57954. var Debug;
  57955. (function (Debug) {
  57956. /**
  57957. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  57958. */
  57959. var SkeletonViewer = (function () {
  57960. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  57961. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  57962. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  57963. this.skeleton = skeleton;
  57964. this.mesh = mesh;
  57965. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  57966. this.renderingGroupId = renderingGroupId;
  57967. this.color = BABYLON.Color3.White();
  57968. this._debugLines = [];
  57969. this._isEnabled = false;
  57970. this._scene = scene;
  57971. this.update();
  57972. this._renderFunction = this.update.bind(this);
  57973. }
  57974. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  57975. get: function () {
  57976. return this._isEnabled;
  57977. },
  57978. set: function (value) {
  57979. if (this._isEnabled === value) {
  57980. return;
  57981. }
  57982. this._isEnabled = value;
  57983. if (value) {
  57984. this._scene.registerBeforeRender(this._renderFunction);
  57985. }
  57986. else {
  57987. this._scene.unregisterBeforeRender(this._renderFunction);
  57988. }
  57989. },
  57990. enumerable: true,
  57991. configurable: true
  57992. });
  57993. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  57994. if (x === void 0) { x = 0; }
  57995. if (y === void 0) { y = 0; }
  57996. if (z === void 0) { z = 0; }
  57997. var tmat = BABYLON.Tmp.Matrix[0];
  57998. var parentBone = bone.getParent();
  57999. tmat.copyFrom(bone.getLocalMatrix());
  58000. if (x !== 0 || y !== 0 || z !== 0) {
  58001. var tmat2 = BABYLON.Tmp.Matrix[1];
  58002. BABYLON.Matrix.IdentityToRef(tmat2);
  58003. tmat2.m[12] = x;
  58004. tmat2.m[13] = y;
  58005. tmat2.m[14] = z;
  58006. tmat2.multiplyToRef(tmat, tmat);
  58007. }
  58008. if (parentBone) {
  58009. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  58010. }
  58011. tmat.multiplyToRef(meshMat, tmat);
  58012. position.x = tmat.m[12];
  58013. position.y = tmat.m[13];
  58014. position.z = tmat.m[14];
  58015. };
  58016. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  58017. var len = bones.length;
  58018. for (var i = 0; i < len; i++) {
  58019. var bone = bones[i];
  58020. var points = this._debugLines[i];
  58021. if (!points) {
  58022. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58023. this._debugLines[i] = points;
  58024. }
  58025. this._getBonePosition(points[0], bone, meshMat);
  58026. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  58027. }
  58028. };
  58029. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  58030. var len = bones.length;
  58031. var boneNum = 0;
  58032. for (var i = len - 1; i >= 0; i--) {
  58033. var childBone = bones[i];
  58034. var parentBone = childBone.getParent();
  58035. if (!parentBone) {
  58036. continue;
  58037. }
  58038. var points = this._debugLines[boneNum];
  58039. if (!points) {
  58040. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58041. this._debugLines[boneNum] = points;
  58042. }
  58043. this._getBonePosition(points[0], childBone, meshMat);
  58044. this._getBonePosition(points[1], parentBone, meshMat);
  58045. boneNum++;
  58046. }
  58047. };
  58048. SkeletonViewer.prototype.update = function () {
  58049. if (this.autoUpdateBonesMatrices) {
  58050. this._updateBoneMatrix(this.skeleton.bones[0]);
  58051. }
  58052. if (this.skeleton.bones[0].length === undefined) {
  58053. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58054. }
  58055. else {
  58056. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58057. }
  58058. if (!this._debugMesh) {
  58059. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  58060. this._debugMesh.renderingGroupId = this.renderingGroupId;
  58061. }
  58062. else {
  58063. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  58064. }
  58065. this._debugMesh.color = this.color;
  58066. };
  58067. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  58068. if (bone.getParent()) {
  58069. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  58070. }
  58071. var children = bone.children;
  58072. var len = children.length;
  58073. for (var i = 0; i < len; i++) {
  58074. this._updateBoneMatrix(children[i]);
  58075. }
  58076. };
  58077. SkeletonViewer.prototype.dispose = function () {
  58078. if (this._debugMesh) {
  58079. this.isEnabled = false;
  58080. this._debugMesh.dispose();
  58081. this._debugMesh = null;
  58082. }
  58083. };
  58084. return SkeletonViewer;
  58085. }());
  58086. Debug.SkeletonViewer = SkeletonViewer;
  58087. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58088. })(BABYLON || (BABYLON = {}));
  58089. var BABYLON;
  58090. (function (BABYLON) {
  58091. /**
  58092. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  58093. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  58094. * 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;
  58095. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  58096. */
  58097. var ColorCurves = (function () {
  58098. function ColorCurves() {
  58099. this._dirty = true;
  58100. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  58101. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  58102. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  58103. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  58104. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  58105. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  58106. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  58107. this._globalHue = 30;
  58108. this._globalDensity = 0;
  58109. this._globalSaturation = 0;
  58110. this._globalExposure = 0;
  58111. this._highlightsHue = 30;
  58112. this._highlightsDensity = 0;
  58113. this._highlightsSaturation = 0;
  58114. this._highlightsExposure = 0;
  58115. this._midtonesHue = 30;
  58116. this._midtonesDensity = 0;
  58117. this._midtonesSaturation = 0;
  58118. this._midtonesExposure = 0;
  58119. this._shadowsHue = 30;
  58120. this._shadowsDensity = 0;
  58121. this._shadowsSaturation = 0;
  58122. this._shadowsExposure = 0;
  58123. }
  58124. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  58125. /**
  58126. * Gets the global Hue value.
  58127. * 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).
  58128. */
  58129. get: function () {
  58130. return this._globalHue;
  58131. },
  58132. /**
  58133. * Sets the global Hue value.
  58134. * 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).
  58135. */
  58136. set: function (value) {
  58137. this._globalHue = value;
  58138. this._dirty = true;
  58139. },
  58140. enumerable: true,
  58141. configurable: true
  58142. });
  58143. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  58144. /**
  58145. * Gets the global Density value.
  58146. * 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.
  58147. * Values less than zero provide a filter of opposite hue.
  58148. */
  58149. get: function () {
  58150. return this._globalDensity;
  58151. },
  58152. /**
  58153. * Sets the global Density value.
  58154. * 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.
  58155. * Values less than zero provide a filter of opposite hue.
  58156. */
  58157. set: function (value) {
  58158. this._globalDensity = value;
  58159. this._dirty = true;
  58160. },
  58161. enumerable: true,
  58162. configurable: true
  58163. });
  58164. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  58165. /**
  58166. * Gets the global Saturation value.
  58167. * 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.
  58168. */
  58169. get: function () {
  58170. return this._globalSaturation;
  58171. },
  58172. /**
  58173. * Sets the global Saturation value.
  58174. * 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.
  58175. */
  58176. set: function (value) {
  58177. this._globalSaturation = value;
  58178. this._dirty = true;
  58179. },
  58180. enumerable: true,
  58181. configurable: true
  58182. });
  58183. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  58184. /**
  58185. * Gets the highlights Hue value.
  58186. * 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).
  58187. */
  58188. get: function () {
  58189. return this._highlightsHue;
  58190. },
  58191. /**
  58192. * Sets the highlights Hue value.
  58193. * 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).
  58194. */
  58195. set: function (value) {
  58196. this._highlightsHue = value;
  58197. this._dirty = true;
  58198. },
  58199. enumerable: true,
  58200. configurable: true
  58201. });
  58202. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  58203. /**
  58204. * Gets the highlights Density value.
  58205. * 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.
  58206. * Values less than zero provide a filter of opposite hue.
  58207. */
  58208. get: function () {
  58209. return this._highlightsDensity;
  58210. },
  58211. /**
  58212. * Sets the highlights Density value.
  58213. * 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.
  58214. * Values less than zero provide a filter of opposite hue.
  58215. */
  58216. set: function (value) {
  58217. this._highlightsDensity = value;
  58218. this._dirty = true;
  58219. },
  58220. enumerable: true,
  58221. configurable: true
  58222. });
  58223. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  58224. /**
  58225. * Gets the highlights Saturation value.
  58226. * 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.
  58227. */
  58228. get: function () {
  58229. return this._highlightsSaturation;
  58230. },
  58231. /**
  58232. * Sets the highlights Saturation value.
  58233. * 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.
  58234. */
  58235. set: function (value) {
  58236. this._highlightsSaturation = value;
  58237. this._dirty = true;
  58238. },
  58239. enumerable: true,
  58240. configurable: true
  58241. });
  58242. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  58243. /**
  58244. * Gets the highlights Exposure value.
  58245. * 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.
  58246. */
  58247. get: function () {
  58248. return this._highlightsExposure;
  58249. },
  58250. /**
  58251. * Sets the highlights Exposure value.
  58252. * 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.
  58253. */
  58254. set: function (value) {
  58255. this._highlightsExposure = value;
  58256. this._dirty = true;
  58257. },
  58258. enumerable: true,
  58259. configurable: true
  58260. });
  58261. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  58262. /**
  58263. * Gets the midtones Hue value.
  58264. * 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).
  58265. */
  58266. get: function () {
  58267. return this._midtonesHue;
  58268. },
  58269. /**
  58270. * Sets the midtones Hue value.
  58271. * 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).
  58272. */
  58273. set: function (value) {
  58274. this._midtonesHue = value;
  58275. this._dirty = true;
  58276. },
  58277. enumerable: true,
  58278. configurable: true
  58279. });
  58280. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  58281. /**
  58282. * Gets the midtones Density value.
  58283. * 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.
  58284. * Values less than zero provide a filter of opposite hue.
  58285. */
  58286. get: function () {
  58287. return this._midtonesDensity;
  58288. },
  58289. /**
  58290. * Sets the midtones Density value.
  58291. * 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.
  58292. * Values less than zero provide a filter of opposite hue.
  58293. */
  58294. set: function (value) {
  58295. this._midtonesDensity = value;
  58296. this._dirty = true;
  58297. },
  58298. enumerable: true,
  58299. configurable: true
  58300. });
  58301. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  58302. /**
  58303. * Gets the midtones Saturation value.
  58304. * 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.
  58305. */
  58306. get: function () {
  58307. return this._midtonesSaturation;
  58308. },
  58309. /**
  58310. * Sets the midtones Saturation value.
  58311. * 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.
  58312. */
  58313. set: function (value) {
  58314. this._midtonesSaturation = value;
  58315. this._dirty = true;
  58316. },
  58317. enumerable: true,
  58318. configurable: true
  58319. });
  58320. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  58321. /**
  58322. * Gets the midtones Exposure value.
  58323. * 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.
  58324. */
  58325. get: function () {
  58326. return this._midtonesExposure;
  58327. },
  58328. /**
  58329. * Sets the midtones Exposure value.
  58330. * 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.
  58331. */
  58332. set: function (value) {
  58333. this._midtonesExposure = value;
  58334. this._dirty = true;
  58335. },
  58336. enumerable: true,
  58337. configurable: true
  58338. });
  58339. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  58340. /**
  58341. * Gets the shadows Hue value.
  58342. * 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).
  58343. */
  58344. get: function () {
  58345. return this._shadowsHue;
  58346. },
  58347. /**
  58348. * Sets the shadows Hue value.
  58349. * 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).
  58350. */
  58351. set: function (value) {
  58352. this._shadowsHue = value;
  58353. this._dirty = true;
  58354. },
  58355. enumerable: true,
  58356. configurable: true
  58357. });
  58358. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  58359. /**
  58360. * Gets the shadows Density value.
  58361. * 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.
  58362. * Values less than zero provide a filter of opposite hue.
  58363. */
  58364. get: function () {
  58365. return this._shadowsDensity;
  58366. },
  58367. /**
  58368. * Sets the shadows Density value.
  58369. * 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.
  58370. * Values less than zero provide a filter of opposite hue.
  58371. */
  58372. set: function (value) {
  58373. this._shadowsDensity = value;
  58374. this._dirty = true;
  58375. },
  58376. enumerable: true,
  58377. configurable: true
  58378. });
  58379. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  58380. /**
  58381. * Gets the shadows Saturation value.
  58382. * 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.
  58383. */
  58384. get: function () {
  58385. return this._shadowsSaturation;
  58386. },
  58387. /**
  58388. * Sets the shadows Saturation value.
  58389. * 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.
  58390. */
  58391. set: function (value) {
  58392. this._shadowsSaturation = value;
  58393. this._dirty = true;
  58394. },
  58395. enumerable: true,
  58396. configurable: true
  58397. });
  58398. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  58399. /**
  58400. * Gets the shadows Exposure value.
  58401. * 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.
  58402. */
  58403. get: function () {
  58404. return this._shadowsExposure;
  58405. },
  58406. /**
  58407. * Sets the shadows Exposure value.
  58408. * 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.
  58409. */
  58410. set: function (value) {
  58411. this._shadowsExposure = value;
  58412. this._dirty = true;
  58413. },
  58414. enumerable: true,
  58415. configurable: true
  58416. });
  58417. /**
  58418. * Binds the color curves to the shader.
  58419. * @param colorCurves The color curve to bind
  58420. * @param effect The effect to bind to
  58421. */
  58422. ColorCurves.Bind = function (colorCurves, effect) {
  58423. if (colorCurves._dirty) {
  58424. colorCurves._dirty = false;
  58425. // Fill in global info.
  58426. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  58427. // Compute highlights info.
  58428. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  58429. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  58430. // Compute midtones info.
  58431. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  58432. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  58433. // Compute shadows info.
  58434. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  58435. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  58436. // Compute deltas (neutral is midtones).
  58437. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  58438. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  58439. }
  58440. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  58441. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  58442. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  58443. };
  58444. /**
  58445. * Prepare the list of uniforms associated with the ColorCurves effects.
  58446. * @param uniformsList The list of uniforms used in the effect
  58447. */
  58448. ColorCurves.PrepareUniforms = function (uniformsList) {
  58449. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  58450. };
  58451. /**
  58452. * Returns color grading data based on a hue, density, saturation and exposure value.
  58453. * @param filterHue The hue of the color filter.
  58454. * @param filterDensity The density of the color filter.
  58455. * @param saturation The saturation.
  58456. * @param exposure The exposure.
  58457. * @param result The result data container.
  58458. */
  58459. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  58460. if (hue == null) {
  58461. return;
  58462. }
  58463. hue = ColorCurves.clamp(hue, 0, 360);
  58464. density = ColorCurves.clamp(density, -100, 100);
  58465. saturation = ColorCurves.clamp(saturation, -100, 100);
  58466. exposure = ColorCurves.clamp(exposure, -100, 100);
  58467. // Remap the slider/config filter density with non-linear mapping and also scale by half
  58468. // so that the maximum filter density is only 50% control. This provides fine control
  58469. // for small values and reasonable range.
  58470. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  58471. density *= 0.5;
  58472. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  58473. if (density < 0) {
  58474. density *= -1;
  58475. hue = (hue + 180) % 360;
  58476. }
  58477. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  58478. result.scaleToRef(2, result);
  58479. result.a = 1 + 0.01 * saturation;
  58480. };
  58481. /**
  58482. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  58483. * @param value The input slider value in range [-100,100].
  58484. * @returns Adjusted value.
  58485. */
  58486. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  58487. value /= 100;
  58488. var x = Math.abs(value);
  58489. x = Math.pow(x, 2);
  58490. if (value < 0) {
  58491. x *= -1;
  58492. }
  58493. x *= 100;
  58494. return x;
  58495. };
  58496. /**
  58497. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  58498. * @param hue The hue (H) input.
  58499. * @param saturation The saturation (S) input.
  58500. * @param brightness The brightness (B) input.
  58501. * @result An RGBA color represented as Vector4.
  58502. */
  58503. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  58504. var h = ColorCurves.clamp(hue, 0, 360);
  58505. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  58506. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  58507. if (s === 0) {
  58508. result.r = v;
  58509. result.g = v;
  58510. result.b = v;
  58511. }
  58512. else {
  58513. // sector 0 to 5
  58514. h /= 60;
  58515. var i = Math.floor(h);
  58516. // fractional part of h
  58517. var f = h - i;
  58518. var p = v * (1 - s);
  58519. var q = v * (1 - s * f);
  58520. var t = v * (1 - s * (1 - f));
  58521. switch (i) {
  58522. case 0:
  58523. result.r = v;
  58524. result.g = t;
  58525. result.b = p;
  58526. break;
  58527. case 1:
  58528. result.r = q;
  58529. result.g = v;
  58530. result.b = p;
  58531. break;
  58532. case 2:
  58533. result.r = p;
  58534. result.g = v;
  58535. result.b = t;
  58536. break;
  58537. case 3:
  58538. result.r = p;
  58539. result.g = q;
  58540. result.b = v;
  58541. break;
  58542. case 4:
  58543. result.r = t;
  58544. result.g = p;
  58545. result.b = v;
  58546. break;
  58547. default:
  58548. result.r = v;
  58549. result.g = p;
  58550. result.b = q;
  58551. break;
  58552. }
  58553. }
  58554. result.a = 1;
  58555. };
  58556. /**
  58557. * Returns a value clamped between min and max
  58558. * @param value The value to clamp
  58559. * @param min The minimum of value
  58560. * @param max The maximum of value
  58561. * @returns The clamped value.
  58562. */
  58563. ColorCurves.clamp = function (value, min, max) {
  58564. return Math.min(Math.max(value, min), max);
  58565. };
  58566. /**
  58567. * Clones the current color curve instance.
  58568. * @return The cloned curves
  58569. */
  58570. ColorCurves.prototype.clone = function () {
  58571. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  58572. };
  58573. /**
  58574. * Serializes the current color curve instance to a json representation.
  58575. * @return a JSON representation
  58576. */
  58577. ColorCurves.prototype.serialize = function () {
  58578. return BABYLON.SerializationHelper.Serialize(this);
  58579. };
  58580. /**
  58581. * Parses the color curve from a json representation.
  58582. * @param source the JSON source to parse
  58583. * @return The parsed curves
  58584. */
  58585. ColorCurves.Parse = function (source) {
  58586. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  58587. };
  58588. __decorate([
  58589. BABYLON.serialize()
  58590. ], ColorCurves.prototype, "_globalHue", void 0);
  58591. __decorate([
  58592. BABYLON.serialize()
  58593. ], ColorCurves.prototype, "_globalDensity", void 0);
  58594. __decorate([
  58595. BABYLON.serialize()
  58596. ], ColorCurves.prototype, "_globalSaturation", void 0);
  58597. __decorate([
  58598. BABYLON.serialize()
  58599. ], ColorCurves.prototype, "_globalExposure", void 0);
  58600. __decorate([
  58601. BABYLON.serialize()
  58602. ], ColorCurves.prototype, "_highlightsHue", void 0);
  58603. __decorate([
  58604. BABYLON.serialize()
  58605. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  58606. __decorate([
  58607. BABYLON.serialize()
  58608. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  58609. __decorate([
  58610. BABYLON.serialize()
  58611. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  58612. __decorate([
  58613. BABYLON.serialize()
  58614. ], ColorCurves.prototype, "_midtonesHue", void 0);
  58615. __decorate([
  58616. BABYLON.serialize()
  58617. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  58618. __decorate([
  58619. BABYLON.serialize()
  58620. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  58621. __decorate([
  58622. BABYLON.serialize()
  58623. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  58624. return ColorCurves;
  58625. }());
  58626. BABYLON.ColorCurves = ColorCurves;
  58627. })(BABYLON || (BABYLON = {}));
  58628. var BABYLON;
  58629. (function (BABYLON) {
  58630. /**
  58631. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  58632. * It can help converting any input color in a desired output one. This can then be used to create effects
  58633. * from sepia, black and white to sixties or futuristic rendering...
  58634. *
  58635. * The only supported format is currently 3dl.
  58636. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  58637. */
  58638. var ColorGradingTexture = (function (_super) {
  58639. __extends(ColorGradingTexture, _super);
  58640. /**
  58641. * Instantiates a ColorGradingTexture from the following parameters.
  58642. *
  58643. * @param url The location of the color gradind data (currently only supporting 3dl)
  58644. * @param scene The scene the texture will be used in
  58645. */
  58646. function ColorGradingTexture(url, scene) {
  58647. _super.call(this, scene);
  58648. if (!url) {
  58649. return;
  58650. }
  58651. this._textureMatrix = BABYLON.Matrix.Identity();
  58652. this.name = url;
  58653. this.url = url;
  58654. this.hasAlpha = false;
  58655. this.isCube = false;
  58656. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58657. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58658. this.anisotropicFilteringLevel = 1;
  58659. this._texture = this._getFromCache(url, true);
  58660. if (!this._texture) {
  58661. if (!scene.useDelayedTextureLoading) {
  58662. this.loadTexture();
  58663. }
  58664. else {
  58665. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58666. }
  58667. }
  58668. }
  58669. /**
  58670. * Returns the texture matrix used in most of the material.
  58671. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  58672. */
  58673. ColorGradingTexture.prototype.getTextureMatrix = function () {
  58674. return this._textureMatrix;
  58675. };
  58676. /**
  58677. * Occurs when the file being loaded is a .3dl LUT file.
  58678. */
  58679. ColorGradingTexture.prototype.load3dlTexture = function () {
  58680. var _this = this;
  58681. var mipLevels = 0;
  58682. var floatArrayView = null;
  58683. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58684. this._texture = texture;
  58685. var callback = function (text) {
  58686. var data;
  58687. var tempData;
  58688. var line;
  58689. var lines = text.split('\n');
  58690. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  58691. var maxColor = 0;
  58692. for (var i = 0; i < lines.length; i++) {
  58693. line = lines[i];
  58694. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  58695. continue;
  58696. if (line.indexOf('#') === 0)
  58697. continue;
  58698. var words = line.split(" ");
  58699. if (size === 0) {
  58700. // Number of space + one
  58701. size = words.length;
  58702. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  58703. tempData = new Float32Array(size * size * size * 4);
  58704. continue;
  58705. }
  58706. if (size != 0) {
  58707. var r = Math.max(parseInt(words[0]), 0);
  58708. var g = Math.max(parseInt(words[1]), 0);
  58709. var b = Math.max(parseInt(words[2]), 0);
  58710. maxColor = Math.max(r, maxColor);
  58711. maxColor = Math.max(g, maxColor);
  58712. maxColor = Math.max(b, maxColor);
  58713. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  58714. tempData[pixelStorageIndex + 0] = r;
  58715. tempData[pixelStorageIndex + 1] = g;
  58716. tempData[pixelStorageIndex + 2] = b;
  58717. tempData[pixelStorageIndex + 3] = 0;
  58718. pixelIndexSlice++;
  58719. if (pixelIndexSlice % size == 0) {
  58720. pixelIndexH++;
  58721. pixelIndexSlice = 0;
  58722. if (pixelIndexH % size == 0) {
  58723. pixelIndexW++;
  58724. pixelIndexH = 0;
  58725. }
  58726. }
  58727. }
  58728. }
  58729. for (var i = 0; i < tempData.length; i++) {
  58730. var value = tempData[i];
  58731. data[i] = (value / maxColor * 255);
  58732. }
  58733. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  58734. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  58735. };
  58736. BABYLON.Tools.LoadFile(this.url, callback);
  58737. return this._texture;
  58738. };
  58739. /**
  58740. * Starts the loading process of the texture.
  58741. */
  58742. ColorGradingTexture.prototype.loadTexture = function () {
  58743. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  58744. this.load3dlTexture();
  58745. }
  58746. };
  58747. /**
  58748. * Clones the color gradind texture.
  58749. */
  58750. ColorGradingTexture.prototype.clone = function () {
  58751. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  58752. // Base texture
  58753. newTexture.level = this.level;
  58754. return newTexture;
  58755. };
  58756. /**
  58757. * Called during delayed load for textures.
  58758. */
  58759. ColorGradingTexture.prototype.delayLoad = function () {
  58760. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58761. return;
  58762. }
  58763. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58764. this._texture = this._getFromCache(this.url, true);
  58765. if (!this._texture) {
  58766. this.loadTexture();
  58767. }
  58768. };
  58769. /**
  58770. * Binds the color grading to the shader.
  58771. * @param colorGrading The texture to bind
  58772. * @param effect The effect to bind to
  58773. */
  58774. ColorGradingTexture.Bind = function (colorGrading, effect) {
  58775. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  58776. var x = colorGrading.level; // Texture Level
  58777. var y = colorGrading.getSize().height; // Texture Size example with 8
  58778. var z = y - 1.0; // SizeMinusOne 8 - 1
  58779. var w = 1 / y; // Space of 1 slice 1 / 8
  58780. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  58781. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  58782. 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
  58783. 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
  58784. 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
  58785. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  58786. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  58787. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  58788. };
  58789. /**
  58790. * Prepare the list of uniforms associated with the ColorGrading effects.
  58791. * @param uniformsList The list of uniforms used in the effect
  58792. * @param samplersList The list of samplers used in the effect
  58793. */
  58794. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  58795. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  58796. samplersList.push("cameraColorGrading2DSampler");
  58797. };
  58798. /**
  58799. * Parses a color grading texture serialized by Babylon.
  58800. * @param parsedTexture The texture information being parsedTexture
  58801. * @param scene The scene to load the texture in
  58802. * @param rootUrl The root url of the data assets to load
  58803. * @return A color gradind texture
  58804. */
  58805. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58806. var texture = null;
  58807. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  58808. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  58809. texture.name = parsedTexture.name;
  58810. texture.level = parsedTexture.level;
  58811. }
  58812. return texture;
  58813. };
  58814. /**
  58815. * Serializes the LUT texture to json format.
  58816. */
  58817. ColorGradingTexture.prototype.serialize = function () {
  58818. if (!this.name) {
  58819. return null;
  58820. }
  58821. var serializationObject = {};
  58822. serializationObject.name = this.name;
  58823. serializationObject.level = this.level;
  58824. return serializationObject;
  58825. };
  58826. /**
  58827. * Empty line regex stored for GC.
  58828. */
  58829. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  58830. return ColorGradingTexture;
  58831. }(BABYLON.BaseTexture));
  58832. BABYLON.ColorGradingTexture = ColorGradingTexture;
  58833. })(BABYLON || (BABYLON = {}));
  58834. var BABYLON;
  58835. (function (BABYLON) {
  58836. var PBRMaterialDefines = (function (_super) {
  58837. __extends(PBRMaterialDefines, _super);
  58838. function PBRMaterialDefines() {
  58839. _super.call(this);
  58840. this.ALBEDO = false;
  58841. this.AMBIENT = false;
  58842. this.OPACITY = false;
  58843. this.OPACITYRGB = false;
  58844. this.REFLECTION = false;
  58845. this.EMISSIVE = false;
  58846. this.REFLECTIVITY = false;
  58847. this.BUMP = false;
  58848. this.PARALLAX = false;
  58849. this.PARALLAXOCCLUSION = false;
  58850. this.SPECULAROVERALPHA = false;
  58851. this.CLIPPLANE = false;
  58852. this.ALPHATEST = false;
  58853. this.ALPHAFROMALBEDO = false;
  58854. this.POINTSIZE = false;
  58855. this.FOG = false;
  58856. this.SPECULARTERM = false;
  58857. this.OPACITYFRESNEL = false;
  58858. this.EMISSIVEFRESNEL = false;
  58859. this.FRESNEL = false;
  58860. this.NORMAL = false;
  58861. this.UV1 = false;
  58862. this.UV2 = false;
  58863. this.VERTEXCOLOR = false;
  58864. this.VERTEXALPHA = false;
  58865. this.NUM_BONE_INFLUENCERS = 0;
  58866. this.BonesPerMesh = 0;
  58867. this.INSTANCES = false;
  58868. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  58869. this.MICROSURFACEAUTOMATIC = false;
  58870. this.EMISSIVEASILLUMINATION = false;
  58871. this.LINKEMISSIVEWITHALBEDO = false;
  58872. this.LIGHTMAP = false;
  58873. this.USELIGHTMAPASSHADOWMAP = false;
  58874. this.REFLECTIONMAP_3D = false;
  58875. this.REFLECTIONMAP_SPHERICAL = false;
  58876. this.REFLECTIONMAP_PLANAR = false;
  58877. this.REFLECTIONMAP_CUBIC = false;
  58878. this.REFLECTIONMAP_PROJECTION = false;
  58879. this.REFLECTIONMAP_SKYBOX = false;
  58880. this.REFLECTIONMAP_EXPLICIT = false;
  58881. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  58882. this.INVERTCUBICMAP = false;
  58883. this.LOGARITHMICDEPTH = false;
  58884. this.CAMERATONEMAP = false;
  58885. this.CAMERACONTRAST = false;
  58886. this.CAMERACOLORGRADING = false;
  58887. this.CAMERACOLORCURVES = false;
  58888. this.OVERLOADEDVALUES = false;
  58889. this.OVERLOADEDSHADOWVALUES = false;
  58890. this.USESPHERICALFROMREFLECTIONMAP = false;
  58891. this.REFRACTION = false;
  58892. this.REFRACTIONMAP_3D = false;
  58893. this.LINKREFRACTIONTOTRANSPARENCY = false;
  58894. this.REFRACTIONMAPINLINEARSPACE = false;
  58895. this.LODBASEDMICROSFURACE = false;
  58896. this.USEPHYSICALLIGHTFALLOFF = false;
  58897. this.RADIANCEOVERALPHA = false;
  58898. this.USEPMREMREFLECTION = false;
  58899. this.USEPMREMREFRACTION = false;
  58900. this.OPENGLNORMALMAP = false;
  58901. this.INVERTNORMALMAPX = false;
  58902. this.INVERTNORMALMAPY = false;
  58903. this.SHADOWFULLFLOAT = false;
  58904. this.rebuild();
  58905. }
  58906. return PBRMaterialDefines;
  58907. }(BABYLON.MaterialDefines));
  58908. /**
  58909. * The Physically based material of BJS.
  58910. *
  58911. * This offers the main features of a standard PBR material.
  58912. * For more information, please refer to the documentation :
  58913. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  58914. */
  58915. var PBRMaterial = (function (_super) {
  58916. __extends(PBRMaterial, _super);
  58917. /**
  58918. * Instantiates a new PBRMaterial instance.
  58919. *
  58920. * @param name The material name
  58921. * @param scene The scene the material will be use in.
  58922. */
  58923. function PBRMaterial(name, scene) {
  58924. var _this = this;
  58925. _super.call(this, name, scene);
  58926. /**
  58927. * Intensity of the direct lights e.g. the four lights available in your scene.
  58928. * This impacts both the direct diffuse and specular highlights.
  58929. */
  58930. this.directIntensity = 1.0;
  58931. /**
  58932. * Intensity of the emissive part of the material.
  58933. * This helps controlling the emissive effect without modifying the emissive color.
  58934. */
  58935. this.emissiveIntensity = 1.0;
  58936. /**
  58937. * Intensity of the environment e.g. how much the environment will light the object
  58938. * either through harmonics for rough material or through the refelction for shiny ones.
  58939. */
  58940. this.environmentIntensity = 1.0;
  58941. /**
  58942. * This is a special control allowing the reduction of the specular highlights coming from the
  58943. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  58944. */
  58945. this.specularIntensity = 1.0;
  58946. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  58947. /**
  58948. * Debug Control allowing disabling the bump map on this material.
  58949. */
  58950. this.disableBumpMap = false;
  58951. /**
  58952. * Debug Control helping enforcing or dropping the darkness of shadows.
  58953. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  58954. */
  58955. this.overloadedShadowIntensity = 1.0;
  58956. /**
  58957. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  58958. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  58959. */
  58960. this.overloadedShadeIntensity = 1.0;
  58961. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  58962. /**
  58963. * The camera exposure used on this material.
  58964. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  58965. * This corresponds to a photographic exposure.
  58966. */
  58967. this.cameraExposure = 1.0;
  58968. /**
  58969. * The camera contrast used on this material.
  58970. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  58971. */
  58972. this.cameraContrast = 1.0;
  58973. /**
  58974. * Color Grading 2D Lookup Texture.
  58975. * This allows special effects like sepia, black and white to sixties rendering style.
  58976. */
  58977. this.cameraColorGradingTexture = null;
  58978. /**
  58979. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  58980. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  58981. * 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;
  58982. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  58983. */
  58984. this.cameraColorCurves = null;
  58985. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  58986. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  58987. /**
  58988. * Debug Control allowing to overload the ambient color.
  58989. * This as to be use with the overloadedAmbientIntensity parameter.
  58990. */
  58991. this.overloadedAmbient = BABYLON.Color3.White();
  58992. /**
  58993. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  58994. */
  58995. this.overloadedAmbientIntensity = 0.0;
  58996. /**
  58997. * Debug Control allowing to overload the albedo color.
  58998. * This as to be use with the overloadedAlbedoIntensity parameter.
  58999. */
  59000. this.overloadedAlbedo = BABYLON.Color3.White();
  59001. /**
  59002. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  59003. */
  59004. this.overloadedAlbedoIntensity = 0.0;
  59005. /**
  59006. * Debug Control allowing to overload the reflectivity color.
  59007. * This as to be use with the overloadedReflectivityIntensity parameter.
  59008. */
  59009. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  59010. /**
  59011. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  59012. */
  59013. this.overloadedReflectivityIntensity = 0.0;
  59014. /**
  59015. * Debug Control allowing to overload the emissive color.
  59016. * This as to be use with the overloadedEmissiveIntensity parameter.
  59017. */
  59018. this.overloadedEmissive = BABYLON.Color3.White();
  59019. /**
  59020. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  59021. */
  59022. this.overloadedEmissiveIntensity = 0.0;
  59023. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  59024. /**
  59025. * Debug Control allowing to overload the reflection color.
  59026. * This as to be use with the overloadedReflectionIntensity parameter.
  59027. */
  59028. this.overloadedReflection = BABYLON.Color3.White();
  59029. /**
  59030. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  59031. */
  59032. this.overloadedReflectionIntensity = 0.0;
  59033. /**
  59034. * Debug Control allowing to overload the microsurface.
  59035. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  59036. */
  59037. this.overloadedMicroSurface = 0.0;
  59038. /**
  59039. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  59040. */
  59041. this.overloadedMicroSurfaceIntensity = 0.0;
  59042. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  59043. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  59044. /**
  59045. * AKA Diffuse Color in other nomenclature.
  59046. */
  59047. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  59048. /**
  59049. * AKA Specular Color in other nomenclature.
  59050. */
  59051. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  59052. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  59053. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  59054. /**
  59055. * AKA Glossiness in other nomenclature.
  59056. */
  59057. this.microSurface = 0.9;
  59058. /**
  59059. * source material index of refraction (IOR)' / 'destination material IOR.
  59060. */
  59061. this.indexOfRefraction = 0.66;
  59062. /**
  59063. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  59064. */
  59065. this.invertRefractionY = false;
  59066. /**
  59067. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  59068. * Materials half opaque for instance using refraction could benefit from this control.
  59069. */
  59070. this.linkRefractionWithTransparency = false;
  59071. /**
  59072. * The emissive and albedo are linked to never be more than one (Energy conservation).
  59073. */
  59074. this.linkEmissiveWithAlbedo = false;
  59075. this.useLightmapAsShadowmap = false;
  59076. /**
  59077. * In this mode, the emissive informtaion will always be added to the lighting once.
  59078. * A light for instance can be thought as emissive.
  59079. */
  59080. this.useEmissiveAsIllumination = false;
  59081. /**
  59082. * Secifies that the alpha is coming form the albedo channel alpha channel.
  59083. */
  59084. this.useAlphaFromAlbedoTexture = false;
  59085. /**
  59086. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  59087. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  59088. */
  59089. this.useSpecularOverAlpha = true;
  59090. /**
  59091. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  59092. */
  59093. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  59094. /**
  59095. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  59096. * The material will try to infer what glossiness each pixel should be.
  59097. */
  59098. this.useAutoMicroSurfaceFromReflectivityMap = false;
  59099. /**
  59100. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  59101. * the creation of the material.
  59102. */
  59103. this.useScalarInLinearSpace = false;
  59104. /**
  59105. * BJS is using an harcoded light falloff based on a manually sets up range.
  59106. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  59107. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  59108. */
  59109. this.usePhysicalLightFalloff = true;
  59110. /**
  59111. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  59112. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  59113. */
  59114. this.useRadianceOverAlpha = true;
  59115. /**
  59116. * Allows using the bump map in parallax mode.
  59117. */
  59118. this.useParallax = false;
  59119. /**
  59120. * Allows using the bump map in parallax occlusion mode.
  59121. */
  59122. this.useParallaxOcclusion = false;
  59123. /**
  59124. * Controls the scale bias of the parallax mode.
  59125. */
  59126. this.parallaxScaleBias = 0.05;
  59127. /**
  59128. * If sets to true, disables all the lights affecting the material.
  59129. */
  59130. this.disableLighting = false;
  59131. /**
  59132. * Number of Simultaneous lights allowed on the material.
  59133. */
  59134. this.maxSimultaneousLights = 4;
  59135. /**
  59136. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  59137. */
  59138. this.invertNormalMapX = false;
  59139. /**
  59140. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  59141. */
  59142. this.invertNormalMapY = false;
  59143. this._renderTargets = new BABYLON.SmartArray(16);
  59144. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  59145. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  59146. this._tempColor = new BABYLON.Color3();
  59147. this._defines = new PBRMaterialDefines();
  59148. this._cachedDefines = new PBRMaterialDefines();
  59149. this._myScene = null;
  59150. this._myShadowGenerator = null;
  59151. this._cachedDefines.BonesPerMesh = -1;
  59152. this.getRenderTargetTextures = function () {
  59153. _this._renderTargets.reset();
  59154. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  59155. _this._renderTargets.push(_this.reflectionTexture);
  59156. }
  59157. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  59158. _this._renderTargets.push(_this.refractionTexture);
  59159. }
  59160. return _this._renderTargets;
  59161. };
  59162. }
  59163. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  59164. get: function () {
  59165. return this._useLogarithmicDepth;
  59166. },
  59167. set: function (value) {
  59168. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  59169. },
  59170. enumerable: true,
  59171. configurable: true
  59172. });
  59173. PBRMaterial.prototype.needAlphaBlending = function () {
  59174. if (this.linkRefractionWithTransparency) {
  59175. return false;
  59176. }
  59177. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  59178. };
  59179. PBRMaterial.prototype.needAlphaTesting = function () {
  59180. if (this.linkRefractionWithTransparency) {
  59181. return false;
  59182. }
  59183. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  59184. };
  59185. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  59186. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  59187. };
  59188. PBRMaterial.prototype.getAlphaTestTexture = function () {
  59189. return this.albedoTexture;
  59190. };
  59191. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59192. if (!mesh) {
  59193. return true;
  59194. }
  59195. if (this._defines.INSTANCES !== useInstances) {
  59196. return false;
  59197. }
  59198. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  59199. return true;
  59200. }
  59201. return false;
  59202. };
  59203. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  59204. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  59205. };
  59206. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  59207. if (!useScalarInLinear) {
  59208. color.toLinearSpaceToRef(ref);
  59209. }
  59210. else {
  59211. ref.r = color.r;
  59212. ref.g = color.g;
  59213. ref.b = color.b;
  59214. }
  59215. };
  59216. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  59217. var lightIndex = 0;
  59218. var depthValuesAlreadySet = false;
  59219. for (var index = 0; index < scene.lights.length; index++) {
  59220. var light = scene.lights[index];
  59221. if (!light.isEnabled()) {
  59222. continue;
  59223. }
  59224. if (!light.canAffectMesh(mesh)) {
  59225. continue;
  59226. }
  59227. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  59228. // GAMMA CORRECTION.
  59229. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  59230. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  59231. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  59232. if (defines["SPECULARTERM"]) {
  59233. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  59234. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  59235. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  59236. }
  59237. // Shadows
  59238. if (scene.shadowsEnabled) {
  59239. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  59240. }
  59241. lightIndex++;
  59242. if (lightIndex === maxSimultaneousLights)
  59243. break;
  59244. }
  59245. };
  59246. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  59247. if (this.checkReadyOnlyOnce) {
  59248. if (this._wasPreviouslyReady) {
  59249. return true;
  59250. }
  59251. }
  59252. var scene = this.getScene();
  59253. if (!this.checkReadyOnEveryCall) {
  59254. if (this._renderId === scene.getRenderId()) {
  59255. if (this._checkCache(scene, mesh, useInstances)) {
  59256. return true;
  59257. }
  59258. }
  59259. }
  59260. var engine = scene.getEngine();
  59261. var needNormals = false;
  59262. var needUVs = false;
  59263. this._defines.reset();
  59264. if (scene.texturesEnabled) {
  59265. // Textures
  59266. if (scene.texturesEnabled) {
  59267. if (scene.getEngine().getCaps().textureLOD) {
  59268. this._defines.LODBASEDMICROSFURACE = true;
  59269. }
  59270. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  59271. if (!this.albedoTexture.isReady()) {
  59272. return false;
  59273. }
  59274. else {
  59275. needUVs = true;
  59276. this._defines.ALBEDO = true;
  59277. }
  59278. }
  59279. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  59280. if (!this.ambientTexture.isReady()) {
  59281. return false;
  59282. }
  59283. else {
  59284. needUVs = true;
  59285. this._defines.AMBIENT = true;
  59286. }
  59287. }
  59288. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  59289. if (!this.opacityTexture.isReady()) {
  59290. return false;
  59291. }
  59292. else {
  59293. needUVs = true;
  59294. this._defines.OPACITY = true;
  59295. if (this.opacityTexture.getAlphaFromRGB) {
  59296. this._defines.OPACITYRGB = true;
  59297. }
  59298. }
  59299. }
  59300. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  59301. if (!this.reflectionTexture.isReady()) {
  59302. return false;
  59303. }
  59304. else {
  59305. needNormals = true;
  59306. this._defines.REFLECTION = true;
  59307. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  59308. this._defines.INVERTCUBICMAP = true;
  59309. }
  59310. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  59311. switch (this.reflectionTexture.coordinatesMode) {
  59312. case BABYLON.Texture.CUBIC_MODE:
  59313. case BABYLON.Texture.INVCUBIC_MODE:
  59314. this._defines.REFLECTIONMAP_CUBIC = true;
  59315. break;
  59316. case BABYLON.Texture.EXPLICIT_MODE:
  59317. this._defines.REFLECTIONMAP_EXPLICIT = true;
  59318. break;
  59319. case BABYLON.Texture.PLANAR_MODE:
  59320. this._defines.REFLECTIONMAP_PLANAR = true;
  59321. break;
  59322. case BABYLON.Texture.PROJECTION_MODE:
  59323. this._defines.REFLECTIONMAP_PROJECTION = true;
  59324. break;
  59325. case BABYLON.Texture.SKYBOX_MODE:
  59326. this._defines.REFLECTIONMAP_SKYBOX = true;
  59327. break;
  59328. case BABYLON.Texture.SPHERICAL_MODE:
  59329. this._defines.REFLECTIONMAP_SPHERICAL = true;
  59330. break;
  59331. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  59332. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  59333. break;
  59334. }
  59335. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  59336. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  59337. needNormals = true;
  59338. if (this.reflectionTexture.isPMREM) {
  59339. this._defines.USEPMREMREFLECTION = true;
  59340. }
  59341. }
  59342. }
  59343. }
  59344. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  59345. if (!this.lightmapTexture.isReady()) {
  59346. return false;
  59347. }
  59348. else {
  59349. needUVs = true;
  59350. this._defines.LIGHTMAP = true;
  59351. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  59352. }
  59353. }
  59354. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  59355. if (!this.emissiveTexture.isReady()) {
  59356. return false;
  59357. }
  59358. else {
  59359. needUVs = true;
  59360. this._defines.EMISSIVE = true;
  59361. }
  59362. }
  59363. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  59364. if (!this.reflectivityTexture.isReady()) {
  59365. return false;
  59366. }
  59367. else {
  59368. needUVs = true;
  59369. this._defines.REFLECTIVITY = true;
  59370. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  59371. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  59372. }
  59373. }
  59374. }
  59375. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  59376. if (!this.bumpTexture.isReady()) {
  59377. return false;
  59378. }
  59379. else {
  59380. needUVs = true;
  59381. this._defines.BUMP = true;
  59382. if (this.useParallax) {
  59383. this._defines.PARALLAX = true;
  59384. if (this.useParallaxOcclusion) {
  59385. this._defines.PARALLAXOCCLUSION = true;
  59386. }
  59387. }
  59388. if (this.invertNormalMapX) {
  59389. this._defines.INVERTNORMALMAPX = true;
  59390. }
  59391. if (this.invertNormalMapY) {
  59392. this._defines.INVERTNORMALMAPY = true;
  59393. }
  59394. }
  59395. }
  59396. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  59397. if (!this.refractionTexture.isReady()) {
  59398. return false;
  59399. }
  59400. else {
  59401. needUVs = true;
  59402. this._defines.REFRACTION = true;
  59403. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  59404. if (this.linkRefractionWithTransparency) {
  59405. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  59406. }
  59407. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  59408. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  59409. if (this.refractionTexture.isPMREM) {
  59410. this._defines.USEPMREMREFRACTION = true;
  59411. }
  59412. }
  59413. }
  59414. }
  59415. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  59416. if (!this.cameraColorGradingTexture.isReady()) {
  59417. return false;
  59418. }
  59419. else {
  59420. this._defines.CAMERACOLORGRADING = true;
  59421. }
  59422. }
  59423. }
  59424. // Effect
  59425. if (scene.clipPlane) {
  59426. this._defines.CLIPPLANE = true;
  59427. }
  59428. if (engine.getAlphaTesting()) {
  59429. this._defines.ALPHATEST = true;
  59430. }
  59431. if (this._shouldUseAlphaFromAlbedoTexture()) {
  59432. this._defines.ALPHAFROMALBEDO = true;
  59433. }
  59434. if (this.useEmissiveAsIllumination) {
  59435. this._defines.EMISSIVEASILLUMINATION = true;
  59436. }
  59437. if (this.linkEmissiveWithAlbedo) {
  59438. this._defines.LINKEMISSIVEWITHALBEDO = true;
  59439. }
  59440. if (this.useLogarithmicDepth) {
  59441. this._defines.LOGARITHMICDEPTH = true;
  59442. }
  59443. if (this.cameraContrast != 1) {
  59444. this._defines.CAMERACONTRAST = true;
  59445. }
  59446. if (this.cameraExposure != 1) {
  59447. this._defines.CAMERATONEMAP = true;
  59448. }
  59449. if (this.cameraColorCurves) {
  59450. this._defines.CAMERACOLORCURVES = true;
  59451. }
  59452. if (this.overloadedShadeIntensity != 1 ||
  59453. this.overloadedShadowIntensity != 1) {
  59454. this._defines.OVERLOADEDSHADOWVALUES = true;
  59455. }
  59456. if (this.overloadedMicroSurfaceIntensity > 0 ||
  59457. this.overloadedEmissiveIntensity > 0 ||
  59458. this.overloadedReflectivityIntensity > 0 ||
  59459. this.overloadedAlbedoIntensity > 0 ||
  59460. this.overloadedAmbientIntensity > 0 ||
  59461. this.overloadedReflectionIntensity > 0) {
  59462. this._defines.OVERLOADEDVALUES = true;
  59463. }
  59464. // Point size
  59465. if (this.pointsCloud || scene.forcePointsCloud) {
  59466. this._defines.POINTSIZE = true;
  59467. }
  59468. // Fog
  59469. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  59470. this._defines.FOG = true;
  59471. }
  59472. if (scene.lightsEnabled && !this.disableLighting) {
  59473. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  59474. }
  59475. if (BABYLON.StandardMaterial.FresnelEnabled) {
  59476. // Fresnel
  59477. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  59478. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  59479. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  59480. this._defines.OPACITYFRESNEL = true;
  59481. }
  59482. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  59483. this._defines.EMISSIVEFRESNEL = true;
  59484. }
  59485. needNormals = true;
  59486. this._defines.FRESNEL = true;
  59487. }
  59488. }
  59489. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  59490. this._defines.SPECULAROVERALPHA = true;
  59491. }
  59492. if (this.usePhysicalLightFalloff) {
  59493. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  59494. }
  59495. if (this.useRadianceOverAlpha) {
  59496. this._defines.RADIANCEOVERALPHA = true;
  59497. }
  59498. // Attribs
  59499. if (mesh) {
  59500. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  59501. this._defines.NORMAL = true;
  59502. }
  59503. if (needUVs) {
  59504. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59505. this._defines.UV1 = true;
  59506. }
  59507. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59508. this._defines.UV2 = true;
  59509. }
  59510. }
  59511. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59512. this._defines.VERTEXCOLOR = true;
  59513. if (mesh.hasVertexAlpha) {
  59514. this._defines.VERTEXALPHA = true;
  59515. }
  59516. }
  59517. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59518. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  59519. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  59520. }
  59521. // Instances
  59522. if (useInstances) {
  59523. this._defines.INSTANCES = true;
  59524. }
  59525. }
  59526. // Get correct effect
  59527. if (!this._defines.isEqual(this._cachedDefines)) {
  59528. this._defines.cloneTo(this._cachedDefines);
  59529. scene.resetCachedMaterial();
  59530. // Fallbacks
  59531. var fallbacks = new BABYLON.EffectFallbacks();
  59532. if (this._defines.REFLECTION) {
  59533. fallbacks.addFallback(0, "REFLECTION");
  59534. }
  59535. if (this._defines.REFRACTION) {
  59536. fallbacks.addFallback(0, "REFRACTION");
  59537. }
  59538. if (this._defines.REFLECTIVITY) {
  59539. fallbacks.addFallback(0, "REFLECTIVITY");
  59540. }
  59541. if (this._defines.BUMP) {
  59542. fallbacks.addFallback(0, "BUMP");
  59543. }
  59544. if (this._defines.PARALLAX) {
  59545. fallbacks.addFallback(1, "PARALLAX");
  59546. }
  59547. if (this._defines.PARALLAXOCCLUSION) {
  59548. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  59549. }
  59550. if (this._defines.SPECULAROVERALPHA) {
  59551. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  59552. }
  59553. if (this._defines.FOG) {
  59554. fallbacks.addFallback(1, "FOG");
  59555. }
  59556. if (this._defines.POINTSIZE) {
  59557. fallbacks.addFallback(0, "POINTSIZE");
  59558. }
  59559. if (this._defines.LOGARITHMICDEPTH) {
  59560. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  59561. }
  59562. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  59563. if (this._defines.SPECULARTERM) {
  59564. fallbacks.addFallback(0, "SPECULARTERM");
  59565. }
  59566. if (this._defines.OPACITYFRESNEL) {
  59567. fallbacks.addFallback(1, "OPACITYFRESNEL");
  59568. }
  59569. if (this._defines.EMISSIVEFRESNEL) {
  59570. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  59571. }
  59572. if (this._defines.FRESNEL) {
  59573. fallbacks.addFallback(3, "FRESNEL");
  59574. }
  59575. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  59576. fallbacks.addCPUSkinningFallback(0, mesh);
  59577. }
  59578. //Attributes
  59579. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59580. if (this._defines.NORMAL) {
  59581. attribs.push(BABYLON.VertexBuffer.NormalKind);
  59582. }
  59583. if (this._defines.UV1) {
  59584. attribs.push(BABYLON.VertexBuffer.UVKind);
  59585. }
  59586. if (this._defines.UV2) {
  59587. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59588. }
  59589. if (this._defines.VERTEXCOLOR) {
  59590. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59591. }
  59592. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  59593. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  59594. // Legacy browser patch
  59595. var shaderName = "pbr";
  59596. if (!scene.getEngine().getCaps().standardDerivatives) {
  59597. shaderName = "legacypbr";
  59598. }
  59599. var join = this._defines.toString();
  59600. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  59601. "vFogInfos", "vFogColor", "pointSize",
  59602. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  59603. "mBones",
  59604. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  59605. "depthValues",
  59606. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  59607. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  59608. "logarithmicDepthConstant",
  59609. "vSphericalX", "vSphericalY", "vSphericalZ",
  59610. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  59611. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  59612. "vMicrosurfaceTextureLods",
  59613. "vCameraInfos"
  59614. ];
  59615. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  59616. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  59617. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  59618. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  59619. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  59620. }
  59621. if (!this._effect.isReady()) {
  59622. return false;
  59623. }
  59624. this._renderId = scene.getRenderId();
  59625. this._wasPreviouslyReady = true;
  59626. if (mesh) {
  59627. if (!mesh._materialDefines) {
  59628. mesh._materialDefines = new PBRMaterialDefines();
  59629. }
  59630. this._defines.cloneTo(mesh._materialDefines);
  59631. }
  59632. return true;
  59633. };
  59634. PBRMaterial.prototype.unbind = function () {
  59635. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  59636. this._effect.setTexture("reflection2DSampler", null);
  59637. }
  59638. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  59639. this._effect.setTexture("refraction2DSampler", null);
  59640. }
  59641. _super.prototype.unbind.call(this);
  59642. };
  59643. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59644. this._effect.setMatrix("world", world);
  59645. };
  59646. PBRMaterial.prototype.bind = function (world, mesh) {
  59647. this._myScene = this.getScene();
  59648. // Matrices
  59649. this.bindOnlyWorldMatrix(world);
  59650. // Bones
  59651. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59652. if (this._myScene.getCachedMaterial() !== this) {
  59653. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  59654. if (BABYLON.StandardMaterial.FresnelEnabled) {
  59655. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  59656. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  59657. }
  59658. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  59659. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  59660. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  59661. }
  59662. }
  59663. // Textures
  59664. if (this._myScene.texturesEnabled) {
  59665. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  59666. this._effect.setTexture("albedoSampler", this.albedoTexture);
  59667. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  59668. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  59669. }
  59670. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  59671. this._effect.setTexture("ambientSampler", this.ambientTexture);
  59672. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  59673. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  59674. }
  59675. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  59676. this._effect.setTexture("opacitySampler", this.opacityTexture);
  59677. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  59678. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  59679. }
  59680. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  59681. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  59682. if (this.reflectionTexture.isCube) {
  59683. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  59684. }
  59685. else {
  59686. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  59687. }
  59688. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  59689. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  59690. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  59691. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  59692. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  59693. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  59694. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  59695. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  59696. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  59697. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  59698. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  59699. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  59700. }
  59701. }
  59702. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  59703. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  59704. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  59705. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  59706. }
  59707. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  59708. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  59709. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  59710. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  59711. }
  59712. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  59713. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  59714. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  59715. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  59716. }
  59717. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  59718. this._effect.setTexture("bumpSampler", this.bumpTexture);
  59719. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  59720. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  59721. }
  59722. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  59723. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  59724. var depth = 1.0;
  59725. if (this.refractionTexture.isCube) {
  59726. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  59727. }
  59728. else {
  59729. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  59730. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  59731. if (this.refractionTexture.depth) {
  59732. depth = this.refractionTexture.depth;
  59733. }
  59734. }
  59735. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  59736. }
  59737. if ((this.reflectionTexture || this.refractionTexture)) {
  59738. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  59739. }
  59740. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  59741. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  59742. }
  59743. }
  59744. // Clip plane
  59745. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  59746. // Point size
  59747. if (this.pointsCloud) {
  59748. this._effect.setFloat("pointSize", this.pointSize);
  59749. }
  59750. // Colors
  59751. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  59752. // GAMMA CORRECTION.
  59753. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  59754. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  59755. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  59756. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  59757. // GAMMA CORRECTION.
  59758. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  59759. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  59760. // GAMMA CORRECTION.
  59761. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  59762. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  59763. }
  59764. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  59765. // GAMMA CORRECTION.
  59766. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  59767. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  59768. // Lights
  59769. if (this._myScene.lightsEnabled && !this.disableLighting) {
  59770. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  59771. }
  59772. // View
  59773. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  59774. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  59775. }
  59776. // Fog
  59777. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  59778. this._lightingInfos.x = this.directIntensity;
  59779. this._lightingInfos.y = this.emissiveIntensity;
  59780. this._lightingInfos.z = this.environmentIntensity;
  59781. this._lightingInfos.w = this.specularIntensity;
  59782. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  59783. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  59784. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  59785. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  59786. this._cameraInfos.x = this.cameraExposure;
  59787. this._cameraInfos.y = this.cameraContrast;
  59788. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  59789. if (this.cameraColorCurves) {
  59790. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  59791. }
  59792. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  59793. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  59794. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  59795. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  59796. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  59797. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  59798. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  59799. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  59800. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  59801. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  59802. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  59803. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  59804. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  59805. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  59806. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  59807. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  59808. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  59809. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  59810. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  59811. // Log. depth
  59812. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  59813. }
  59814. _super.prototype.bind.call(this, world, mesh);
  59815. this._myScene = null;
  59816. };
  59817. PBRMaterial.prototype.getAnimatables = function () {
  59818. var results = [];
  59819. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  59820. results.push(this.albedoTexture);
  59821. }
  59822. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  59823. results.push(this.ambientTexture);
  59824. }
  59825. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  59826. results.push(this.opacityTexture);
  59827. }
  59828. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  59829. results.push(this.reflectionTexture);
  59830. }
  59831. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  59832. results.push(this.emissiveTexture);
  59833. }
  59834. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  59835. results.push(this.reflectivityTexture);
  59836. }
  59837. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  59838. results.push(this.bumpTexture);
  59839. }
  59840. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  59841. results.push(this.lightmapTexture);
  59842. }
  59843. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  59844. results.push(this.refractionTexture);
  59845. }
  59846. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  59847. results.push(this.cameraColorGradingTexture);
  59848. }
  59849. return results;
  59850. };
  59851. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59852. if (forceDisposeTextures) {
  59853. if (this.albedoTexture) {
  59854. this.albedoTexture.dispose();
  59855. }
  59856. if (this.ambientTexture) {
  59857. this.ambientTexture.dispose();
  59858. }
  59859. if (this.opacityTexture) {
  59860. this.opacityTexture.dispose();
  59861. }
  59862. if (this.reflectionTexture) {
  59863. this.reflectionTexture.dispose();
  59864. }
  59865. if (this.emissiveTexture) {
  59866. this.emissiveTexture.dispose();
  59867. }
  59868. if (this.reflectivityTexture) {
  59869. this.reflectivityTexture.dispose();
  59870. }
  59871. if (this.bumpTexture) {
  59872. this.bumpTexture.dispose();
  59873. }
  59874. if (this.lightmapTexture) {
  59875. this.lightmapTexture.dispose();
  59876. }
  59877. if (this.refractionTexture) {
  59878. this.refractionTexture.dispose();
  59879. }
  59880. if (this.cameraColorGradingTexture) {
  59881. this.cameraColorGradingTexture.dispose();
  59882. }
  59883. }
  59884. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59885. };
  59886. PBRMaterial.prototype.clone = function (name) {
  59887. var _this = this;
  59888. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  59889. };
  59890. PBRMaterial.prototype.serialize = function () {
  59891. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59892. serializationObject.customType = "BABYLON.PBRMaterial";
  59893. return serializationObject;
  59894. };
  59895. // Statics
  59896. PBRMaterial.Parse = function (source, scene, rootUrl) {
  59897. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  59898. };
  59899. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  59900. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  59901. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  59902. PBRMaterial._scaledReflection = new BABYLON.Color3();
  59903. __decorate([
  59904. BABYLON.serialize()
  59905. ], PBRMaterial.prototype, "directIntensity", void 0);
  59906. __decorate([
  59907. BABYLON.serialize()
  59908. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  59909. __decorate([
  59910. BABYLON.serialize()
  59911. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  59912. __decorate([
  59913. BABYLON.serialize()
  59914. ], PBRMaterial.prototype, "specularIntensity", void 0);
  59915. __decorate([
  59916. BABYLON.serialize()
  59917. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  59918. __decorate([
  59919. BABYLON.serialize()
  59920. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  59921. __decorate([
  59922. BABYLON.serialize()
  59923. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  59924. __decorate([
  59925. BABYLON.serialize()
  59926. ], PBRMaterial.prototype, "cameraExposure", void 0);
  59927. __decorate([
  59928. BABYLON.serialize()
  59929. ], PBRMaterial.prototype, "cameraContrast", void 0);
  59930. __decorate([
  59931. BABYLON.serializeAsTexture()
  59932. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  59933. __decorate([
  59934. BABYLON.serializeAsColorCurves()
  59935. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  59936. __decorate([
  59937. BABYLON.serializeAsColor3()
  59938. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  59939. __decorate([
  59940. BABYLON.serialize()
  59941. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  59942. __decorate([
  59943. BABYLON.serializeAsColor3()
  59944. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  59945. __decorate([
  59946. BABYLON.serialize()
  59947. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  59948. __decorate([
  59949. BABYLON.serializeAsColor3()
  59950. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  59951. __decorate([
  59952. BABYLON.serialize()
  59953. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  59954. __decorate([
  59955. BABYLON.serializeAsColor3()
  59956. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  59957. __decorate([
  59958. BABYLON.serialize()
  59959. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  59960. __decorate([
  59961. BABYLON.serializeAsColor3()
  59962. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  59963. __decorate([
  59964. BABYLON.serialize()
  59965. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  59966. __decorate([
  59967. BABYLON.serialize()
  59968. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  59969. __decorate([
  59970. BABYLON.serialize()
  59971. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  59972. __decorate([
  59973. BABYLON.serializeAsTexture()
  59974. ], PBRMaterial.prototype, "albedoTexture", void 0);
  59975. __decorate([
  59976. BABYLON.serializeAsTexture()
  59977. ], PBRMaterial.prototype, "ambientTexture", void 0);
  59978. __decorate([
  59979. BABYLON.serializeAsTexture()
  59980. ], PBRMaterial.prototype, "opacityTexture", void 0);
  59981. __decorate([
  59982. BABYLON.serializeAsTexture()
  59983. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  59984. __decorate([
  59985. BABYLON.serializeAsTexture()
  59986. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  59987. __decorate([
  59988. BABYLON.serializeAsTexture()
  59989. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  59990. __decorate([
  59991. BABYLON.serializeAsTexture()
  59992. ], PBRMaterial.prototype, "bumpTexture", void 0);
  59993. __decorate([
  59994. BABYLON.serializeAsTexture()
  59995. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  59996. __decorate([
  59997. BABYLON.serializeAsTexture()
  59998. ], PBRMaterial.prototype, "refractionTexture", void 0);
  59999. __decorate([
  60000. BABYLON.serializeAsColor3("ambient")
  60001. ], PBRMaterial.prototype, "ambientColor", void 0);
  60002. __decorate([
  60003. BABYLON.serializeAsColor3("albedo")
  60004. ], PBRMaterial.prototype, "albedoColor", void 0);
  60005. __decorate([
  60006. BABYLON.serializeAsColor3("reflectivity")
  60007. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  60008. __decorate([
  60009. BABYLON.serializeAsColor3("reflection")
  60010. ], PBRMaterial.prototype, "reflectionColor", void 0);
  60011. __decorate([
  60012. BABYLON.serializeAsColor3("emissive")
  60013. ], PBRMaterial.prototype, "emissiveColor", void 0);
  60014. __decorate([
  60015. BABYLON.serialize()
  60016. ], PBRMaterial.prototype, "microSurface", void 0);
  60017. __decorate([
  60018. BABYLON.serialize()
  60019. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  60020. __decorate([
  60021. BABYLON.serialize()
  60022. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  60023. __decorate([
  60024. BABYLON.serializeAsFresnelParameters()
  60025. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  60026. __decorate([
  60027. BABYLON.serializeAsFresnelParameters()
  60028. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  60029. __decorate([
  60030. BABYLON.serialize()
  60031. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  60032. __decorate([
  60033. BABYLON.serialize()
  60034. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  60035. __decorate([
  60036. BABYLON.serialize()
  60037. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  60038. __decorate([
  60039. BABYLON.serialize()
  60040. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  60041. __decorate([
  60042. BABYLON.serialize()
  60043. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  60044. __decorate([
  60045. BABYLON.serialize()
  60046. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  60047. __decorate([
  60048. BABYLON.serialize()
  60049. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  60050. __decorate([
  60051. BABYLON.serialize()
  60052. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  60053. __decorate([
  60054. BABYLON.serialize()
  60055. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  60056. __decorate([
  60057. BABYLON.serialize()
  60058. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  60059. __decorate([
  60060. BABYLON.serialize()
  60061. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  60062. __decorate([
  60063. BABYLON.serialize()
  60064. ], PBRMaterial.prototype, "useParallax", void 0);
  60065. __decorate([
  60066. BABYLON.serialize()
  60067. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  60068. __decorate([
  60069. BABYLON.serialize()
  60070. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  60071. __decorate([
  60072. BABYLON.serialize()
  60073. ], PBRMaterial.prototype, "disableLighting", void 0);
  60074. __decorate([
  60075. BABYLON.serialize()
  60076. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  60077. __decorate([
  60078. BABYLON.serialize()
  60079. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  60080. __decorate([
  60081. BABYLON.serialize()
  60082. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  60083. __decorate([
  60084. BABYLON.serialize()
  60085. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  60086. return PBRMaterial;
  60087. }(BABYLON.Material));
  60088. BABYLON.PBRMaterial = PBRMaterial;
  60089. })(BABYLON || (BABYLON = {}));
  60090. var BABYLON;
  60091. (function (BABYLON) {
  60092. var DebugLayer = (function () {
  60093. function DebugLayer(scene) {
  60094. var _this = this;
  60095. this._transformationMatrix = BABYLON.Matrix.Identity();
  60096. this._enabled = false;
  60097. this._labelsEnabled = false;
  60098. this._displayStatistics = true;
  60099. this._displayTree = false;
  60100. this._displayLogs = false;
  60101. this._skeletonViewers = new Array();
  60102. this._identityMatrix = BABYLON.Matrix.Identity();
  60103. this.axisRatio = 0.02;
  60104. this.accentColor = "orange";
  60105. this._scene = scene;
  60106. this._syncPositions = function () {
  60107. var engine = _this._scene.getEngine();
  60108. var canvasRect = engine.getRenderingCanvasClientRect();
  60109. if (_this._showUI) {
  60110. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  60111. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  60112. _this._statsDiv.style.width = "400px";
  60113. _this._statsDiv.style.height = "auto";
  60114. _this._statsSubsetDiv.style.maxHeight = "240px";
  60115. _this._optionsDiv.style.left = "0px";
  60116. _this._optionsDiv.style.top = "10px";
  60117. _this._optionsDiv.style.width = "200px";
  60118. _this._optionsDiv.style.height = "auto";
  60119. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  60120. _this._logDiv.style.left = "0px";
  60121. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  60122. _this._logDiv.style.width = "600px";
  60123. _this._logDiv.style.height = "160px";
  60124. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  60125. _this._treeDiv.style.top = "10px";
  60126. _this._treeDiv.style.width = "300px";
  60127. _this._treeDiv.style.height = "auto";
  60128. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  60129. }
  60130. _this._globalDiv.style.left = canvasRect.left + "px";
  60131. _this._globalDiv.style.top = canvasRect.top + "px";
  60132. _this._drawingCanvas.style.left = "0px";
  60133. _this._drawingCanvas.style.top = "0px";
  60134. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  60135. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  60136. var devicePixelRatio = window.devicePixelRatio || 1;
  60137. var context = _this._drawingContext;
  60138. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  60139. context.mozBackingStorePixelRatio ||
  60140. context.msBackingStorePixelRatio ||
  60141. context.oBackingStorePixelRatio ||
  60142. context.backingStorePixelRatio || 1;
  60143. _this._ratio = devicePixelRatio / backingStoreRatio;
  60144. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  60145. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  60146. };
  60147. this._onCanvasClick = function (evt) {
  60148. _this._clickPosition = {
  60149. x: evt.clientX * _this._ratio,
  60150. y: evt.clientY * _this._ratio
  60151. };
  60152. };
  60153. this._syncUI = function () {
  60154. if (_this._showUI) {
  60155. if (_this._displayStatistics) {
  60156. _this._displayStats();
  60157. _this._statsDiv.style.display = "";
  60158. }
  60159. else {
  60160. _this._statsDiv.style.display = "none";
  60161. }
  60162. if (_this._displayLogs) {
  60163. _this._logDiv.style.display = "";
  60164. }
  60165. else {
  60166. _this._logDiv.style.display = "none";
  60167. }
  60168. if (_this._displayTree) {
  60169. _this._treeDiv.style.display = "";
  60170. if (_this._needToRefreshMeshesTree) {
  60171. _this._needToRefreshMeshesTree = false;
  60172. _this._refreshMeshesTreeContent();
  60173. }
  60174. }
  60175. else {
  60176. _this._treeDiv.style.display = "none";
  60177. }
  60178. }
  60179. };
  60180. this._syncData = function () {
  60181. if (_this._labelsEnabled || !_this._showUI) {
  60182. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  60183. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  60184. var engine = _this._scene.getEngine();
  60185. var viewport = _this._camera.viewport;
  60186. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  60187. // Meshes
  60188. var meshes = _this._camera.getActiveMeshes();
  60189. var index;
  60190. var projectedPosition;
  60191. for (index = 0; index < meshes.length; index++) {
  60192. var mesh = meshes.data[index];
  60193. var position = mesh.getBoundingInfo().boundingSphere.center;
  60194. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  60195. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  60196. _this._renderAxis(projectedPosition, mesh, globalViewport);
  60197. }
  60198. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  60199. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  60200. }
  60201. }
  60202. // Cameras
  60203. var cameras = _this._scene.cameras;
  60204. for (index = 0; index < cameras.length; index++) {
  60205. var camera = cameras[index];
  60206. if (camera === _this._camera) {
  60207. continue;
  60208. }
  60209. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  60210. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  60211. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  60212. _this._camera.detachControl(engine.getRenderingCanvas());
  60213. _this._camera = camera;
  60214. _this._camera.attachControl(engine.getRenderingCanvas());
  60215. }, function () { return "purple"; });
  60216. }
  60217. }
  60218. // Lights
  60219. var lights = _this._scene.lights;
  60220. for (index = 0; index < lights.length; index++) {
  60221. var light = lights[index];
  60222. if (light.position) {
  60223. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  60224. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  60225. _this._renderLabel(light.name, projectedPosition, -20, function () {
  60226. light.setEnabled(!light.isEnabled());
  60227. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  60228. }
  60229. }
  60230. }
  60231. }
  60232. _this._clickPosition = undefined;
  60233. };
  60234. }
  60235. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  60236. while (this._treeSubsetDiv.hasChildNodes()) {
  60237. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  60238. }
  60239. // Add meshes
  60240. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  60241. sortedArray.sort(function (a, b) {
  60242. if (a.name === b.name) {
  60243. return 0;
  60244. }
  60245. return (a.name > b.name) ? 1 : -1;
  60246. });
  60247. for (var index = 0; index < sortedArray.length; index++) {
  60248. var mesh = sortedArray[index];
  60249. if (!mesh.isEnabled()) {
  60250. continue;
  60251. }
  60252. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  60253. m.isVisible = element.checked;
  60254. }, mesh);
  60255. }
  60256. };
  60257. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  60258. this._drawingContext.beginPath();
  60259. this._drawingContext.moveTo(zero.x, zero.y);
  60260. this._drawingContext.lineTo(unit.x, unit.y);
  60261. this._drawingContext.strokeStyle = color;
  60262. this._drawingContext.lineWidth = 4;
  60263. this._drawingContext.stroke();
  60264. this._drawingContext.font = "normal 14px Segoe UI";
  60265. this._drawingContext.fillStyle = color;
  60266. this._drawingContext.fillText(label, unitText.x, unitText.y);
  60267. };
  60268. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  60269. var position = mesh.getBoundingInfo().boundingSphere.center;
  60270. var worldMatrix = mesh.getWorldMatrix();
  60271. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  60272. var unit = (unprojectedVector.subtract(position)).length();
  60273. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  60274. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  60275. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  60276. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  60277. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  60278. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  60279. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  60280. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  60281. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  60282. };
  60283. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  60284. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  60285. this._drawingContext.font = "normal 12px Segoe UI";
  60286. var textMetrics = this._drawingContext.measureText(text);
  60287. var centerX = projectedPosition.x - textMetrics.width / 2;
  60288. var centerY = projectedPosition.y;
  60289. var clientRect = this._drawingCanvas.getBoundingClientRect();
  60290. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  60291. onClick();
  60292. }
  60293. this._drawingContext.beginPath();
  60294. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  60295. this._drawingContext.fillStyle = getFillStyle();
  60296. this._drawingContext.globalAlpha = 0.5;
  60297. this._drawingContext.fill();
  60298. this._drawingContext.globalAlpha = 1.0;
  60299. this._drawingContext.strokeStyle = '#FFFFFF';
  60300. this._drawingContext.lineWidth = 1;
  60301. this._drawingContext.stroke();
  60302. this._drawingContext.fillStyle = "#FFFFFF";
  60303. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  60304. this._drawingContext.beginPath();
  60305. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  60306. this._drawingContext.fill();
  60307. }
  60308. };
  60309. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  60310. if (!this._clickPosition) {
  60311. return false;
  60312. }
  60313. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  60314. return false;
  60315. }
  60316. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  60317. return false;
  60318. }
  60319. return true;
  60320. };
  60321. DebugLayer.prototype.isVisible = function () {
  60322. return this._enabled;
  60323. };
  60324. DebugLayer.prototype.hide = function () {
  60325. if (!this._enabled) {
  60326. return;
  60327. }
  60328. this._enabled = false;
  60329. var engine = this._scene.getEngine();
  60330. this._scene.unregisterBeforeRender(this._syncData);
  60331. this._scene.unregisterAfterRender(this._syncUI);
  60332. this._rootElement.removeChild(this._globalDiv);
  60333. this._scene.forceShowBoundingBoxes = false;
  60334. this._scene.forceWireframe = false;
  60335. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  60336. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  60337. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  60338. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  60339. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  60340. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  60341. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  60342. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  60343. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  60344. BABYLON.StandardMaterial.ColorGradingTextureEnabled = true;
  60345. this._scene.shadowsEnabled = true;
  60346. this._scene.particlesEnabled = true;
  60347. this._scene.postProcessesEnabled = true;
  60348. this._scene.collisionsEnabled = true;
  60349. this._scene.lightsEnabled = true;
  60350. this._scene.texturesEnabled = true;
  60351. this._scene.lensFlaresEnabled = true;
  60352. this._scene.proceduralTexturesEnabled = true;
  60353. this._scene.renderTargetsEnabled = true;
  60354. this._scene.probesEnabled = true;
  60355. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  60356. this._clearSkeletonViewers();
  60357. };
  60358. DebugLayer.prototype._clearSkeletonViewers = function () {
  60359. for (var index = 0; index < this._skeletonViewers.length; index++) {
  60360. this._skeletonViewers[index].dispose();
  60361. }
  60362. this._skeletonViewers = [];
  60363. };
  60364. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  60365. if (showUI === void 0) { showUI = true; }
  60366. if (camera === void 0) { camera = null; }
  60367. if (rootElement === void 0) { rootElement = null; }
  60368. if (this._enabled) {
  60369. return;
  60370. }
  60371. this._enabled = true;
  60372. if (camera) {
  60373. this._camera = camera;
  60374. }
  60375. else {
  60376. this._camera = this._scene.activeCamera;
  60377. }
  60378. this._showUI = showUI;
  60379. var engine = this._scene.getEngine();
  60380. this._globalDiv = document.createElement("div");
  60381. this._rootElement = rootElement || document.body;
  60382. this._rootElement.appendChild(this._globalDiv);
  60383. this._generateDOMelements();
  60384. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  60385. this._syncPositions();
  60386. this._scene.registerBeforeRender(this._syncData);
  60387. this._scene.registerAfterRender(this._syncUI);
  60388. };
  60389. DebugLayer.prototype._clearLabels = function () {
  60390. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  60391. for (var index = 0; index < this._scene.meshes.length; index++) {
  60392. var mesh = this._scene.meshes[index];
  60393. mesh.renderOverlay = false;
  60394. }
  60395. };
  60396. DebugLayer.prototype._generateheader = function (root, text) {
  60397. var header = document.createElement("div");
  60398. header.innerHTML = text + "&nbsp;";
  60399. header.style.textAlign = "right";
  60400. header.style.width = "100%";
  60401. header.style.color = "white";
  60402. header.style.backgroundColor = "Black";
  60403. header.style.padding = "5px 5px 4px 0px";
  60404. header.style.marginLeft = "-5px";
  60405. header.style.fontWeight = "bold";
  60406. root.appendChild(header);
  60407. };
  60408. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  60409. var label = document.createElement("label");
  60410. label.style.display = "inline";
  60411. label.innerHTML = title;
  60412. label.style.color = color;
  60413. root.appendChild(label);
  60414. root.appendChild(document.createElement("br"));
  60415. };
  60416. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  60417. if (tag === void 0) { tag = null; }
  60418. var label = document.createElement("label");
  60419. label.style.display = "inline";
  60420. var boundingBoxesCheckbox = document.createElement("input");
  60421. boundingBoxesCheckbox.type = "checkbox";
  60422. boundingBoxesCheckbox.checked = initialState;
  60423. boundingBoxesCheckbox.style.display = "inline";
  60424. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  60425. boundingBoxesCheckbox.style.verticalAlign = "sub";
  60426. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  60427. task(evt.target, tag);
  60428. });
  60429. label.appendChild(boundingBoxesCheckbox);
  60430. var container = document.createElement("span");
  60431. var leftPart = document.createElement("span");
  60432. var rightPart = document.createElement("span");
  60433. rightPart.style.cssFloat = "right";
  60434. leftPart.innerHTML = leftTitle;
  60435. rightPart.innerHTML = rightTitle;
  60436. rightPart.style.fontSize = "12px";
  60437. rightPart.style.maxWidth = "200px";
  60438. container.appendChild(leftPart);
  60439. container.appendChild(rightPart);
  60440. label.appendChild(container);
  60441. root.appendChild(label);
  60442. root.appendChild(document.createElement("br"));
  60443. };
  60444. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  60445. if (tag === void 0) { tag = null; }
  60446. var label = document.createElement("label");
  60447. label.style.display = "inline";
  60448. var checkBox = document.createElement("input");
  60449. checkBox.type = "checkbox";
  60450. checkBox.checked = initialState;
  60451. checkBox.style.display = "inline";
  60452. checkBox.style.margin = "0px 5px 0px 0px";
  60453. checkBox.style.verticalAlign = "sub";
  60454. checkBox.addEventListener("change", function (evt) {
  60455. task(evt.target, tag);
  60456. });
  60457. label.appendChild(checkBox);
  60458. label.appendChild(document.createTextNode(title));
  60459. root.appendChild(label);
  60460. root.appendChild(document.createElement("br"));
  60461. };
  60462. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  60463. if (tag === void 0) { tag = null; }
  60464. var button = document.createElement("button");
  60465. button.innerHTML = title;
  60466. button.style.height = "24px";
  60467. button.style.width = "150px";
  60468. button.style.marginBottom = "5px";
  60469. button.style.color = "#444444";
  60470. button.style.border = "1px solid white";
  60471. button.className = "debugLayerButton";
  60472. button.addEventListener("click", function (evt) {
  60473. task(evt.target, tag);
  60474. });
  60475. root.appendChild(button);
  60476. root.appendChild(document.createElement("br"));
  60477. };
  60478. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  60479. if (tag === void 0) { tag = null; }
  60480. var label = document.createElement("label");
  60481. label.style.display = "inline";
  60482. var boundingBoxesRadio = document.createElement("input");
  60483. boundingBoxesRadio.type = "radio";
  60484. boundingBoxesRadio.name = name;
  60485. boundingBoxesRadio.checked = initialState;
  60486. boundingBoxesRadio.style.display = "inline";
  60487. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  60488. boundingBoxesRadio.style.verticalAlign = "sub";
  60489. boundingBoxesRadio.addEventListener("change", function (evt) {
  60490. task(evt.target, tag);
  60491. });
  60492. label.appendChild(boundingBoxesRadio);
  60493. label.appendChild(document.createTextNode(title));
  60494. root.appendChild(label);
  60495. root.appendChild(document.createElement("br"));
  60496. };
  60497. DebugLayer.prototype._generateDOMelements = function () {
  60498. var _this = this;
  60499. this._globalDiv.id = "DebugLayer";
  60500. this._globalDiv.style.position = "absolute";
  60501. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  60502. this._globalDiv.style.fontSize = "14px";
  60503. this._globalDiv.style.color = "white";
  60504. // Drawing canvas
  60505. this._drawingCanvas = document.createElement("canvas");
  60506. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  60507. this._drawingCanvas.style.position = "absolute";
  60508. this._drawingCanvas.style.pointerEvents = "none";
  60509. this._drawingCanvas.style.backgroundColor = "transparent";
  60510. this._drawingContext = this._drawingCanvas.getContext("2d");
  60511. this._globalDiv.appendChild(this._drawingCanvas);
  60512. if (this._showUI) {
  60513. var background = "rgba(128, 128, 128, 0.4)";
  60514. var border = "rgb(180, 180, 180) solid 1px";
  60515. // Stats
  60516. this._statsDiv = document.createElement("div");
  60517. this._statsDiv.id = "DebugLayerStats";
  60518. this._statsDiv.style.border = border;
  60519. this._statsDiv.style.position = "absolute";
  60520. this._statsDiv.style.background = background;
  60521. this._statsDiv.style.padding = "0px 0px 0px 5px";
  60522. this._generateheader(this._statsDiv, "STATISTICS");
  60523. this._statsSubsetDiv = document.createElement("div");
  60524. this._statsSubsetDiv.style.paddingTop = "5px";
  60525. this._statsSubsetDiv.style.paddingBottom = "5px";
  60526. this._statsSubsetDiv.style.overflowY = "auto";
  60527. this._statsDiv.appendChild(this._statsSubsetDiv);
  60528. // Tree
  60529. this._treeDiv = document.createElement("div");
  60530. this._treeDiv.id = "DebugLayerTree";
  60531. this._treeDiv.style.border = border;
  60532. this._treeDiv.style.position = "absolute";
  60533. this._treeDiv.style.background = background;
  60534. this._treeDiv.style.padding = "0px 0px 0px 5px";
  60535. this._treeDiv.style.display = "none";
  60536. this._generateheader(this._treeDiv, "MESHES TREE");
  60537. this._treeSubsetDiv = document.createElement("div");
  60538. this._treeSubsetDiv.style.paddingTop = "5px";
  60539. this._treeSubsetDiv.style.paddingRight = "5px";
  60540. this._treeSubsetDiv.style.overflowY = "auto";
  60541. this._treeSubsetDiv.style.maxHeight = "300px";
  60542. this._treeDiv.appendChild(this._treeSubsetDiv);
  60543. this._needToRefreshMeshesTree = true;
  60544. // Logs
  60545. this._logDiv = document.createElement("div");
  60546. this._logDiv.style.border = border;
  60547. this._logDiv.id = "DebugLayerLogs";
  60548. this._logDiv.style.position = "absolute";
  60549. this._logDiv.style.background = background;
  60550. this._logDiv.style.padding = "0px 0px 0px 5px";
  60551. this._logDiv.style.display = "none";
  60552. this._generateheader(this._logDiv, "LOGS");
  60553. this._logSubsetDiv = document.createElement("div");
  60554. this._logSubsetDiv.style.height = "127px";
  60555. this._logSubsetDiv.style.paddingTop = "5px";
  60556. this._logSubsetDiv.style.overflowY = "auto";
  60557. this._logSubsetDiv.style.fontSize = "12px";
  60558. this._logSubsetDiv.style.fontFamily = "consolas";
  60559. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  60560. this._logDiv.appendChild(this._logSubsetDiv);
  60561. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  60562. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  60563. };
  60564. // Options
  60565. this._optionsDiv = document.createElement("div");
  60566. this._optionsDiv.id = "DebugLayerOptions";
  60567. this._optionsDiv.style.border = border;
  60568. this._optionsDiv.style.position = "absolute";
  60569. this._optionsDiv.style.background = background;
  60570. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  60571. this._optionsDiv.style.overflowY = "auto";
  60572. this._generateheader(this._optionsDiv, "OPTIONS");
  60573. this._optionsSubsetDiv = document.createElement("div");
  60574. this._optionsSubsetDiv.style.paddingTop = "5px";
  60575. this._optionsSubsetDiv.style.paddingBottom = "5px";
  60576. this._optionsSubsetDiv.style.overflowY = "auto";
  60577. this._optionsSubsetDiv.style.maxHeight = "200px";
  60578. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  60579. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  60580. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  60581. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  60582. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  60583. _this._displayTree = element.checked;
  60584. _this._needToRefreshMeshesTree = true;
  60585. });
  60586. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60587. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  60588. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  60589. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  60590. _this._labelsEnabled = element.checked;
  60591. if (!_this._labelsEnabled) {
  60592. _this._clearLabels();
  60593. }
  60594. });
  60595. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  60596. if (element.checked) {
  60597. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  60598. }
  60599. else {
  60600. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  60601. }
  60602. });
  60603. ;
  60604. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60605. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  60606. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  60607. if (element.checked) {
  60608. _this._scene.forceWireframe = false;
  60609. _this._scene.forcePointsCloud = false;
  60610. }
  60611. });
  60612. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  60613. if (element.checked) {
  60614. _this._scene.forceWireframe = true;
  60615. _this._scene.forcePointsCloud = false;
  60616. }
  60617. });
  60618. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  60619. if (element.checked) {
  60620. _this._scene.forceWireframe = false;
  60621. _this._scene.forcePointsCloud = true;
  60622. }
  60623. });
  60624. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60625. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  60626. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  60627. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  60628. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  60629. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  60630. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  60631. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  60632. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  60633. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  60634. this._generateCheckBox(this._optionsSubsetDiv, "ColorGrading", BABYLON.StandardMaterial.ColorGradingTextureEnabled, function (element) { BABYLON.StandardMaterial.ColorGradingTextureEnabled = element.checked; });
  60635. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  60636. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  60637. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60638. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  60639. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  60640. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  60641. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  60642. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  60643. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  60644. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  60645. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  60646. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  60647. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  60648. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  60649. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  60650. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  60651. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  60652. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  60653. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  60654. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60655. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  60656. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  60657. if (element.checked) {
  60658. _this._scene.headphone = true;
  60659. }
  60660. });
  60661. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  60662. if (element.checked) {
  60663. _this._scene.headphone = false;
  60664. }
  60665. });
  60666. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  60667. _this._scene.audioEnabled = !element.checked;
  60668. });
  60669. }
  60670. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60671. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  60672. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  60673. if (!element.checked) {
  60674. _this._clearSkeletonViewers();
  60675. return;
  60676. }
  60677. for (var index = 0; index < _this._scene.meshes.length; index++) {
  60678. var mesh = _this._scene.meshes[index];
  60679. if (mesh.skeleton) {
  60680. var found = false;
  60681. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  60682. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  60683. found = true;
  60684. break;
  60685. }
  60686. }
  60687. if (found) {
  60688. continue;
  60689. }
  60690. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  60691. viewer.isEnabled = true;
  60692. _this._skeletonViewers.push(viewer);
  60693. }
  60694. }
  60695. });
  60696. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60697. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  60698. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  60699. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  60700. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  60701. if (_this._camera) {
  60702. console.log(_this._camera);
  60703. }
  60704. else {
  60705. console.warn("No camera defined, or debug layer created before camera creation!");
  60706. }
  60707. });
  60708. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60709. this._globalDiv.appendChild(this._statsDiv);
  60710. this._globalDiv.appendChild(this._logDiv);
  60711. this._globalDiv.appendChild(this._optionsDiv);
  60712. this._globalDiv.appendChild(this._treeDiv);
  60713. }
  60714. };
  60715. DebugLayer.prototype._displayStats = function () {
  60716. var scene = this._scene;
  60717. var engine = scene.getEngine();
  60718. var glInfo = engine.getGlInfo();
  60719. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  60720. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  60721. + "<b>Count</b><br>"
  60722. + "Total meshes: " + scene.meshes.length + "<br>"
  60723. + "Total lights: " + scene.lights.length + "<br>"
  60724. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  60725. + "Total materials: " + scene.materials.length + "<br>"
  60726. + "Total textures: " + scene.textures.length + "<br>"
  60727. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  60728. + "Active indices: " + scene.getActiveIndices() + "<br>"
  60729. + "Active bones: " + scene.getActiveBones() + "<br>"
  60730. + "Active particles: " + scene.getActiveParticles() + "<br>"
  60731. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  60732. + "<b>Duration</b><br>"
  60733. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  60734. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  60735. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  60736. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  60737. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  60738. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  60739. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  60740. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  60741. + "</div>"
  60742. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  60743. + "<b>Extensions</b><br>"
  60744. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  60745. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  60746. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  60747. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  60748. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  60749. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  60750. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  60751. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  60752. + "</div><br>"
  60753. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  60754. + "<b>Caps.</b><br>"
  60755. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  60756. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  60757. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  60758. + "<b>Info</b><br>"
  60759. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  60760. + glInfo.version + "<br>"
  60761. + "</div><br>"
  60762. + glInfo.renderer + "<br>";
  60763. if (this.customStatsFunction) {
  60764. this._statsSubsetDiv.innerHTML += this.customStatsFunction();
  60765. }
  60766. };
  60767. return DebugLayer;
  60768. }());
  60769. BABYLON.DebugLayer = DebugLayer;
  60770. })(BABYLON || (BABYLON = {}));
  60771. 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 sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (color.a == 0.05) {\ndiscard;\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 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);\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*sizeUV.x)+off.x,topLeftUV.y-off.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x+(frame*sizeUV.x)+off.x,(topLeftUV.y+sizeUV.y));\n}\n\nelse if (index == 2.0) {\npos2=vec2( 1.0,1.0);\nvUV=vec2(topLeftUV.x+sizeUV.x+(frame*sizeUV.x),(topLeftUV.y+sizeUV.y));\n}\n\nelse if (index == 3.0) {\npos2=vec2( 1.0,0.0);\nvUV=vec2(topLeftUV.x+sizeUV.x+(frame*sizeUV.x),topLeftUV.y-off.y);\n}\nif (invertY == 1.0) {\nvUV.y=1.0-vUV.y;\n}\nvec4 pos;\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","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);\nif (color.a<0.05)\ndiscard;\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}"};
  60772. 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"};
  60773. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:!(o.z-i>e.z)},o=function(){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(0>r)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&&s>c?(t.root=c,t.found=!0,t):h>0&&s>h?(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 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var 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&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),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&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),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&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?(0===i.x&&0===i.y&&0===i.z||t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,r){void 0===r&&(r=1.401298e-45);var n=t-i;return n>=-r&&r>=n},t.ToHex=function(t){var i=t.toString(16);return 15>=t?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,r){return void 0===i&&(i=0),void 0===r&&(r=1),Math.min(r,Math.max(i,t))},t}();t.MathTools=i;var r=function(){function r(t,i,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),this.r=t,this.g=i,this.b=r}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.prototype.getClassName=function(){return\"Color3\"},r.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new n(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,r){return this.r===t&&this.g===i&&this.b===r},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,r){return this.r=t,this.g=i,this.b=r,this},r.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},r.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new r(0,0,0);var i=parseInt(t.substring(1,3),16),n=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return r.FromInts(i,n,o)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,e=t.g+(i.g-t.g)*n,s=t.b+(i.b-t.b)*n;return new r(o,e,s)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r}();t.Color3=r;var n=function(){function t(t,i,r,n){this.r=t,this.g=i,this.b=r,this.a=n}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,i.a=this.a*t.a,i},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.getClassName=function(){return\"Color4\"},t.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0),t=397*t^(this.a||0)},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var r=parseInt(i.substring(1,3),16),n=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return t.FromInts(r,n,o,e)},t.Lerp=function(i,r,n){var o=new t(0,0,0,0);return t.LerpToRef(i,r,n,o),o},t.LerpToRef=function(t,i,r,n){n.r=t.r+(i.r-t.r)*r,n.g=t.g+(i.g-t.g)*r,n.b=t.b+(i.b-t.b)*r,n.a=t.a+(i.a-t.a)*r},t.FromArray=function(i,r){return void 0===r&&(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.FromInts=function(i,r,n,o){return new t(i/255,r/255,n/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var r=[],n=0;n<t.length;n+=3){var o=n/3*4;r[o]=t[n],r[o+1]=t[n+1],r[o+2]=t[n+2],r[o+3]=1}return r}return t},t}();t.Color4=n;var o=function(){function r(t,i){this.x=t,this.y=i}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},r.prototype.getClassName=function(){return\"Vector2\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},r.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},r.prototype.addVector3=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},r.prototype.multiplyByFloats=function(t,i){return new r(this.x*t,this.y*i)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},r.prototype.negate=function(){return new r(-this.x,-this.y)},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t)},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},r.prototype.clone=function(){return new r(this.x,this.y)},r.Zero=function(){return new r(0,0)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h);return new r(a,u)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>n.y?n.y:e,e=e<i.y?i.y:e,new r(o,e)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y;return new r(c,p)},r.Lerp=function(t,i,n){var o=t.x+(i.x-t.x)*n,e=t.y+(i.y-t.y)*n;return new r(o,e)},r.Dot=function(t,i){return t.x*i.x+t.y*i.y},r.Normalize=function(t){var i=t.clone();return i.normalize(),i},r.Minimize=function(t,i){var n=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new r(n,o)},r.Maximize=function(t,i){var n=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new r(n,o)},r.Transform=function(t,i){var n=r.Zero();return r.TransformToRef(t,i,n),n},r.TransformToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];r.x=n,r.y=o},r.PointInTriangle=function(t,i,r,n){var o=.5*(-r.y*n.x+i.y*(-r.x+n.x)+i.x*(r.y-n.y)+r.x*n.y),e=0>o?-1:1,s=(i.y*n.x-i.x*n.y+(n.y-i.y)*t.x+(i.x-n.x)*t.y)*e,h=(i.x*r.y-i.y*r.x+(i.y-r.y)*t.x+(r.x-i.x)*t.y)*e;return s>0&&h>0&&2*o*e>s+h},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y;return r*r+n*n},r.DistanceOfPointFromSegment=function(t,i,n){var o=r.DistanceSquared(i,n);if(0===o)return r.Distance(t,i);var e=n.subtract(i),s=Math.max(0,Math.min(1,r.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return r.Distance(t,h)},r}();t.Vector2=o;var e=function(){function r(t,i,r){this.x=t,this.y=i,this.z=r}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},r.prototype.getClassName=function(){return\"Vector3\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},r.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),r=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),e=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return t.x=n*s,t.y=-o*s,t.z=r*e,t.w=i*e,t},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},r.prototype.subtractFromFloats=function(t,i,n){return new r(this.x-t,this.y-i,this.z-n)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-r,this},r.prototype.negate=function(){return new r(-this.x,-this.y,-this.z)},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t)},r.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)},r.prototype.equalsToFloats=function(t,i,r){return this.x===t&&this.y===i&&this.z===r},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},r.prototype.multiplyByFloats=function(t,i,n){return new r(this.x*t,this.y*i,this.z*n)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},r.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},r.prototype.clone=function(){return new r(this.x,this.y,this.z)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},r.prototype.copyFromFloats=function(t,i,r){return this.x=t,this.y=i,this.z=r,this},r.GetClipFactor=function(t,i,n,o){var e=r.Dot(t,n)-o,s=r.Dot(i,n)-o,h=e/(e-s);return h},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromFloatArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatsToRef=function(t,i,r,n){n.x=t,n.y=i,n.z=r},r.Zero=function(){return new r(0,0,0)},r.Up=function(){return new r(0,1,0)},r.TransformCoordinates=function(t,i){var n=r.Zero();return r.TransformCoordinatesToRef(t,i,n),n},r.TransformCoordinatesToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],s=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];r.x=n/s,r.y=o/s,r.z=e/s},r.TransformCoordinatesFromFloatsToRef=function(t,i,r,n,o){var e=t*n.m[0]+i*n.m[4]+r*n.m[8]+n.m[12],s=t*n.m[1]+i*n.m[5]+r*n.m[9]+n.m[13],h=t*n.m[2]+i*n.m[6]+r*n.m[10]+n.m[14],a=t*n.m[3]+i*n.m[7]+r*n.m[11]+n.m[15];o.x=e/a,o.y=s/a,o.z=h/a},r.TransformNormal=function(t,i){var n=r.Zero();return r.TransformNormalToRef(t,i,n),n},r.TransformNormalToRef=function(t,i,r){r.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],r.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],r.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},r.TransformNormalFromFloatsToRef=function(t,i,r,n,o){o.x=t*n.m[0]+i*n.m[4]+r*n.m[8],o.y=t*n.m[1]+i*n.m[5]+r*n.m[9],o.z=t*n.m[2]+i*n.m[6]+r*n.m[10]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h),m=.5*(2*i.z+(-t.z+n.z)*e+(2*t.z-5*i.z+4*n.z-o.z)*s+(-t.z+3*i.z-3*n.z+o.z)*h);return new r(a,u,m)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>n.y?n.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>n.z?n.z:s,s=s<i.z?i.z:s,new r(o,e,s)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y,f=t.z*a+n.z*u+i.z*m+o.z*y;return new r(c,p,f)},r.Lerp=function(t,i,n){var o=t.x+(i.x-t.x)*n,e=t.y+(i.y-t.y)*n,s=t.z+(i.z-t.z)*n;return new r(o,e,s)},r.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},r.Cross=function(t,i){var n=r.Zero();return r.CrossToRef(t,i,n),n},r.CrossToRef=function(t,i,r){M.Vector3[0].x=t.y*i.z-t.z*i.y,M.Vector3[0].y=t.z*i.x-t.x*i.z,M.Vector3[0].z=t.x*i.y-t.y*i.x,r.copyFrom(M.Vector3[0])},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Project=function(t,i,n,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=r._viewportMatrixCache?r._viewportMatrixCache:r._viewportMatrixCache=new u;u.FromValuesToRef(e/2,0,0,0,0,-s/2,0,0,0,0,1,0,h+e/2,s/2+a,0,1,m);var y=r._matrixCache?r._matrixCache:r._matrixCache=new u;return i.multiplyToRef(n,y),y.multiplyToRef(m,y),r.TransformCoordinates(t,y)},r.UnprojectFromTransform=function(t,n,o,e,s){var h=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,h),h.invert(),t.x=t.x/n*2-1,t.y=-(t.y/o*2-1);var a=r.TransformCoordinates(t,h),m=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(m,1)&&(a=a.scale(1/m)),a},r.Unproject=function(t,n,o,e,s,h){var a=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,a),a.multiplyToRef(h,a),a.invert();var m=new r(t.x/n*2-1,-(t.y/o*2-1),t.z),y=r.TransformCoordinates(m,a),c=m.x*a.m[3]+m.y*a.m[7]+m.z*a.m[11]+a.m[15];return i.WithinEpsilon(c,1)&&(y=y.scale(1/c)),y},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z;return r*r+n*n+o*o},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.RotationFromAxis=function(t,i,n){var o=r.Zero();return r.RotationFromAxisToRef(t,i,n,o),o},r.RotationFromAxisToRef=function(n,o,e,s){var h=n.normalize(),a=e.normalize(),u=p.X,m=p.Y,y=0,c=0,f=0,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(),r.CrossToRef(h,R,g),g.normalize(),r.Dot(a,g)<0&&(v=1),T=r.Dot(h,R),T=Math.min(1,Math.max(-1,T)),f=Math.acos(T)*v,r.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(),r.CrossToRef(_,R,b),b.normalize(),r.CrossToRef(a,_,g),g.normalize(),r.Dot(R,g)<0&&(v=1),T=r.Dot(a,_),T=Math.min(1,Math.max(-1,T)),c=Math.acos(T)*v,r.Dot(b,m)<0&&(c=Math.PI+c,d++),v=-1,r.CrossToRef(u,R,g),g.normalize(),r.Dot(g,m)<0&&(v=1),T=r.Dot(R,u),T=Math.min(1,Math.max(-1,T)),y=-Math.acos(T)*v,0>T&&2>d&&(y=Math.PI+y),s.x=c,s.y=y,s.z=f},r}();t.Vector3=e;var s=function(){function r(t,i,r,n){this.x=t,this.y=i,this.z=r,this.w=n}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},r.prototype.getClassName=function(){return\"Vector4\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},r.prototype.subtractFromFloats=function(t,i,n,o){return new r(this.x-t,this.y-i,this.z-n,this.w-o)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-r,o.w=this.w-n,this},r.prototype.negate=function(){return new r(-this.x,-this.y,-this.z,-this.w)},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t,this.w*t)},r.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)&&i.WithinEpsilon(this.w,r.w,n)},r.prototype.equalsToFloats=function(t,i,r,n){return this.x===t&&this.y===i&&this.z===r&&this.w===n},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},r.prototype.multiplyByFloats=function(t,i,n,o){return new r(this.x*t,this.y*i,this.z*n,this.w*o)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},r.prototype.toVector3=function(){return new e(this.x,this.y,this.z)},r.prototype.clone=function(){return new r(this.x,this.y,this.z,this.w)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},r.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2],t[i+3])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatsToRef=function(t,i,r,n,o){o.x=t,o.y=i,o.z=r,o.w=n},r.Zero=function(){return new r(0,0,0,0)},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z,e=t.w-i.w;return r*r+n*n+o*o+e*e},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r}();t.Vector4=s;var h=function(){function t(t,i){this.width=t,this.height=i}return t.prototype.toString=function(){return\"{W: \"+this.width+\", H: \"+this.height+\"}\"},t.prototype.getClassName=function(){return\"Size\"},t.prototype.getHashCode=function(){var t=this.width||0;return t=397*t^(this.height||0)},t.prototype.copyFrom=function(t){this.width=t.width,this.height=t.height},t.prototype.copyFromFloats=function(t,i){this.width=t,this.height=i},t.prototype.multiplyByFloats=function(i,r){return new t(this.width*i,this.height*r)},t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return t?this.width===t.width&&this.height===t.height:!1},Object.defineProperty(t.prototype,\"surface\",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),t.Zero=function(){return new t(0,0)},t.prototype.add=function(i){var r=new t(this.width+i.width,this.height+i.height);return r},t.prototype.substract=function(i){var r=new t(this.width-i.width,this.height-i.height);return r},t.Lerp=function(i,r,n){var o=i.width+(r.width-i.width)*n,e=i.height+(r.height-i.height)*n;return new t(o,e)},t}();t.Size=h;var a=function(){function t(t,i,r,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=r,this.w=n}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.getClassName=function(){return\"Quaternion\"},t.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var r=new t(0,0,0,1);return this.multiplyToRef(i,r),r},t.prototype.multiplyToRef=function(t,i){var r=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,n=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,e=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(r,n,o,e),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t(-this.x,-this.y,-this.z,this.w);return i},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var r,n,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&&(r=2*Math.atan2(e,a),n=Math.PI/2,o=0),-.499>u&&(r=-2*Math.atan2(e,a),n=-Math.PI/2,o=0),isNaN(r)){var m=e*e,y=s*s,c=h*h;r=Math.atan2(2*s*a-2*e*h,1-2*y-2*c),n=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=r,t.z=n,t.x=o,this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,r=this.y*this.y,n=this.z*this.z,o=this.x*this.y,e=this.z*this.w,s=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(r+n),t.m[1]=2*(o+e),t.m[2]=2*(s-h),t.m[3]=0,t.m[4]=2*(o-e),t.m[5]=1-2*(n+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(s+h),t.m[9]=2*(a-u),t.m[10]=1-2*(r+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var r=new t;return t.FromRotationMatrixToRef(i,r),r},t.FromRotationMatrixToRef=function(t,i){var r,n=t.m,o=n[0],e=n[4],s=n[8],h=n[1],a=n[5],u=n[9],m=n[2],y=n[6],c=n[10],p=o+a+c;p>0?(r=.5/Math.sqrt(p+1),i.w=.25/r,i.x=(y-u)*r,i.y=(s-m)*r,i.z=(h-e)*r):o>a&&o>c?(r=2*Math.sqrt(1+o-a-c),i.w=(y-u)/r,i.x=.25*r,i.y=(e+h)/r,i.z=(s+m)/r):a>c?(r=2*Math.sqrt(1+a-o-c),i.w=(s-m)/r,i.x=(e+h)/r,i.y=.25*r,i.z=(u+y)/r):(r=2*Math.sqrt(1+c-o-a),i.w=(h-e)/r,i.x=(s+m)/r,i.y=(u+y)/r,i.z=.25*r)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,r){return t.RotationAxisToRef(i,r,new t)},t.RotationAxisToRef=function(t,i,r){var n=Math.sin(i/2);return t.normalize(),r.w=Math.cos(i/2),r.x=t.x*n,r.y=t.y*n,r.z=t.z*n,r},t.FromArray=function(i,r){return r||(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.RotationYawPitchRoll=function(i,r,n){var o=new t;return t.RotationYawPitchRollToRef(i,r,n,o),o},t.RotationYawPitchRollToRef=function(t,i,r,n){var o=.5*r,e=.5*i,s=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(e),m=Math.cos(e),y=Math.sin(s),c=Math.cos(s);n.x=c*u*a+y*m*h,n.y=y*m*a-c*u*h,n.z=c*m*h-y*u*a,n.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,r,n){var o=new t;return t.RotationAlphaBetaGammaToRef(i,r,n,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,r,n){var o=.5*(r+t),e=.5*(r-t),s=.5*i;n.x=Math.cos(e)*Math.sin(s),n.y=Math.sin(e)*Math.sin(s),n.z=Math.sin(o)*Math.cos(s),n.w=Math.cos(o)*Math.cos(s)},t.Slerp=function(i,r,n){var o,e,s=n,h=i.x*r.x+i.y*r.y+i.z*r.z+i.w*r.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)e=1-s,o=a?-s:s;else{var u=Math.acos(h),m=1/Math.sin(u);e=Math.sin((1-s)*u)*m,o=a?-Math.sin(s*u)*m:Math.sin(s*u)*m}return new t(e*i.x+o*r.x,e*i.y+o*r.y,e*i.z+o*r.z,e*i.w+o*r.w)},t}();t.Quaternion=a;var u=function(){function t(){this.m=new Float32Array(16)}return t.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14]},t.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],r=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],e=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*r)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*e)-this.m[3]*(this.m[4]*r-this.m[5]*o+this.m[6]*e)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},t.prototype.add=function(i){var r=new t;return this.addToRef(i,r),r},t.prototype.addToRef=function(t,i){for(var r=0;16>r;r++)i.m[r]=this.m[r]+t.m[r];return this},t.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],r=this.m[1],n=this.m[2],o=this.m[3],e=this.m[4],s=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],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+r*_+n*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,q=s*c-a*m,H=s*y-h*m,N=e*c-a*u,V=e*y-h*u,D=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]=-(r*z-n*w+o*v)*F,t.m[5]=(i*z-n*d+o*g)*F,t.m[9]=-(i*w-r*d+o*T)*F,t.m[13]=(i*v-r*g+n*T)*F,t.m[2]=(r*A-n*L+o*C)*F,t.m[6]=-(i*A-n*P+o*Z)*F,t.m[10]=(i*L-r*P+o*S)*F,t.m[14]=-(i*C-r*Z+n*S)*F,t.m[3]=-(r*I-n*q+o*H)*F,t.m[7]=(i*I-n*N+o*V)*F,t.m[11]=-(i*q-r*N+o*D)*F,t.m[15]=(i*H-r*V+n*D)*F,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.getTranslation=function(){return new e(this.m[12],this.m[13],this.m[14])},t.prototype.multiply=function(i){var r=new t;return this.multiplyToRef(i,r),r},t.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},t.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var r=0;16>r;r++)t[i+r]=this.m[r];return this},t.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},t.prototype.multiplyToArray=function(t,i,r){var n=this.m[0],o=this.m[1],e=this.m[2],s=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],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];\nreturn i[r]=n*v+o*R+e*F+s*P,i[r+1]=n*d+o*_+e*A+s*Z,i[r+2]=n*g+o*M+e*L+s*S,i[r+3]=n*T+o*b+e*C+s*I,i[r+4]=h*v+a*R+u*F+m*P,i[r+5]=h*d+a*_+u*A+m*Z,i[r+6]=h*g+a*M+u*L+m*S,i[r+7]=h*T+a*b+u*C+m*I,i[r+8]=y*v+c*R+p*F+f*P,i[r+9]=y*d+c*_+p*A+f*Z,i[r+10]=y*g+c*M+p*L+f*S,i[r+11]=y*T+c*b+p*C+f*I,i[r+12]=l*v+x*R+z*F+w*P,i[r+13]=l*d+x*_+z*A+w*Z,i[r+14]=l*g+x*M+z*L+w*S,i[r+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;16>i;i++)t=397*t^(this.m[i]||0);return t},t.prototype.decompose=function(r,n,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var e=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,s=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(r.x=e*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),r.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),r.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===r.x||0===r.y||0===r.z)return n.x=0,n.y=0,n.z=0,n.w=1,!1;var u=t.FromValues(this.m[0]/r.x,this.m[1]/r.x,this.m[2]/r.x,0,this.m[4]/r.y,this.m[5]/r.y,this.m[6]/r.y,0,this.m[8]/r.z,this.m[9]/r.z,this.m[10]/r.z,0,0,0,0,1);return a.FromRotationMatrixToRef(u,n),!0},t.FromArray=function(i,r){var n=new t;return r||(r=0),t.FromArrayToRef(i,r,n),n},t.FromArrayToRef=function(t,i,r){for(var n=0;16>n;n++)r.m[n]=t[n+i]},t.FromFloat32ArrayToRefScaled=function(t,i,r,n){for(var o=0;16>o;o++)n.m[o]=t[o+i]*r},t.FromValuesToRef=function(t,i,r,n,o,e,s,h,a,u,m,y,c,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=r,x.m[3]=n,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(0>t||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(0>t||t>3)return this;var r=4*t;return this.m[r+0]=i.x,this.m[r+1]=i.y,this.m[r+2]=i.z,this.m[r+3]=i.w,this},t.FromValues=function(i,r,n,o,e,s,h,a,u,m,y,c,p,f,l,x){var z=new t;return z.m[0]=i,z.m[1]=r,z.m[2]=n,z.m[3]=o,z.m[4]=e,z.m[5]=s,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},t.Compose=function(i,r,n){var o=t.FromValues(i.x,0,0,0,0,i.y,0,0,0,0,i.z,0,0,0,0,1),e=t.Identity();return r.toRotationMatrix(e),o=o.multiply(e),o.setTranslation(n),o},t.Identity=function(){return t.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},t.IdentityToRef=function(i){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i)},t.Zero=function(){return t.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},t.RotationX=function(i){var r=new t;return t.RotationXToRef(i,r),r},t.Invert=function(i){var r=new t;return i.invertToRef(r),r},t.RotationXToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-r,i.m[6]=r,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationY=function(i){var r=new t;return t.RotationYToRef(i,r),r},t.RotationYToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-r,i.m[8]=r,i.m[10]=n,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationZ=function(i){var r=new t;return t.RotationZToRef(i,r),r},t.RotationZToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=r,i.m[4]=-r,i.m[5]=n,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationAxis=function(i,r){var n=t.Zero();return t.RotationAxisToRef(i,r,n),n},t.RotationAxisToRef=function(t,i,r){var n=Math.sin(-i),o=Math.cos(-i),e=1-o;t.normalize(),r.m[0]=t.x*t.x*e+o,r.m[1]=t.x*t.y*e-t.z*n,r.m[2]=t.x*t.z*e+t.y*n,r.m[3]=0,r.m[4]=t.y*t.x*e+t.z*n,r.m[5]=t.y*t.y*e+o,r.m[6]=t.y*t.z*e-t.x*n,r.m[7]=0,r.m[8]=t.z*t.x*e-t.y*n,r.m[9]=t.z*t.y*e+t.x*n,r.m[10]=t.z*t.z*e+o,r.m[11]=0,r.m[15]=1},t.RotationYawPitchRoll=function(i,r,n){var o=new t;return t.RotationYawPitchRollToRef(i,r,n,o),o},t.RotationYawPitchRollToRef=function(t,i,r,n){a.RotationYawPitchRollToRef(t,i,r,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},t.Scaling=function(i,r,n){var o=t.Zero();return t.ScalingToRef(i,r,n,o),o},t.ScalingToRef=function(t,i,r,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=r,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},t.Translation=function(i,r,n){var o=t.Identity();return t.TranslationToRef(i,r,n,o),o},t.TranslationToRef=function(i,r,n,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,r,n,1,o)},t.Lerp=function(i,r,n){for(var o=t.Zero(),e=0;16>e;e++)o.m[e]=i.m[e]*(1-n)+r.m[e]*n;return o},t.DecomposeLerp=function(i,r,n){var o=new e(0,0,0),s=new a,h=new e(0,0,0);i.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);r.decompose(u,m,y);var c=e.Lerp(o,u,n),p=a.Slerp(s,m,n),f=e.Lerp(h,y,n);return t.Compose(c,p,f)},t.LookAtLH=function(i,r,n){var o=t.Zero();return t.LookAtLHToRef(i,r,n,o),o},t.LookAtLHToRef=function(i,r,n,o){r.subtractToRef(i,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,i),h=-e.Dot(this._yAxis,i),a=-e.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},t.OrthoLH=function(i,r,n,o){var e=t.Zero();return t.OrthoLHToRef(i,r,n,o,e),e},t.OrthoLHToRef=function(i,r,n,o,e){var s=2/i,h=2/r,a=1/(o-n),u=n/(n-o);t.FromValuesToRef(s,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,e)},t.OrthoOffCenterLH=function(i,r,n,o,e,s){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,r,n,o,e,s,h),h},t.OrthoOffCenterLHToRef=function(t,i,r,n,o,e,s){s.m[0]=2/(i-t),s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2/(n-r),s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-1/(o-e),s.m[8]=s.m[9]=s.m[11]=0,s.m[12]=(t+i)/(t-i),s.m[13]=(n+r)/(r-n),s.m[14]=o/(o-e),s.m[15]=1},t.PerspectiveLH=function(i,r,n,o){var e=t.Zero();return e.m[0]=2*n/i,e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2*n/r,e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-o/(n-o),e.m[8]=e.m[9]=0,e.m[11]=1,e.m[12]=e.m[13]=e.m[15]=0,e.m[14]=n*o/(n-o),e},t.PerspectiveFovLH=function(i,r,n,o){var e=t.Zero();return t.PerspectiveFovLHToRef(i,r,n,o,e),e},t.PerspectiveFovLHToRef=function(t,i,r,n,o,e){void 0===e&&(e=!0);var s=1/Math.tan(.5*t);e?o.m[0]=s/i:o.m[0]=s,o.m[1]=o.m[2]=o.m[3]=0,e?o.m[5]=s:o.m[5]=s*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=-n/(r-n),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=r*n/(r-n)},t.GetFinalMatrix=function(i,r,n,o,e,s){var h=i.width,a=i.height,u=i.x,m=i.y,y=t.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,s-e,0,u+h/2,a/2+m,e,1);return r.multiply(n).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},t.Transpose=function(i){var r=new t;return r.m[0]=i.m[0],r.m[1]=i.m[4],r.m[2]=i.m[8],r.m[3]=i.m[12],r.m[4]=i.m[1],r.m[5]=i.m[5],r.m[6]=i.m[9],r.m[7]=i.m[13],r.m[8]=i.m[2],r.m[9]=i.m[6],r.m[10]=i.m[10],r.m[11]=i.m[14],r.m[12]=i.m[3],r.m[13]=i.m[7],r.m[14]=i.m[11],r.m[15]=i.m[15],r},t.Reflection=function(i){var r=new t;return t.ReflectionToRef(i,r),r},t.ReflectionToRef=function(t,i){t.normalize();var r=t.normal.x,n=t.normal.y,o=t.normal.z,e=-2*r,s=-2*n,h=-2*o;i.m[0]=e*r+1,i.m[1]=s*r,i.m[2]=h*r,i.m[3]=0,i.m[4]=e*n,i.m[5]=s*n+1,i.m[6]=h*n,i.m[7]=0,i.m[8]=e*o,i.m[9]=s*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=e*t.d,i.m[13]=s*t.d,i.m[14]=h*t.d,i.m[15]=1},t._tempQuaternion=new a,t._xAxis=e.Zero(),t._yAxis=e.Zero(),t._zAxis=e.Zero(),t}();t.Matrix=u;var m=function(){function t(t,i,r,n){this.normal=new e(t,i,r),this.d=n}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.getClassName=function(){return\"Plane\"},t.prototype.getHashCode=function(){var t=this.normal.getHashCode();return t=397*t^(this.d||0)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var r=u.Transpose(i),n=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d,h=n*r.m[0]+o*r.m[1]+e*r.m[2]+s*r.m[3],a=n*r.m[4]+o*r.m[5]+e*r.m[6]+s*r.m[7],m=n*r.m[8]+o*r.m[9]+e*r.m[10]+s*r.m[11],y=n*r.m[12]+o*r.m[13]+e*r.m[14]+s*r.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,r){var n,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=r.x-t.x,a=r.y-t.y,u=r.z-t.z,m=e*u-s*a,y=s*h-o*u,c=o*a-e*h,p=Math.sqrt(m*m+y*y+c*c);return n=0!==p?1/p:0,this.normal.x=m*n,this.normal.y=y*n,this.normal.z=c*n,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var r=e.Dot(this.normal,t);return i>=r},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,r,n){var o=new t(0,0,0,0);return o.copyFromPoints(i,r,n),o},t.FromPositionAndNormal=function(i,r){var n=new t(0,0,0,0);return r.normalize(),n.normal=r,n.d=-(r.x*i.x+r.y*i.y+r.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,r){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(r,i)+n},t}();t.Plane=m;var y=function(){function t(t,i,r,n){this.x=t,this.y=i,this.width=r,this.height=n}return t.prototype.toGlobal=function(i,r){return new t(this.x*i,this.y*r,this.width*i,this.height*r)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var r=[],n=0;6>n;n++)r.push(new m(0,0,0,0));return t.GetPlanesToRef(i,r),r},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var p=(t.Space,function(){function t(){}return t.X=new e(1,0,0),t.Y=new e(0,1,0),t.Z=new e(0,0,1),t}());t.Axis=p;var f=function(){function t(){}return t.interpolate=function(t,i,r,n,o){for(var e=1-3*n+3*i,s=3*n-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=e*y+s*m+h*a,p=1/(3*e*m+2*s*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*r+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=f,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var 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,r){var n=r.subtract(i),o=Math.atan2(n.y,n.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=x;var z=function(){function t(t,i,r){this.startPoint=t,this.midPoint=i,this.endPoint=r;var n=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-n)/2,s=(n-Math.pow(r.x,2)-Math.pow(r.y,2))/2,h=(t.x-i.x)*(i.y-r.y)-(i.x-r.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-r.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-r.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=x.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=x.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=x.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?l.CW:l.CCW,this.angle=x.FromDegrees(this.orientation===l.CW?a-m:m-a)}return t}();t.Arc2=z;var w=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var r=new o(t,i),n=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(n).length(),this},t.prototype.addArcTo=function(t,i,r,n,e){if(void 0===e&&(e=36),closed)return this;var s=this._points[this._points.length-1],h=new o(t,i),a=new o(r,n),u=new z(s,h,a),m=u.angle.radians()/e;u.orientation===l.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;e>c;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],r=this._points[0];t+=r.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(0>t||t>1)return o.Zero();for(var i=t*this.length(),r=0,n=0;n<this._points.length;n++){var e=(n+1)%this._points.length,s=this._points[n],h=this._points[e],a=h.subtract(s),u=a.length()+r;if(i>=r&&u>=i){var m=a.normalize(),y=i-r;return new o(s.x+m.x*y,s.y+m.y*y)}r=u}return o.Zero()},t.StartingAt=function(i,r){return new t(i,r)},t}();t.Path2=w;var v=function(){function r(t,i,r){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var n=0;n<t.length;n++)this._curve[n]=t[n].clone();this._raw=r||!1,this._compute(i)}return r.prototype.getCurve=function(){return this._curve},r.prototype.getTangents=function(){return this._tangents},r.prototype.getNormals=function(){return this._normals},r.prototype.getBinormals=function(){return this._binormals},r.prototype.getDistances=function(){return this._distances},r.prototype.update=function(t,i){for(var r=0;r<t.length;r++)this._curve[r].x=t[r].x,this._curve[r].y=t[r].y,this._curve[r].z=t[r].z;return this._compute(i),this},r.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var r=this._tangents[0],n=this._normalVector(this._curve[0],r,t);this._normals[0]=n,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(r,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},r.prototype._getFirstNonNullVector=function(t){for(var i=1,r=this._curve[t+i].subtract(this._curve[t]);0===r.length()&&t+i+1<this._curve.length;)i++,r=this._curve[t+i].subtract(this._curve[t]);return r},r.prototype._getLastNonNullVector=function(t){for(var i=1,r=this._curve[t].subtract(this._curve[t-i]);0===r.length()&&t>i+1;)i++,r=this._curve[t].subtract(this._curve[t-i]);return r},r.prototype._normalVector=function(r,n,o){var s;if(void 0===o||null===o){var h;i.WithinEpsilon(n.y,1,t.Epsilon)?i.WithinEpsilon(n.x,1,t.Epsilon)?i.WithinEpsilon(n.z,1,t.Epsilon)||(h=new e(0,0,1)):h=new e(1,0,0):h=new e(0,-1,0),s=e.Cross(n,h)}else s=e.Cross(n,o),e.CrossToRef(s,n,s);return s.normalize(),s},r}();t.Path3D=v;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,r,n,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,r,n){var o=(1-t)*(1-t)*i+2*t*(1-t)*r+t*t*n;return o},a=0;o>=a;a++)s.push(new e(h(a/o,i.x,r.x,n.x),h(a/o,i.y,r.y,n.y),h(a/o,i.z,r.z,n.z)));return new t(s)},t.CreateCubicBezier=function(i,r,n,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,r,n,o){var e=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*r+3*t*t*(1-t)*n+t*t*t*o;return e},u=0;s>=u;u++)h.push(new e(a(u/s,i.x,r.x,n.x,o.x),a(u/s,i.y,r.y,n.y,o.y),a(u/s,i.z,r.z,n.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,r,n,o,s){for(var h=new Array,a=1/s,u=0;s>=u;u++)h.push(e.Hermite(i,r,n,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var r=this._points[this._points.length-1],n=this._points.slice(),o=i.getPoints(),e=1;e<o.length;e++)n.push(o[e].subtract(o[0]).add(r));var s=new t(n);return s},t.prototype._computeLength=function(t){for(var i=0,r=1;r<t.length;r++)i+=t[r].subtract(t[r-1]).length();return i},t}();t.Curve3=d;var g=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,r){var n=new e(i.r,i.g,i.b),o=n.scale(r);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=g;var 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 r=new t;return r.x=i.L11.scale(1.02333),r.y=i.L1_1.scale(1.02333),r.z=i.L10.scale(1.02333),r.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),r.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),r.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),r.yz=i.L2_1.scale(.858086),r.zx=i.L21.scale(.858086),r.xy=i.L2_2.scale(.858086),r},t}();t.SphericalPolynomial=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,r){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===r&&(r=o.Zero()),this.position=t,this.normal=i,this.uv=r}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_;var M=function(){function t(){}return t.Color3=[r.Black(),r.Black(),r.Black()],t.Vector2=[o.Zero(),o.Zero(),o.Zero()],t.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],t.Vector4=[s.Zero(),s.Zero(),s.Zero()],t.Quaternion=[new a(0,0,0,0)],t.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t}();t.Tmp=M}(BABYLON||(BABYLON={}));";
  60774. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  60775. module.exports = BABYLON;
  60776. };