babylon.max.js 3.2 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || function (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. })();
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. Color3.prototype.getClassName = function () {
  62. return "Color3";
  63. };
  64. Color3.prototype.getHashCode = function () {
  65. var hash = this.r || 0;
  66. hash = (hash * 397) ^ (this.g || 0);
  67. hash = (hash * 397) ^ (this.b || 0);
  68. return hash;
  69. };
  70. // Operators
  71. Color3.prototype.toArray = function (array, index) {
  72. if (index === undefined) {
  73. index = 0;
  74. }
  75. array[index] = this.r;
  76. array[index + 1] = this.g;
  77. array[index + 2] = this.b;
  78. return this;
  79. };
  80. Color3.prototype.toColor4 = function (alpha) {
  81. if (alpha === void 0) { alpha = 1; }
  82. return new Color4(this.r, this.g, this.b, alpha);
  83. };
  84. Color3.prototype.asArray = function () {
  85. var result = [];
  86. this.toArray(result, 0);
  87. return result;
  88. };
  89. Color3.prototype.toLuminance = function () {
  90. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  91. };
  92. Color3.prototype.multiply = function (otherColor) {
  93. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  94. };
  95. Color3.prototype.multiplyToRef = function (otherColor, result) {
  96. result.r = this.r * otherColor.r;
  97. result.g = this.g * otherColor.g;
  98. result.b = this.b * otherColor.b;
  99. return this;
  100. };
  101. Color3.prototype.equals = function (otherColor) {
  102. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  103. };
  104. Color3.prototype.equalsFloats = function (r, g, b) {
  105. return this.r === r && this.g === g && this.b === b;
  106. };
  107. Color3.prototype.scale = function (scale) {
  108. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  109. };
  110. Color3.prototype.scaleToRef = function (scale, result) {
  111. result.r = this.r * scale;
  112. result.g = this.g * scale;
  113. result.b = this.b * scale;
  114. return this;
  115. };
  116. Color3.prototype.add = function (otherColor) {
  117. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  118. };
  119. Color3.prototype.addToRef = function (otherColor, result) {
  120. result.r = this.r + otherColor.r;
  121. result.g = this.g + otherColor.g;
  122. result.b = this.b + otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.subtract = function (otherColor) {
  126. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  127. };
  128. Color3.prototype.subtractToRef = function (otherColor, result) {
  129. result.r = this.r - otherColor.r;
  130. result.g = this.g - otherColor.g;
  131. result.b = this.b - otherColor.b;
  132. return this;
  133. };
  134. Color3.prototype.clone = function () {
  135. return new Color3(this.r, this.g, this.b);
  136. };
  137. Color3.prototype.copyFrom = function (source) {
  138. this.r = source.r;
  139. this.g = source.g;
  140. this.b = source.b;
  141. return this;
  142. };
  143. Color3.prototype.copyFromFloats = function (r, g, b) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. return this;
  148. };
  149. Color3.prototype.toHexString = function () {
  150. var intR = (this.r * 255) | 0;
  151. var intG = (this.g * 255) | 0;
  152. var intB = (this.b * 255) | 0;
  153. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  154. };
  155. Color3.prototype.toLinearSpace = function () {
  156. var convertedColor = new Color3();
  157. this.toLinearSpaceToRef(convertedColor);
  158. return convertedColor;
  159. };
  160. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  161. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  162. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  163. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  164. return this;
  165. };
  166. Color3.prototype.toGammaSpace = function () {
  167. var convertedColor = new Color3();
  168. this.toGammaSpaceToRef(convertedColor);
  169. return convertedColor;
  170. };
  171. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  172. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  173. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  174. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  175. return this;
  176. };
  177. // Statics
  178. Color3.FromHexString = function (hex) {
  179. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  180. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  181. return new Color3(0, 0, 0);
  182. }
  183. var r = parseInt(hex.substring(1, 3), 16);
  184. var g = parseInt(hex.substring(3, 5), 16);
  185. var b = parseInt(hex.substring(5, 7), 16);
  186. return Color3.FromInts(r, g, b);
  187. };
  188. Color3.FromArray = function (array, offset) {
  189. if (offset === void 0) { offset = 0; }
  190. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  191. };
  192. Color3.FromInts = function (r, g, b) {
  193. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  194. };
  195. Color3.Lerp = function (start, end, amount) {
  196. var r = start.r + ((end.r - start.r) * amount);
  197. var g = start.g + ((end.g - start.g) * amount);
  198. var b = start.b + ((end.b - start.b) * amount);
  199. return new Color3(r, g, b);
  200. };
  201. Color3.Red = function () { return new Color3(1, 0, 0); };
  202. Color3.Green = function () { return new Color3(0, 1, 0); };
  203. Color3.Blue = function () { return new Color3(0, 0, 1); };
  204. Color3.Black = function () { return new Color3(0, 0, 0); };
  205. Color3.White = function () { return new Color3(1, 1, 1); };
  206. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  207. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  208. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  209. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  210. return Color3;
  211. })();
  212. BABYLON.Color3 = Color3;
  213. var Color4 = (function () {
  214. function Color4(r, g, b, a) {
  215. this.r = r;
  216. this.g = g;
  217. this.b = b;
  218. this.a = a;
  219. }
  220. // Operators
  221. Color4.prototype.addInPlace = function (right) {
  222. this.r += right.r;
  223. this.g += right.g;
  224. this.b += right.b;
  225. this.a += right.a;
  226. return this;
  227. };
  228. Color4.prototype.asArray = function () {
  229. var result = [];
  230. this.toArray(result, 0);
  231. return result;
  232. };
  233. Color4.prototype.toArray = function (array, index) {
  234. if (index === undefined) {
  235. index = 0;
  236. }
  237. array[index] = this.r;
  238. array[index + 1] = this.g;
  239. array[index + 2] = this.b;
  240. array[index + 3] = this.a;
  241. return this;
  242. };
  243. Color4.prototype.add = function (right) {
  244. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  245. };
  246. Color4.prototype.subtract = function (right) {
  247. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  248. };
  249. Color4.prototype.subtractToRef = function (right, result) {
  250. result.r = this.r - right.r;
  251. result.g = this.g - right.g;
  252. result.b = this.b - right.b;
  253. result.a = this.a - right.a;
  254. return this;
  255. };
  256. Color4.prototype.scale = function (scale) {
  257. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  258. };
  259. Color4.prototype.scaleToRef = function (scale, result) {
  260. result.r = this.r * scale;
  261. result.g = this.g * scale;
  262. result.b = this.b * scale;
  263. result.a = this.a * scale;
  264. return this;
  265. };
  266. /**
  267. * Multipy an RGBA Color4 value by another and return a new Color4 object
  268. * @param color The Color4 (RGBA) value to multiply by
  269. * @returns A new Color4.
  270. */
  271. Color4.prototype.multiply = function (color) {
  272. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  273. };
  274. /**
  275. * Multipy an RGBA Color4 value by another and push the result in a reference value
  276. * @param color The Color4 (RGBA) value to multiply by
  277. * @param result The Color4 (RGBA) to fill the result in
  278. * @returns the result Color4.
  279. */
  280. Color4.prototype.multiplyToRef = function (color, result) {
  281. result.r = this.r * color.r;
  282. result.g = this.g * color.g;
  283. result.b = this.b * color.b;
  284. result.a = this.a * color.a;
  285. return result;
  286. };
  287. Color4.prototype.toString = function () {
  288. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  289. };
  290. Color4.prototype.getClassName = function () {
  291. return "Color4";
  292. };
  293. Color4.prototype.getHashCode = function () {
  294. var hash = this.r || 0;
  295. hash = (hash * 397) ^ (this.g || 0);
  296. hash = (hash * 397) ^ (this.b || 0);
  297. hash = (hash * 397) ^ (this.a || 0);
  298. return hash;
  299. };
  300. Color4.prototype.clone = function () {
  301. return new Color4(this.r, this.g, this.b, this.a);
  302. };
  303. Color4.prototype.copyFrom = function (source) {
  304. this.r = source.r;
  305. this.g = source.g;
  306. this.b = source.b;
  307. this.a = source.a;
  308. return this;
  309. };
  310. Color4.prototype.toHexString = function () {
  311. var intR = (this.r * 255) | 0;
  312. var intG = (this.g * 255) | 0;
  313. var intB = (this.b * 255) | 0;
  314. var intA = (this.a * 255) | 0;
  315. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  316. };
  317. // Statics
  318. Color4.FromHexString = function (hex) {
  319. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  320. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  321. return new Color4(0, 0, 0, 0);
  322. }
  323. var r = parseInt(hex.substring(1, 3), 16);
  324. var g = parseInt(hex.substring(3, 5), 16);
  325. var b = parseInt(hex.substring(5, 7), 16);
  326. var a = parseInt(hex.substring(7, 9), 16);
  327. return Color4.FromInts(r, g, b, a);
  328. };
  329. Color4.Lerp = function (left, right, amount) {
  330. var result = new Color4(0, 0, 0, 0);
  331. Color4.LerpToRef(left, right, amount, result);
  332. return result;
  333. };
  334. Color4.LerpToRef = function (left, right, amount, result) {
  335. result.r = left.r + (right.r - left.r) * amount;
  336. result.g = left.g + (right.g - left.g) * amount;
  337. result.b = left.b + (right.b - left.b) * amount;
  338. result.a = left.a + (right.a - left.a) * amount;
  339. };
  340. Color4.FromArray = function (array, offset) {
  341. if (offset === void 0) { offset = 0; }
  342. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  343. };
  344. Color4.FromInts = function (r, g, b, a) {
  345. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  346. };
  347. Color4.CheckColors4 = function (colors, count) {
  348. // Check if color3 was used
  349. if (colors.length === count * 3) {
  350. var colors4 = [];
  351. for (var index = 0; index < colors.length; index += 3) {
  352. var newIndex = (index / 3) * 4;
  353. colors4[newIndex] = colors[index];
  354. colors4[newIndex + 1] = colors[index + 1];
  355. colors4[newIndex + 2] = colors[index + 2];
  356. colors4[newIndex + 3] = 1.0;
  357. }
  358. return colors4;
  359. }
  360. return colors;
  361. };
  362. return Color4;
  363. })();
  364. BABYLON.Color4 = Color4;
  365. var Vector2 = (function () {
  366. function Vector2(x, y) {
  367. this.x = x;
  368. this.y = y;
  369. }
  370. Vector2.prototype.toString = function () {
  371. return "{X: " + this.x + " Y:" + this.y + "}";
  372. };
  373. Vector2.prototype.getClassName = function () {
  374. return "Vector2";
  375. };
  376. Vector2.prototype.getHashCode = function () {
  377. var hash = this.x || 0;
  378. hash = (hash * 397) ^ (this.y || 0);
  379. return hash;
  380. };
  381. // Operators
  382. Vector2.prototype.toArray = function (array, index) {
  383. if (index === void 0) { index = 0; }
  384. array[index] = this.x;
  385. array[index + 1] = this.y;
  386. return this;
  387. };
  388. Vector2.prototype.asArray = function () {
  389. var result = [];
  390. this.toArray(result, 0);
  391. return result;
  392. };
  393. Vector2.prototype.copyFrom = function (source) {
  394. this.x = source.x;
  395. this.y = source.y;
  396. return this;
  397. };
  398. Vector2.prototype.copyFromFloats = function (x, y) {
  399. this.x = x;
  400. this.y = y;
  401. return this;
  402. };
  403. Vector2.prototype.add = function (otherVector) {
  404. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  405. };
  406. Vector2.prototype.addToRef = function (otherVector, result) {
  407. result.x = this.x + otherVector.x;
  408. result.y = this.y + otherVector.y;
  409. return this;
  410. };
  411. Vector2.prototype.addInPlace = function (otherVector) {
  412. this.x += otherVector.x;
  413. this.y += otherVector.y;
  414. return this;
  415. };
  416. Vector2.prototype.addVector3 = function (otherVector) {
  417. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  418. };
  419. Vector2.prototype.subtract = function (otherVector) {
  420. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  421. };
  422. Vector2.prototype.subtractToRef = function (otherVector, result) {
  423. result.x = this.x - otherVector.x;
  424. result.y = this.y - otherVector.y;
  425. return this;
  426. };
  427. Vector2.prototype.subtractInPlace = function (otherVector) {
  428. this.x -= otherVector.x;
  429. this.y -= otherVector.y;
  430. return this;
  431. };
  432. Vector2.prototype.multiplyInPlace = function (otherVector) {
  433. this.x *= otherVector.x;
  434. this.y *= otherVector.y;
  435. return this;
  436. };
  437. Vector2.prototype.multiply = function (otherVector) {
  438. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  439. };
  440. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  441. result.x = this.x * otherVector.x;
  442. result.y = this.y * otherVector.y;
  443. return this;
  444. };
  445. Vector2.prototype.multiplyByFloats = function (x, y) {
  446. return new Vector2(this.x * x, this.y * y);
  447. };
  448. Vector2.prototype.divide = function (otherVector) {
  449. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  450. };
  451. Vector2.prototype.divideToRef = function (otherVector, result) {
  452. result.x = this.x / otherVector.x;
  453. result.y = this.y / otherVector.y;
  454. return this;
  455. };
  456. Vector2.prototype.negate = function () {
  457. return new Vector2(-this.x, -this.y);
  458. };
  459. Vector2.prototype.scaleInPlace = function (scale) {
  460. this.x *= scale;
  461. this.y *= scale;
  462. return this;
  463. };
  464. Vector2.prototype.scale = function (scale) {
  465. return new Vector2(this.x * scale, this.y * scale);
  466. };
  467. Vector2.prototype.equals = function (otherVector) {
  468. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  469. };
  470. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  471. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  472. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  473. };
  474. // Properties
  475. Vector2.prototype.length = function () {
  476. return Math.sqrt(this.x * this.x + this.y * this.y);
  477. };
  478. Vector2.prototype.lengthSquared = function () {
  479. return (this.x * this.x + this.y * this.y);
  480. };
  481. // Methods
  482. Vector2.prototype.normalize = function () {
  483. var len = this.length();
  484. if (len === 0)
  485. return this;
  486. var num = 1.0 / len;
  487. this.x *= num;
  488. this.y *= num;
  489. return this;
  490. };
  491. Vector2.prototype.clone = function () {
  492. return new Vector2(this.x, this.y);
  493. };
  494. // Statics
  495. Vector2.Zero = function () {
  496. return new Vector2(0, 0);
  497. };
  498. Vector2.FromArray = function (array, offset) {
  499. if (offset === void 0) { offset = 0; }
  500. return new Vector2(array[offset], array[offset + 1]);
  501. };
  502. Vector2.FromArrayToRef = function (array, offset, result) {
  503. result.x = array[offset];
  504. result.y = array[offset + 1];
  505. };
  506. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  507. var squared = amount * amount;
  508. var cubed = amount * squared;
  509. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  510. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  511. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  512. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  513. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  514. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  515. return new Vector2(x, y);
  516. };
  517. Vector2.Clamp = function (value, min, max) {
  518. var x = value.x;
  519. x = (x > max.x) ? max.x : x;
  520. x = (x < min.x) ? min.x : x;
  521. var y = value.y;
  522. y = (y > max.y) ? max.y : y;
  523. y = (y < min.y) ? min.y : y;
  524. return new Vector2(x, y);
  525. };
  526. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  527. var squared = amount * amount;
  528. var cubed = amount * squared;
  529. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  530. var part2 = (-2.0 * cubed) + (3.0 * squared);
  531. var part3 = (cubed - (2.0 * squared)) + amount;
  532. var part4 = cubed - squared;
  533. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  534. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  535. return new Vector2(x, y);
  536. };
  537. Vector2.Lerp = function (start, end, amount) {
  538. var x = start.x + ((end.x - start.x) * amount);
  539. var y = start.y + ((end.y - start.y) * amount);
  540. return new Vector2(x, y);
  541. };
  542. Vector2.Dot = function (left, right) {
  543. return left.x * right.x + left.y * right.y;
  544. };
  545. Vector2.Normalize = function (vector) {
  546. var newVector = vector.clone();
  547. newVector.normalize();
  548. return newVector;
  549. };
  550. Vector2.Minimize = function (left, right) {
  551. var x = (left.x < right.x) ? left.x : right.x;
  552. var y = (left.y < right.y) ? left.y : right.y;
  553. return new Vector2(x, y);
  554. };
  555. Vector2.Maximize = function (left, right) {
  556. var x = (left.x > right.x) ? left.x : right.x;
  557. var y = (left.y > right.y) ? left.y : right.y;
  558. return new Vector2(x, y);
  559. };
  560. Vector2.Transform = function (vector, transformation) {
  561. var r = Vector2.Zero();
  562. Vector2.TransformToRef(vector, transformation, r);
  563. return r;
  564. };
  565. Vector2.TransformToRef = function (vector, transformation, result) {
  566. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  567. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  568. result.x = x;
  569. result.y = y;
  570. };
  571. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  572. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  573. var sign = a < 0 ? -1 : 1;
  574. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  575. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  576. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  577. };
  578. Vector2.Distance = function (value1, value2) {
  579. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  580. };
  581. Vector2.DistanceSquared = function (value1, value2) {
  582. var x = value1.x - value2.x;
  583. var y = value1.y - value2.y;
  584. return (x * x) + (y * y);
  585. };
  586. Vector2.Center = function (value1, value2) {
  587. var center = value1.add(value2);
  588. center.scaleInPlace(0.5);
  589. return center;
  590. };
  591. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  592. var l2 = Vector2.DistanceSquared(segA, segB);
  593. if (l2 === 0.0) {
  594. return Vector2.Distance(p, segA);
  595. }
  596. var v = segB.subtract(segA);
  597. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  598. var proj = segA.add(v.multiplyByFloats(t, t));
  599. return Vector2.Distance(p, proj);
  600. };
  601. return Vector2;
  602. })();
  603. BABYLON.Vector2 = Vector2;
  604. var Vector3 = (function () {
  605. function Vector3(x, y, z) {
  606. this.x = x;
  607. this.y = y;
  608. this.z = z;
  609. }
  610. Vector3.prototype.toString = function () {
  611. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  612. };
  613. Vector3.prototype.getClassName = function () {
  614. return "Vector3";
  615. };
  616. Vector3.prototype.getHashCode = function () {
  617. var hash = this.x || 0;
  618. hash = (hash * 397) ^ (this.y || 0);
  619. hash = (hash * 397) ^ (this.z || 0);
  620. return hash;
  621. };
  622. // Operators
  623. Vector3.prototype.asArray = function () {
  624. var result = [];
  625. this.toArray(result, 0);
  626. return result;
  627. };
  628. Vector3.prototype.toArray = function (array, index) {
  629. if (index === void 0) { index = 0; }
  630. array[index] = this.x;
  631. array[index + 1] = this.y;
  632. array[index + 2] = this.z;
  633. return this;
  634. };
  635. Vector3.prototype.toQuaternion = function () {
  636. var result = new Quaternion(0, 0, 0, 1);
  637. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  638. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  639. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  640. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  641. var cosy = Math.cos(this.y * 0.5);
  642. var siny = Math.sin(this.y * 0.5);
  643. result.x = coszMinusx * siny;
  644. result.y = -sinzMinusx * siny;
  645. result.z = sinxPlusz * cosy;
  646. result.w = cosxPlusz * cosy;
  647. return result;
  648. };
  649. Vector3.prototype.addInPlace = function (otherVector) {
  650. this.x += otherVector.x;
  651. this.y += otherVector.y;
  652. this.z += otherVector.z;
  653. return this;
  654. };
  655. Vector3.prototype.add = function (otherVector) {
  656. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  657. };
  658. Vector3.prototype.addToRef = function (otherVector, result) {
  659. result.x = this.x + otherVector.x;
  660. result.y = this.y + otherVector.y;
  661. result.z = this.z + otherVector.z;
  662. return this;
  663. };
  664. Vector3.prototype.subtractInPlace = function (otherVector) {
  665. this.x -= otherVector.x;
  666. this.y -= otherVector.y;
  667. this.z -= otherVector.z;
  668. return this;
  669. };
  670. Vector3.prototype.subtract = function (otherVector) {
  671. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  672. };
  673. Vector3.prototype.subtractToRef = function (otherVector, result) {
  674. result.x = this.x - otherVector.x;
  675. result.y = this.y - otherVector.y;
  676. result.z = this.z - otherVector.z;
  677. return this;
  678. };
  679. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  680. return new Vector3(this.x - x, this.y - y, this.z - z);
  681. };
  682. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  683. result.x = this.x - x;
  684. result.y = this.y - y;
  685. result.z = this.z - z;
  686. return this;
  687. };
  688. Vector3.prototype.negate = function () {
  689. return new Vector3(-this.x, -this.y, -this.z);
  690. };
  691. Vector3.prototype.scaleInPlace = function (scale) {
  692. this.x *= scale;
  693. this.y *= scale;
  694. this.z *= scale;
  695. return this;
  696. };
  697. Vector3.prototype.scale = function (scale) {
  698. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  699. };
  700. Vector3.prototype.scaleToRef = function (scale, result) {
  701. result.x = this.x * scale;
  702. result.y = this.y * scale;
  703. result.z = this.z * scale;
  704. };
  705. Vector3.prototype.equals = function (otherVector) {
  706. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  707. };
  708. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  709. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  710. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  711. };
  712. Vector3.prototype.equalsToFloats = function (x, y, z) {
  713. return this.x === x && this.y === y && this.z === z;
  714. };
  715. Vector3.prototype.multiplyInPlace = function (otherVector) {
  716. this.x *= otherVector.x;
  717. this.y *= otherVector.y;
  718. this.z *= otherVector.z;
  719. return this;
  720. };
  721. Vector3.prototype.multiply = function (otherVector) {
  722. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  723. };
  724. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  725. result.x = this.x * otherVector.x;
  726. result.y = this.y * otherVector.y;
  727. result.z = this.z * otherVector.z;
  728. return this;
  729. };
  730. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  731. return new Vector3(this.x * x, this.y * y, this.z * z);
  732. };
  733. Vector3.prototype.divide = function (otherVector) {
  734. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  735. };
  736. Vector3.prototype.divideToRef = function (otherVector, result) {
  737. result.x = this.x / otherVector.x;
  738. result.y = this.y / otherVector.y;
  739. result.z = this.z / otherVector.z;
  740. return this;
  741. };
  742. Vector3.prototype.MinimizeInPlace = function (other) {
  743. if (other.x < this.x)
  744. this.x = other.x;
  745. if (other.y < this.y)
  746. this.y = other.y;
  747. if (other.z < this.z)
  748. this.z = other.z;
  749. return this;
  750. };
  751. Vector3.prototype.MaximizeInPlace = function (other) {
  752. if (other.x > this.x)
  753. this.x = other.x;
  754. if (other.y > this.y)
  755. this.y = other.y;
  756. if (other.z > this.z)
  757. this.z = other.z;
  758. return this;
  759. };
  760. // Properties
  761. Vector3.prototype.length = function () {
  762. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  763. };
  764. Vector3.prototype.lengthSquared = function () {
  765. return (this.x * this.x + this.y * this.y + this.z * this.z);
  766. };
  767. // Methods
  768. Vector3.prototype.normalize = function () {
  769. var len = this.length();
  770. if (len === 0 || len === 1.0)
  771. return this;
  772. var num = 1.0 / len;
  773. this.x *= num;
  774. this.y *= num;
  775. this.z *= num;
  776. return this;
  777. };
  778. Vector3.prototype.clone = function () {
  779. return new Vector3(this.x, this.y, this.z);
  780. };
  781. Vector3.prototype.copyFrom = function (source) {
  782. this.x = source.x;
  783. this.y = source.y;
  784. this.z = source.z;
  785. return this;
  786. };
  787. Vector3.prototype.copyFromFloats = function (x, y, z) {
  788. this.x = x;
  789. this.y = y;
  790. this.z = z;
  791. return this;
  792. };
  793. // Statics
  794. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  795. var d0 = Vector3.Dot(vector0, axis) - size;
  796. var d1 = Vector3.Dot(vector1, axis) - size;
  797. var s = d0 / (d0 - d1);
  798. return s;
  799. };
  800. Vector3.FromArray = function (array, offset) {
  801. if (!offset) {
  802. offset = 0;
  803. }
  804. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  805. };
  806. Vector3.FromFloatArray = function (array, offset) {
  807. if (!offset) {
  808. offset = 0;
  809. }
  810. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  811. };
  812. Vector3.FromArrayToRef = function (array, offset, result) {
  813. result.x = array[offset];
  814. result.y = array[offset + 1];
  815. result.z = array[offset + 2];
  816. };
  817. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  818. result.x = array[offset];
  819. result.y = array[offset + 1];
  820. result.z = array[offset + 2];
  821. };
  822. Vector3.FromFloatsToRef = function (x, y, z, result) {
  823. result.x = x;
  824. result.y = y;
  825. result.z = z;
  826. };
  827. Vector3.Zero = function () {
  828. return new Vector3(0, 0, 0);
  829. };
  830. Vector3.Up = function () {
  831. return new Vector3(0, 1.0, 0);
  832. };
  833. Vector3.TransformCoordinates = function (vector, transformation) {
  834. var result = Vector3.Zero();
  835. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  836. return result;
  837. };
  838. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  839. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  840. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  841. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  842. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  843. result.x = x / w;
  844. result.y = y / w;
  845. result.z = z / w;
  846. };
  847. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  848. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  849. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  850. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  851. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  852. result.x = rx / rw;
  853. result.y = ry / rw;
  854. result.z = rz / rw;
  855. };
  856. Vector3.TransformNormal = function (vector, transformation) {
  857. var result = Vector3.Zero();
  858. Vector3.TransformNormalToRef(vector, transformation, result);
  859. return result;
  860. };
  861. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  862. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  863. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  864. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  865. };
  866. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  867. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  868. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  869. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  870. };
  871. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  872. var squared = amount * amount;
  873. var cubed = amount * squared;
  874. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  875. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  876. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  877. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  878. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  879. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  880. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  881. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  882. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  883. return new Vector3(x, y, z);
  884. };
  885. Vector3.Clamp = function (value, min, max) {
  886. var x = value.x;
  887. x = (x > max.x) ? max.x : x;
  888. x = (x < min.x) ? min.x : x;
  889. var y = value.y;
  890. y = (y > max.y) ? max.y : y;
  891. y = (y < min.y) ? min.y : y;
  892. var z = value.z;
  893. z = (z > max.z) ? max.z : z;
  894. z = (z < min.z) ? min.z : z;
  895. return new Vector3(x, y, z);
  896. };
  897. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  898. var squared = amount * amount;
  899. var cubed = amount * squared;
  900. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  901. var part2 = (-2.0 * cubed) + (3.0 * squared);
  902. var part3 = (cubed - (2.0 * squared)) + amount;
  903. var part4 = cubed - squared;
  904. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  905. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  906. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  907. return new Vector3(x, y, z);
  908. };
  909. Vector3.Lerp = function (start, end, amount) {
  910. var x = start.x + ((end.x - start.x) * amount);
  911. var y = start.y + ((end.y - start.y) * amount);
  912. var z = start.z + ((end.z - start.z) * amount);
  913. return new Vector3(x, y, z);
  914. };
  915. Vector3.Dot = function (left, right) {
  916. return (left.x * right.x + left.y * right.y + left.z * right.z);
  917. };
  918. Vector3.Cross = function (left, right) {
  919. var result = Vector3.Zero();
  920. Vector3.CrossToRef(left, right, result);
  921. return result;
  922. };
  923. Vector3.CrossToRef = function (left, right, result) {
  924. Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  925. Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  926. Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  927. result.copyFrom(Tmp.Vector3[0]);
  928. };
  929. Vector3.Normalize = function (vector) {
  930. var result = Vector3.Zero();
  931. Vector3.NormalizeToRef(vector, result);
  932. return result;
  933. };
  934. Vector3.NormalizeToRef = function (vector, result) {
  935. result.copyFrom(vector);
  936. result.normalize();
  937. };
  938. Vector3.Project = function (vector, world, transform, viewport) {
  939. var cw = viewport.width;
  940. var ch = viewport.height;
  941. var cx = viewport.x;
  942. var cy = viewport.y;
  943. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  944. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1, viewportMatrix);
  945. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  946. world.multiplyToRef(transform, matrix);
  947. matrix.multiplyToRef(viewportMatrix, matrix);
  948. return Vector3.TransformCoordinates(vector, matrix);
  949. };
  950. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  951. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  952. world.multiplyToRef(transform, matrix);
  953. matrix.invert();
  954. source.x = source.x / viewportWidth * 2 - 1;
  955. source.y = -(source.y / viewportHeight * 2 - 1);
  956. var vector = Vector3.TransformCoordinates(source, matrix);
  957. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  958. if (MathTools.WithinEpsilon(num, 1.0)) {
  959. vector = vector.scale(1.0 / num);
  960. }
  961. return vector;
  962. };
  963. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  964. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  965. world.multiplyToRef(view, matrix);
  966. matrix.multiplyToRef(projection, matrix);
  967. matrix.invert();
  968. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  969. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  970. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  971. if (MathTools.WithinEpsilon(num, 1.0)) {
  972. vector = vector.scale(1.0 / num);
  973. }
  974. return vector;
  975. };
  976. Vector3.Minimize = function (left, right) {
  977. var min = left.clone();
  978. min.MinimizeInPlace(right);
  979. return min;
  980. };
  981. Vector3.Maximize = function (left, right) {
  982. var max = left.clone();
  983. max.MaximizeInPlace(right);
  984. return max;
  985. };
  986. Vector3.Distance = function (value1, value2) {
  987. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  988. };
  989. Vector3.DistanceSquared = function (value1, value2) {
  990. var x = value1.x - value2.x;
  991. var y = value1.y - value2.y;
  992. var z = value1.z - value2.z;
  993. return (x * x) + (y * y) + (z * z);
  994. };
  995. Vector3.Center = function (value1, value2) {
  996. var center = value1.add(value2);
  997. center.scaleInPlace(0.5);
  998. return center;
  999. };
  1000. /**
  1001. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1002. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1003. * to something in order to rotate it from its local system to the given target system.
  1004. */
  1005. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1006. var rotation = Vector3.Zero();
  1007. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1008. return rotation;
  1009. };
  1010. /**
  1011. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  1012. */
  1013. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1014. var u = axis1.normalize();
  1015. var w = axis3.normalize();
  1016. // world axis
  1017. var X = Axis.X;
  1018. var Y = Axis.Y;
  1019. // equation unknowns and vars
  1020. var yaw = 0.0;
  1021. var pitch = 0.0;
  1022. var roll = 0.0;
  1023. var x = 0.0;
  1024. var y = 0.0;
  1025. var z = 0.0;
  1026. var t = 0.0;
  1027. var sign = -1.0;
  1028. var nbRevert = 0;
  1029. var cross = Tmp.Vector3[0];
  1030. var dot = 0.0;
  1031. // step 1 : rotation around w
  1032. // Rv3(u) = u1, and u1 belongs to plane xOz
  1033. // Rv3(w) = w1 = w invariant
  1034. var u1 = Tmp.Vector3[1];
  1035. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1036. z = 1.0;
  1037. }
  1038. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  1039. x = 1.0;
  1040. }
  1041. else {
  1042. t = w.z / w.x;
  1043. x = -t * Math.sqrt(1 / (1 + t * t));
  1044. z = Math.sqrt(1 / (1 + t * t));
  1045. }
  1046. u1.x = x;
  1047. u1.y = y;
  1048. u1.z = z;
  1049. u1.normalize();
  1050. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  1051. cross.normalize();
  1052. if (Vector3.Dot(w, cross) < 0) {
  1053. sign = 1.0;
  1054. }
  1055. dot = Vector3.Dot(u, u1);
  1056. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1057. roll = Math.acos(dot) * sign;
  1058. if (Vector3.Dot(u1, X) < 0) {
  1059. roll = Math.PI + roll;
  1060. u1 = u1.scaleInPlace(-1);
  1061. nbRevert++;
  1062. }
  1063. // step 2 : rotate around u1
  1064. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1065. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1066. var w2 = Tmp.Vector3[2];
  1067. var v2 = Tmp.Vector3[3];
  1068. x = 0.0;
  1069. y = 0.0;
  1070. z = 0.0;
  1071. sign = -1.0;
  1072. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1073. x = 1.0;
  1074. }
  1075. else {
  1076. t = u1.z / u1.x;
  1077. x = -t * Math.sqrt(1 / (1 + t * t));
  1078. z = Math.sqrt(1 / (1 + t * t));
  1079. }
  1080. w2.x = x;
  1081. w2.y = y;
  1082. w2.z = z;
  1083. w2.normalize();
  1084. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1085. v2.normalize();
  1086. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1087. cross.normalize();
  1088. if (Vector3.Dot(u1, cross) < 0) {
  1089. sign = 1.0;
  1090. }
  1091. dot = Vector3.Dot(w, w2);
  1092. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1093. pitch = Math.acos(dot) * sign;
  1094. if (Vector3.Dot(v2, Y) < 0) {
  1095. pitch = Math.PI + pitch;
  1096. nbRevert++;
  1097. }
  1098. // step 3 : rotate around v2
  1099. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1100. sign = -1.0;
  1101. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1102. cross.normalize();
  1103. if (Vector3.Dot(cross, Y) < 0) {
  1104. sign = 1.0;
  1105. }
  1106. dot = Vector3.Dot(u1, X);
  1107. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1108. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1109. if (dot < 0 && nbRevert < 2) {
  1110. yaw = Math.PI + yaw;
  1111. }
  1112. ref.x = pitch;
  1113. ref.y = yaw;
  1114. ref.z = roll;
  1115. };
  1116. return Vector3;
  1117. })();
  1118. BABYLON.Vector3 = Vector3;
  1119. //Vector4 class created for EulerAngle class conversion to Quaternion
  1120. var Vector4 = (function () {
  1121. function Vector4(x, y, z, w) {
  1122. this.x = x;
  1123. this.y = y;
  1124. this.z = z;
  1125. this.w = w;
  1126. }
  1127. Vector4.prototype.toString = function () {
  1128. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1129. };
  1130. Vector4.prototype.getClassName = function () {
  1131. return "Vector4";
  1132. };
  1133. Vector4.prototype.getHashCode = function () {
  1134. var hash = this.x || 0;
  1135. hash = (hash * 397) ^ (this.y || 0);
  1136. hash = (hash * 397) ^ (this.z || 0);
  1137. hash = (hash * 397) ^ (this.w || 0);
  1138. return hash;
  1139. };
  1140. // Operators
  1141. Vector4.prototype.asArray = function () {
  1142. var result = [];
  1143. this.toArray(result, 0);
  1144. return result;
  1145. };
  1146. Vector4.prototype.toArray = function (array, index) {
  1147. if (index === undefined) {
  1148. index = 0;
  1149. }
  1150. array[index] = this.x;
  1151. array[index + 1] = this.y;
  1152. array[index + 2] = this.z;
  1153. array[index + 3] = this.w;
  1154. return this;
  1155. };
  1156. Vector4.prototype.addInPlace = function (otherVector) {
  1157. this.x += otherVector.x;
  1158. this.y += otherVector.y;
  1159. this.z += otherVector.z;
  1160. this.w += otherVector.w;
  1161. return this;
  1162. };
  1163. Vector4.prototype.add = function (otherVector) {
  1164. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1165. };
  1166. Vector4.prototype.addToRef = function (otherVector, result) {
  1167. result.x = this.x + otherVector.x;
  1168. result.y = this.y + otherVector.y;
  1169. result.z = this.z + otherVector.z;
  1170. result.w = this.w + otherVector.w;
  1171. return this;
  1172. };
  1173. Vector4.prototype.subtractInPlace = function (otherVector) {
  1174. this.x -= otherVector.x;
  1175. this.y -= otherVector.y;
  1176. this.z -= otherVector.z;
  1177. this.w -= otherVector.w;
  1178. return this;
  1179. };
  1180. Vector4.prototype.subtract = function (otherVector) {
  1181. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1182. };
  1183. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1184. result.x = this.x - otherVector.x;
  1185. result.y = this.y - otherVector.y;
  1186. result.z = this.z - otherVector.z;
  1187. result.w = this.w - otherVector.w;
  1188. return this;
  1189. };
  1190. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1191. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1192. };
  1193. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1194. result.x = this.x - x;
  1195. result.y = this.y - y;
  1196. result.z = this.z - z;
  1197. result.w = this.w - w;
  1198. return this;
  1199. };
  1200. Vector4.prototype.negate = function () {
  1201. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1202. };
  1203. Vector4.prototype.scaleInPlace = function (scale) {
  1204. this.x *= scale;
  1205. this.y *= scale;
  1206. this.z *= scale;
  1207. this.w *= scale;
  1208. return this;
  1209. };
  1210. Vector4.prototype.scale = function (scale) {
  1211. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1212. };
  1213. Vector4.prototype.scaleToRef = function (scale, result) {
  1214. result.x = this.x * scale;
  1215. result.y = this.y * scale;
  1216. result.z = this.z * scale;
  1217. result.w = this.w * scale;
  1218. };
  1219. Vector4.prototype.equals = function (otherVector) {
  1220. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1221. };
  1222. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1223. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1224. return otherVector
  1225. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1226. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1227. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1228. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1229. };
  1230. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1231. return this.x === x && this.y === y && this.z === z && this.w === w;
  1232. };
  1233. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1234. this.x *= otherVector.x;
  1235. this.y *= otherVector.y;
  1236. this.z *= otherVector.z;
  1237. this.w *= otherVector.w;
  1238. return this;
  1239. };
  1240. Vector4.prototype.multiply = function (otherVector) {
  1241. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1242. };
  1243. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1244. result.x = this.x * otherVector.x;
  1245. result.y = this.y * otherVector.y;
  1246. result.z = this.z * otherVector.z;
  1247. result.w = this.w * otherVector.w;
  1248. return this;
  1249. };
  1250. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1251. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1252. };
  1253. Vector4.prototype.divide = function (otherVector) {
  1254. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1255. };
  1256. Vector4.prototype.divideToRef = function (otherVector, result) {
  1257. result.x = this.x / otherVector.x;
  1258. result.y = this.y / otherVector.y;
  1259. result.z = this.z / otherVector.z;
  1260. result.w = this.w / otherVector.w;
  1261. return this;
  1262. };
  1263. Vector4.prototype.MinimizeInPlace = function (other) {
  1264. if (other.x < this.x)
  1265. this.x = other.x;
  1266. if (other.y < this.y)
  1267. this.y = other.y;
  1268. if (other.z < this.z)
  1269. this.z = other.z;
  1270. if (other.w < this.w)
  1271. this.w = other.w;
  1272. return this;
  1273. };
  1274. Vector4.prototype.MaximizeInPlace = function (other) {
  1275. if (other.x > this.x)
  1276. this.x = other.x;
  1277. if (other.y > this.y)
  1278. this.y = other.y;
  1279. if (other.z > this.z)
  1280. this.z = other.z;
  1281. if (other.w > this.w)
  1282. this.w = other.w;
  1283. return this;
  1284. };
  1285. // Properties
  1286. Vector4.prototype.length = function () {
  1287. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1288. };
  1289. Vector4.prototype.lengthSquared = function () {
  1290. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1291. };
  1292. // Methods
  1293. Vector4.prototype.normalize = function () {
  1294. var len = this.length();
  1295. if (len === 0)
  1296. return this;
  1297. var num = 1.0 / len;
  1298. this.x *= num;
  1299. this.y *= num;
  1300. this.z *= num;
  1301. this.w *= num;
  1302. return this;
  1303. };
  1304. Vector4.prototype.toVector3 = function () {
  1305. return new Vector3(this.x, this.y, this.z);
  1306. };
  1307. Vector4.prototype.clone = function () {
  1308. return new Vector4(this.x, this.y, this.z, this.w);
  1309. };
  1310. Vector4.prototype.copyFrom = function (source) {
  1311. this.x = source.x;
  1312. this.y = source.y;
  1313. this.z = source.z;
  1314. this.w = source.w;
  1315. return this;
  1316. };
  1317. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1318. this.x = x;
  1319. this.y = y;
  1320. this.z = z;
  1321. this.w = w;
  1322. return this;
  1323. };
  1324. // Statics
  1325. Vector4.FromArray = function (array, offset) {
  1326. if (!offset) {
  1327. offset = 0;
  1328. }
  1329. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1330. };
  1331. Vector4.FromArrayToRef = function (array, offset, result) {
  1332. result.x = array[offset];
  1333. result.y = array[offset + 1];
  1334. result.z = array[offset + 2];
  1335. result.w = array[offset + 3];
  1336. };
  1337. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1338. result.x = array[offset];
  1339. result.y = array[offset + 1];
  1340. result.z = array[offset + 2];
  1341. result.w = array[offset + 3];
  1342. };
  1343. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1344. result.x = x;
  1345. result.y = y;
  1346. result.z = z;
  1347. result.w = w;
  1348. };
  1349. Vector4.Zero = function () {
  1350. return new Vector4(0, 0, 0, 0);
  1351. };
  1352. Vector4.Normalize = function (vector) {
  1353. var result = Vector4.Zero();
  1354. Vector4.NormalizeToRef(vector, result);
  1355. return result;
  1356. };
  1357. Vector4.NormalizeToRef = function (vector, result) {
  1358. result.copyFrom(vector);
  1359. result.normalize();
  1360. };
  1361. Vector4.Minimize = function (left, right) {
  1362. var min = left.clone();
  1363. min.MinimizeInPlace(right);
  1364. return min;
  1365. };
  1366. Vector4.Maximize = function (left, right) {
  1367. var max = left.clone();
  1368. max.MaximizeInPlace(right);
  1369. return max;
  1370. };
  1371. Vector4.Distance = function (value1, value2) {
  1372. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1373. };
  1374. Vector4.DistanceSquared = function (value1, value2) {
  1375. var x = value1.x - value2.x;
  1376. var y = value1.y - value2.y;
  1377. var z = value1.z - value2.z;
  1378. var w = value1.w - value2.w;
  1379. return (x * x) + (y * y) + (z * z) + (w * w);
  1380. };
  1381. Vector4.Center = function (value1, value2) {
  1382. var center = value1.add(value2);
  1383. center.scaleInPlace(0.5);
  1384. return center;
  1385. };
  1386. return Vector4;
  1387. })();
  1388. BABYLON.Vector4 = Vector4;
  1389. var Size = (function () {
  1390. function Size(width, height) {
  1391. this.width = width;
  1392. this.height = height;
  1393. }
  1394. Size.prototype.toString = function () {
  1395. return "{W: " + this.width + ", H: " + this.height + "}";
  1396. };
  1397. Size.prototype.getClassName = function () {
  1398. return "Size";
  1399. };
  1400. Size.prototype.getHashCode = function () {
  1401. var hash = this.width || 0;
  1402. hash = (hash * 397) ^ (this.height || 0);
  1403. return hash;
  1404. };
  1405. Size.prototype.copyFrom = function (src) {
  1406. this.width = src.width;
  1407. this.height = src.height;
  1408. };
  1409. Size.prototype.copyFromFloats = function (width, height) {
  1410. this.width = width;
  1411. this.height = height;
  1412. };
  1413. Size.prototype.multiplyByFloats = function (w, h) {
  1414. return new Size(this.width * w, this.height * h);
  1415. };
  1416. Size.prototype.clone = function () {
  1417. return new Size(this.width, this.height);
  1418. };
  1419. Size.prototype.equals = function (other) {
  1420. if (!other) {
  1421. return false;
  1422. }
  1423. return (this.width === other.width) && (this.height === other.height);
  1424. };
  1425. Object.defineProperty(Size.prototype, "surface", {
  1426. get: function () {
  1427. return this.width * this.height;
  1428. },
  1429. enumerable: true,
  1430. configurable: true
  1431. });
  1432. Size.Zero = function () {
  1433. return new Size(0, 0);
  1434. };
  1435. Size.prototype.add = function (otherSize) {
  1436. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1437. return r;
  1438. };
  1439. Size.prototype.substract = function (otherSize) {
  1440. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1441. return r;
  1442. };
  1443. Size.Lerp = function (start, end, amount) {
  1444. var w = start.width + ((end.width - start.width) * amount);
  1445. var h = start.height + ((end.height - start.height) * amount);
  1446. return new Size(w, h);
  1447. };
  1448. return Size;
  1449. })();
  1450. BABYLON.Size = Size;
  1451. var Quaternion = (function () {
  1452. function Quaternion(x, y, z, w) {
  1453. if (x === void 0) { x = 0; }
  1454. if (y === void 0) { y = 0; }
  1455. if (z === void 0) { z = 0; }
  1456. if (w === void 0) { w = 1; }
  1457. this.x = x;
  1458. this.y = y;
  1459. this.z = z;
  1460. this.w = w;
  1461. }
  1462. Quaternion.prototype.toString = function () {
  1463. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1464. };
  1465. Quaternion.prototype.getClassName = function () {
  1466. return "Quaternion";
  1467. };
  1468. Quaternion.prototype.getHashCode = function () {
  1469. var hash = this.x || 0;
  1470. hash = (hash * 397) ^ (this.y || 0);
  1471. hash = (hash * 397) ^ (this.z || 0);
  1472. hash = (hash * 397) ^ (this.w || 0);
  1473. return hash;
  1474. };
  1475. Quaternion.prototype.asArray = function () {
  1476. return [this.x, this.y, this.z, this.w];
  1477. };
  1478. Quaternion.prototype.equals = function (otherQuaternion) {
  1479. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1480. };
  1481. Quaternion.prototype.clone = function () {
  1482. return new Quaternion(this.x, this.y, this.z, this.w);
  1483. };
  1484. Quaternion.prototype.copyFrom = function (other) {
  1485. this.x = other.x;
  1486. this.y = other.y;
  1487. this.z = other.z;
  1488. this.w = other.w;
  1489. return this;
  1490. };
  1491. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1492. this.x = x;
  1493. this.y = y;
  1494. this.z = z;
  1495. this.w = w;
  1496. return this;
  1497. };
  1498. Quaternion.prototype.add = function (other) {
  1499. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1500. };
  1501. Quaternion.prototype.subtract = function (other) {
  1502. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1503. };
  1504. Quaternion.prototype.scale = function (value) {
  1505. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1506. };
  1507. Quaternion.prototype.multiply = function (q1) {
  1508. var result = new Quaternion(0, 0, 0, 1.0);
  1509. this.multiplyToRef(q1, result);
  1510. return result;
  1511. };
  1512. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1513. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1514. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1515. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1516. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1517. result.copyFromFloats(x, y, z, w);
  1518. return this;
  1519. };
  1520. Quaternion.prototype.multiplyInPlace = function (q1) {
  1521. this.multiplyToRef(q1, this);
  1522. return this;
  1523. };
  1524. Quaternion.prototype.conjugateToRef = function (ref) {
  1525. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1526. return this;
  1527. };
  1528. Quaternion.prototype.conjugateInPlace = function () {
  1529. this.x *= -1;
  1530. this.y *= -1;
  1531. this.z *= -1;
  1532. return this;
  1533. };
  1534. Quaternion.prototype.conjugate = function () {
  1535. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1536. return result;
  1537. };
  1538. Quaternion.prototype.length = function () {
  1539. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1540. };
  1541. Quaternion.prototype.normalize = function () {
  1542. var length = 1.0 / this.length();
  1543. this.x *= length;
  1544. this.y *= length;
  1545. this.z *= length;
  1546. this.w *= length;
  1547. return this;
  1548. };
  1549. Quaternion.prototype.toEulerAngles = function (order) {
  1550. if (order === void 0) { order = "YZX"; }
  1551. var result = Vector3.Zero();
  1552. this.toEulerAnglesToRef(result, order);
  1553. return result;
  1554. };
  1555. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1556. if (order === void 0) { order = "YZX"; }
  1557. var heading, attitude, bank;
  1558. var x = this.x, y = this.y, z = this.z, w = this.w;
  1559. switch (order) {
  1560. case "YZX":
  1561. var test = x * y + z * w;
  1562. if (test > 0.499) {
  1563. heading = 2 * Math.atan2(x, w);
  1564. attitude = Math.PI / 2;
  1565. bank = 0;
  1566. }
  1567. if (test < -0.499) {
  1568. heading = -2 * Math.atan2(x, w);
  1569. attitude = -Math.PI / 2;
  1570. bank = 0;
  1571. }
  1572. if (isNaN(heading)) {
  1573. var sqx = x * x;
  1574. var sqy = y * y;
  1575. var sqz = z * z;
  1576. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1577. attitude = Math.asin(2 * test); // attitude
  1578. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1579. }
  1580. break;
  1581. default:
  1582. throw new Error("Euler order " + order + " not supported yet.");
  1583. }
  1584. result.y = heading;
  1585. result.z = attitude;
  1586. result.x = bank;
  1587. return this;
  1588. };
  1589. ;
  1590. Quaternion.prototype.toRotationMatrix = function (result) {
  1591. var xx = this.x * this.x;
  1592. var yy = this.y * this.y;
  1593. var zz = this.z * this.z;
  1594. var xy = this.x * this.y;
  1595. var zw = this.z * this.w;
  1596. var zx = this.z * this.x;
  1597. var yw = this.y * this.w;
  1598. var yz = this.y * this.z;
  1599. var xw = this.x * this.w;
  1600. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1601. result.m[1] = 2.0 * (xy + zw);
  1602. result.m[2] = 2.0 * (zx - yw);
  1603. result.m[3] = 0;
  1604. result.m[4] = 2.0 * (xy - zw);
  1605. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1606. result.m[6] = 2.0 * (yz + xw);
  1607. result.m[7] = 0;
  1608. result.m[8] = 2.0 * (zx + yw);
  1609. result.m[9] = 2.0 * (yz - xw);
  1610. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1611. result.m[11] = 0;
  1612. result.m[12] = 0;
  1613. result.m[13] = 0;
  1614. result.m[14] = 0;
  1615. result.m[15] = 1.0;
  1616. return this;
  1617. };
  1618. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1619. Quaternion.FromRotationMatrixToRef(matrix, this);
  1620. return this;
  1621. };
  1622. // Statics
  1623. Quaternion.FromRotationMatrix = function (matrix) {
  1624. var result = new Quaternion();
  1625. Quaternion.FromRotationMatrixToRef(matrix, result);
  1626. return result;
  1627. };
  1628. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1629. var data = matrix.m;
  1630. var m11 = data[0], m12 = data[4], m13 = data[8];
  1631. var m21 = data[1], m22 = data[5], m23 = data[9];
  1632. var m31 = data[2], m32 = data[6], m33 = data[10];
  1633. var trace = m11 + m22 + m33;
  1634. var s;
  1635. if (trace > 0) {
  1636. s = 0.5 / Math.sqrt(trace + 1.0);
  1637. result.w = 0.25 / s;
  1638. result.x = (m32 - m23) * s;
  1639. result.y = (m13 - m31) * s;
  1640. result.z = (m21 - m12) * s;
  1641. }
  1642. else if (m11 > m22 && m11 > m33) {
  1643. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1644. result.w = (m32 - m23) / s;
  1645. result.x = 0.25 * s;
  1646. result.y = (m12 + m21) / s;
  1647. result.z = (m13 + m31) / s;
  1648. }
  1649. else if (m22 > m33) {
  1650. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1651. result.w = (m13 - m31) / s;
  1652. result.x = (m12 + m21) / s;
  1653. result.y = 0.25 * s;
  1654. result.z = (m23 + m32) / s;
  1655. }
  1656. else {
  1657. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1658. result.w = (m21 - m12) / s;
  1659. result.x = (m13 + m31) / s;
  1660. result.y = (m23 + m32) / s;
  1661. result.z = 0.25 * s;
  1662. }
  1663. };
  1664. Quaternion.Inverse = function (q) {
  1665. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1666. };
  1667. Quaternion.Identity = function () {
  1668. return new Quaternion(0, 0, 0, 1);
  1669. };
  1670. Quaternion.RotationAxis = function (axis, angle) {
  1671. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  1672. };
  1673. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  1674. var sin = Math.sin(angle / 2);
  1675. axis.normalize();
  1676. result.w = Math.cos(angle / 2);
  1677. result.x = axis.x * sin;
  1678. result.y = axis.y * sin;
  1679. result.z = axis.z * sin;
  1680. return result;
  1681. };
  1682. Quaternion.FromArray = function (array, offset) {
  1683. if (!offset) {
  1684. offset = 0;
  1685. }
  1686. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1687. };
  1688. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1689. var q = new Quaternion();
  1690. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  1691. return q;
  1692. };
  1693. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1694. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1695. var halfRoll = roll * 0.5;
  1696. var halfPitch = pitch * 0.5;
  1697. var halfYaw = yaw * 0.5;
  1698. var sinRoll = Math.sin(halfRoll);
  1699. var cosRoll = Math.cos(halfRoll);
  1700. var sinPitch = Math.sin(halfPitch);
  1701. var cosPitch = Math.cos(halfPitch);
  1702. var sinYaw = Math.sin(halfYaw);
  1703. var cosYaw = Math.cos(halfYaw);
  1704. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1705. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1706. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1707. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1708. };
  1709. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1710. var result = new Quaternion();
  1711. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1712. return result;
  1713. };
  1714. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1715. // Produces a quaternion from Euler angles in the z-x-z orientation
  1716. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1717. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1718. var halfBeta = beta * 0.5;
  1719. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1720. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1721. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1722. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1723. };
  1724. Quaternion.Slerp = function (left, right, amount) {
  1725. var num2;
  1726. var num3;
  1727. var num = amount;
  1728. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1729. var flag = false;
  1730. if (num4 < 0) {
  1731. flag = true;
  1732. num4 = -num4;
  1733. }
  1734. if (num4 > 0.999999) {
  1735. num3 = 1 - num;
  1736. num2 = flag ? -num : num;
  1737. }
  1738. else {
  1739. var num5 = Math.acos(num4);
  1740. var num6 = (1.0 / Math.sin(num5));
  1741. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1742. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1743. }
  1744. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1745. };
  1746. return Quaternion;
  1747. })();
  1748. BABYLON.Quaternion = Quaternion;
  1749. var Matrix = (function () {
  1750. function Matrix() {
  1751. this.m = new Float32Array(16);
  1752. }
  1753. // Properties
  1754. Matrix.prototype.isIdentity = function () {
  1755. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1756. return false;
  1757. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1758. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1759. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1760. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1761. return false;
  1762. return true;
  1763. };
  1764. Matrix.prototype.determinant = function () {
  1765. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1766. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1767. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1768. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1769. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1770. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1771. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1772. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1773. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1774. };
  1775. // Methods
  1776. Matrix.prototype.toArray = function () {
  1777. return this.m;
  1778. };
  1779. Matrix.prototype.asArray = function () {
  1780. return this.toArray();
  1781. };
  1782. Matrix.prototype.invert = function () {
  1783. this.invertToRef(this);
  1784. return this;
  1785. };
  1786. Matrix.prototype.reset = function () {
  1787. for (var index = 0; index < 16; index++) {
  1788. this.m[index] = 0;
  1789. }
  1790. return this;
  1791. };
  1792. Matrix.prototype.add = function (other) {
  1793. var result = new Matrix();
  1794. this.addToRef(other, result);
  1795. return result;
  1796. };
  1797. Matrix.prototype.addToRef = function (other, result) {
  1798. for (var index = 0; index < 16; index++) {
  1799. result.m[index] = this.m[index] + other.m[index];
  1800. }
  1801. return this;
  1802. };
  1803. Matrix.prototype.addToSelf = function (other) {
  1804. for (var index = 0; index < 16; index++) {
  1805. this.m[index] += other.m[index];
  1806. }
  1807. return this;
  1808. };
  1809. Matrix.prototype.invertToRef = function (other) {
  1810. var l1 = this.m[0];
  1811. var l2 = this.m[1];
  1812. var l3 = this.m[2];
  1813. var l4 = this.m[3];
  1814. var l5 = this.m[4];
  1815. var l6 = this.m[5];
  1816. var l7 = this.m[6];
  1817. var l8 = this.m[7];
  1818. var l9 = this.m[8];
  1819. var l10 = this.m[9];
  1820. var l11 = this.m[10];
  1821. var l12 = this.m[11];
  1822. var l13 = this.m[12];
  1823. var l14 = this.m[13];
  1824. var l15 = this.m[14];
  1825. var l16 = this.m[15];
  1826. var l17 = (l11 * l16) - (l12 * l15);
  1827. var l18 = (l10 * l16) - (l12 * l14);
  1828. var l19 = (l10 * l15) - (l11 * l14);
  1829. var l20 = (l9 * l16) - (l12 * l13);
  1830. var l21 = (l9 * l15) - (l11 * l13);
  1831. var l22 = (l9 * l14) - (l10 * l13);
  1832. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1833. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1834. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1835. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1836. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1837. var l28 = (l7 * l16) - (l8 * l15);
  1838. var l29 = (l6 * l16) - (l8 * l14);
  1839. var l30 = (l6 * l15) - (l7 * l14);
  1840. var l31 = (l5 * l16) - (l8 * l13);
  1841. var l32 = (l5 * l15) - (l7 * l13);
  1842. var l33 = (l5 * l14) - (l6 * l13);
  1843. var l34 = (l7 * l12) - (l8 * l11);
  1844. var l35 = (l6 * l12) - (l8 * l10);
  1845. var l36 = (l6 * l11) - (l7 * l10);
  1846. var l37 = (l5 * l12) - (l8 * l9);
  1847. var l38 = (l5 * l11) - (l7 * l9);
  1848. var l39 = (l5 * l10) - (l6 * l9);
  1849. other.m[0] = l23 * l27;
  1850. other.m[4] = l24 * l27;
  1851. other.m[8] = l25 * l27;
  1852. other.m[12] = l26 * l27;
  1853. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1854. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1855. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1856. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1857. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1858. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1859. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1860. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1861. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1862. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1863. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1864. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1865. return this;
  1866. };
  1867. Matrix.prototype.setTranslation = function (vector3) {
  1868. this.m[12] = vector3.x;
  1869. this.m[13] = vector3.y;
  1870. this.m[14] = vector3.z;
  1871. return this;
  1872. };
  1873. Matrix.prototype.getTranslation = function () {
  1874. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1875. };
  1876. Matrix.prototype.multiply = function (other) {
  1877. var result = new Matrix();
  1878. this.multiplyToRef(other, result);
  1879. return result;
  1880. };
  1881. Matrix.prototype.copyFrom = function (other) {
  1882. for (var index = 0; index < 16; index++) {
  1883. this.m[index] = other.m[index];
  1884. }
  1885. return this;
  1886. };
  1887. Matrix.prototype.copyToArray = function (array, offset) {
  1888. if (offset === void 0) { offset = 0; }
  1889. for (var index = 0; index < 16; index++) {
  1890. array[offset + index] = this.m[index];
  1891. }
  1892. return this;
  1893. };
  1894. Matrix.prototype.multiplyToRef = function (other, result) {
  1895. this.multiplyToArray(other, result.m, 0);
  1896. return this;
  1897. };
  1898. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1899. var tm0 = this.m[0];
  1900. var tm1 = this.m[1];
  1901. var tm2 = this.m[2];
  1902. var tm3 = this.m[3];
  1903. var tm4 = this.m[4];
  1904. var tm5 = this.m[5];
  1905. var tm6 = this.m[6];
  1906. var tm7 = this.m[7];
  1907. var tm8 = this.m[8];
  1908. var tm9 = this.m[9];
  1909. var tm10 = this.m[10];
  1910. var tm11 = this.m[11];
  1911. var tm12 = this.m[12];
  1912. var tm13 = this.m[13];
  1913. var tm14 = this.m[14];
  1914. var tm15 = this.m[15];
  1915. var om0 = other.m[0];
  1916. var om1 = other.m[1];
  1917. var om2 = other.m[2];
  1918. var om3 = other.m[3];
  1919. var om4 = other.m[4];
  1920. var om5 = other.m[5];
  1921. var om6 = other.m[6];
  1922. var om7 = other.m[7];
  1923. var om8 = other.m[8];
  1924. var om9 = other.m[9];
  1925. var om10 = other.m[10];
  1926. var om11 = other.m[11];
  1927. var om12 = other.m[12];
  1928. var om13 = other.m[13];
  1929. var om14 = other.m[14];
  1930. var om15 = other.m[15];
  1931. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1932. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1933. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1934. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1935. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1936. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1937. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1938. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1939. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1940. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1941. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1942. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1943. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1944. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1945. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1946. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1947. return this;
  1948. };
  1949. Matrix.prototype.equals = function (value) {
  1950. return value &&
  1951. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1952. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1953. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1954. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1955. };
  1956. Matrix.prototype.clone = function () {
  1957. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1958. };
  1959. Matrix.prototype.getClassName = function () {
  1960. return "Matrix";
  1961. };
  1962. Matrix.prototype.getHashCode = function () {
  1963. var hash = this.m[0] || 0;
  1964. for (var i = 1; i < 16; i++) {
  1965. hash = (hash * 397) ^ (this.m[i] || 0);
  1966. }
  1967. return hash;
  1968. };
  1969. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1970. translation.x = this.m[12];
  1971. translation.y = this.m[13];
  1972. translation.z = this.m[14];
  1973. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1974. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1975. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1976. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1977. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1978. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1979. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1980. rotation.x = 0;
  1981. rotation.y = 0;
  1982. rotation.z = 0;
  1983. rotation.w = 1;
  1984. return false;
  1985. }
  1986. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1987. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1988. return true;
  1989. };
  1990. // Statics
  1991. Matrix.FromArray = function (array, offset) {
  1992. var result = new Matrix();
  1993. if (!offset) {
  1994. offset = 0;
  1995. }
  1996. Matrix.FromArrayToRef(array, offset, result);
  1997. return result;
  1998. };
  1999. Matrix.FromArrayToRef = function (array, offset, result) {
  2000. for (var index = 0; index < 16; index++) {
  2001. result.m[index] = array[index + offset];
  2002. }
  2003. };
  2004. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  2005. for (var index = 0; index < 16; index++) {
  2006. result.m[index] = array[index + offset] * scale;
  2007. }
  2008. };
  2009. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2010. result.m[0] = initialM11;
  2011. result.m[1] = initialM12;
  2012. result.m[2] = initialM13;
  2013. result.m[3] = initialM14;
  2014. result.m[4] = initialM21;
  2015. result.m[5] = initialM22;
  2016. result.m[6] = initialM23;
  2017. result.m[7] = initialM24;
  2018. result.m[8] = initialM31;
  2019. result.m[9] = initialM32;
  2020. result.m[10] = initialM33;
  2021. result.m[11] = initialM34;
  2022. result.m[12] = initialM41;
  2023. result.m[13] = initialM42;
  2024. result.m[14] = initialM43;
  2025. result.m[15] = initialM44;
  2026. };
  2027. Matrix.prototype.getRow = function (index) {
  2028. if (index < 0 || index > 3) {
  2029. return null;
  2030. }
  2031. var i = index * 4;
  2032. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2033. };
  2034. Matrix.prototype.setRow = function (index, row) {
  2035. if (index < 0 || index > 3) {
  2036. return this;
  2037. }
  2038. var i = index * 4;
  2039. this.m[i + 0] = row.x;
  2040. this.m[i + 1] = row.y;
  2041. this.m[i + 2] = row.z;
  2042. this.m[i + 3] = row.w;
  2043. return this;
  2044. };
  2045. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2046. var result = new Matrix();
  2047. result.m[0] = initialM11;
  2048. result.m[1] = initialM12;
  2049. result.m[2] = initialM13;
  2050. result.m[3] = initialM14;
  2051. result.m[4] = initialM21;
  2052. result.m[5] = initialM22;
  2053. result.m[6] = initialM23;
  2054. result.m[7] = initialM24;
  2055. result.m[8] = initialM31;
  2056. result.m[9] = initialM32;
  2057. result.m[10] = initialM33;
  2058. result.m[11] = initialM34;
  2059. result.m[12] = initialM41;
  2060. result.m[13] = initialM42;
  2061. result.m[14] = initialM43;
  2062. result.m[15] = initialM44;
  2063. return result;
  2064. };
  2065. Matrix.Compose = function (scale, rotation, translation) {
  2066. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2067. var rotationMatrix = Matrix.Identity();
  2068. rotation.toRotationMatrix(rotationMatrix);
  2069. result = result.multiply(rotationMatrix);
  2070. result.setTranslation(translation);
  2071. return result;
  2072. };
  2073. Matrix.Identity = function () {
  2074. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2075. };
  2076. Matrix.IdentityToRef = function (result) {
  2077. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2078. };
  2079. Matrix.Zero = function () {
  2080. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2081. };
  2082. Matrix.RotationX = function (angle) {
  2083. var result = new Matrix();
  2084. Matrix.RotationXToRef(angle, result);
  2085. return result;
  2086. };
  2087. Matrix.Invert = function (source) {
  2088. var result = new Matrix();
  2089. source.invertToRef(result);
  2090. return result;
  2091. };
  2092. Matrix.RotationXToRef = function (angle, result) {
  2093. var s = Math.sin(angle);
  2094. var c = Math.cos(angle);
  2095. result.m[0] = 1.0;
  2096. result.m[15] = 1.0;
  2097. result.m[5] = c;
  2098. result.m[10] = c;
  2099. result.m[9] = -s;
  2100. result.m[6] = s;
  2101. result.m[1] = 0;
  2102. result.m[2] = 0;
  2103. result.m[3] = 0;
  2104. result.m[4] = 0;
  2105. result.m[7] = 0;
  2106. result.m[8] = 0;
  2107. result.m[11] = 0;
  2108. result.m[12] = 0;
  2109. result.m[13] = 0;
  2110. result.m[14] = 0;
  2111. };
  2112. Matrix.RotationY = function (angle) {
  2113. var result = new Matrix();
  2114. Matrix.RotationYToRef(angle, result);
  2115. return result;
  2116. };
  2117. Matrix.RotationYToRef = function (angle, result) {
  2118. var s = Math.sin(angle);
  2119. var c = Math.cos(angle);
  2120. result.m[5] = 1.0;
  2121. result.m[15] = 1.0;
  2122. result.m[0] = c;
  2123. result.m[2] = -s;
  2124. result.m[8] = s;
  2125. result.m[10] = c;
  2126. result.m[1] = 0;
  2127. result.m[3] = 0;
  2128. result.m[4] = 0;
  2129. result.m[6] = 0;
  2130. result.m[7] = 0;
  2131. result.m[9] = 0;
  2132. result.m[11] = 0;
  2133. result.m[12] = 0;
  2134. result.m[13] = 0;
  2135. result.m[14] = 0;
  2136. };
  2137. Matrix.RotationZ = function (angle) {
  2138. var result = new Matrix();
  2139. Matrix.RotationZToRef(angle, result);
  2140. return result;
  2141. };
  2142. Matrix.RotationZToRef = function (angle, result) {
  2143. var s = Math.sin(angle);
  2144. var c = Math.cos(angle);
  2145. result.m[10] = 1.0;
  2146. result.m[15] = 1.0;
  2147. result.m[0] = c;
  2148. result.m[1] = s;
  2149. result.m[4] = -s;
  2150. result.m[5] = c;
  2151. result.m[2] = 0;
  2152. result.m[3] = 0;
  2153. result.m[6] = 0;
  2154. result.m[7] = 0;
  2155. result.m[8] = 0;
  2156. result.m[9] = 0;
  2157. result.m[11] = 0;
  2158. result.m[12] = 0;
  2159. result.m[13] = 0;
  2160. result.m[14] = 0;
  2161. };
  2162. Matrix.RotationAxis = function (axis, angle) {
  2163. var result = Matrix.Zero();
  2164. Matrix.RotationAxisToRef(axis, angle, result);
  2165. return result;
  2166. };
  2167. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2168. var s = Math.sin(-angle);
  2169. var c = Math.cos(-angle);
  2170. var c1 = 1 - c;
  2171. axis.normalize();
  2172. result.m[0] = (axis.x * axis.x) * c1 + c;
  2173. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2174. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2175. result.m[3] = 0.0;
  2176. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2177. result.m[5] = (axis.y * axis.y) * c1 + c;
  2178. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2179. result.m[7] = 0.0;
  2180. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2181. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2182. result.m[10] = (axis.z * axis.z) * c1 + c;
  2183. result.m[11] = 0.0;
  2184. result.m[15] = 1.0;
  2185. };
  2186. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2187. var result = new Matrix();
  2188. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2189. return result;
  2190. };
  2191. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2192. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2193. this._tempQuaternion.toRotationMatrix(result);
  2194. };
  2195. Matrix.Scaling = function (x, y, z) {
  2196. var result = Matrix.Zero();
  2197. Matrix.ScalingToRef(x, y, z, result);
  2198. return result;
  2199. };
  2200. Matrix.ScalingToRef = function (x, y, z, result) {
  2201. result.m[0] = x;
  2202. result.m[1] = 0;
  2203. result.m[2] = 0;
  2204. result.m[3] = 0;
  2205. result.m[4] = 0;
  2206. result.m[5] = y;
  2207. result.m[6] = 0;
  2208. result.m[7] = 0;
  2209. result.m[8] = 0;
  2210. result.m[9] = 0;
  2211. result.m[10] = z;
  2212. result.m[11] = 0;
  2213. result.m[12] = 0;
  2214. result.m[13] = 0;
  2215. result.m[14] = 0;
  2216. result.m[15] = 1.0;
  2217. };
  2218. Matrix.Translation = function (x, y, z) {
  2219. var result = Matrix.Identity();
  2220. Matrix.TranslationToRef(x, y, z, result);
  2221. return result;
  2222. };
  2223. Matrix.TranslationToRef = function (x, y, z, result) {
  2224. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2225. };
  2226. Matrix.Lerp = function (startValue, endValue, gradient) {
  2227. var result = Matrix.Zero();
  2228. for (var index = 0; index < 16; index++) {
  2229. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2230. }
  2231. return result;
  2232. };
  2233. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2234. var startScale = new Vector3(0, 0, 0);
  2235. var startRotation = new Quaternion();
  2236. var startTranslation = new Vector3(0, 0, 0);
  2237. startValue.decompose(startScale, startRotation, startTranslation);
  2238. var endScale = new Vector3(0, 0, 0);
  2239. var endRotation = new Quaternion();
  2240. var endTranslation = new Vector3(0, 0, 0);
  2241. endValue.decompose(endScale, endRotation, endTranslation);
  2242. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2243. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2244. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2245. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2246. };
  2247. Matrix.LookAtLH = function (eye, target, up) {
  2248. var result = Matrix.Zero();
  2249. Matrix.LookAtLHToRef(eye, target, up, result);
  2250. return result;
  2251. };
  2252. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2253. // Z axis
  2254. target.subtractToRef(eye, this._zAxis);
  2255. this._zAxis.normalize();
  2256. // X axis
  2257. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2258. if (this._xAxis.lengthSquared() === 0) {
  2259. this._xAxis.x = 1.0;
  2260. }
  2261. else {
  2262. this._xAxis.normalize();
  2263. }
  2264. // Y axis
  2265. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2266. this._yAxis.normalize();
  2267. // Eye angles
  2268. var ex = -Vector3.Dot(this._xAxis, eye);
  2269. var ey = -Vector3.Dot(this._yAxis, eye);
  2270. var ez = -Vector3.Dot(this._zAxis, eye);
  2271. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  2272. };
  2273. Matrix.LookAtRH = function (eye, target, up) {
  2274. var result = Matrix.Zero();
  2275. Matrix.LookAtRHToRef(eye, target, up, result);
  2276. return result;
  2277. };
  2278. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  2279. // Z axis
  2280. eye.subtractToRef(target, this._zAxis);
  2281. this._zAxis.normalize();
  2282. // X axis
  2283. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2284. if (this._xAxis.lengthSquared() === 0) {
  2285. this._xAxis.x = 1.0;
  2286. }
  2287. else {
  2288. this._xAxis.normalize();
  2289. }
  2290. // Y axis
  2291. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2292. this._yAxis.normalize();
  2293. // Eye angles
  2294. var ex = -Vector3.Dot(this._xAxis, eye);
  2295. var ey = -Vector3.Dot(this._yAxis, eye);
  2296. var ez = -Vector3.Dot(this._zAxis, eye);
  2297. 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);
  2298. };
  2299. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2300. var matrix = Matrix.Zero();
  2301. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2302. return matrix;
  2303. };
  2304. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2305. var hw = 2.0 / width;
  2306. var hh = 2.0 / height;
  2307. var id = 1.0 / (zfar - znear);
  2308. var nid = znear / (znear - zfar);
  2309. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2310. };
  2311. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2312. var matrix = Matrix.Zero();
  2313. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2314. return matrix;
  2315. };
  2316. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2317. result.m[0] = 2.0 / (right - left);
  2318. result.m[1] = result.m[2] = result.m[3] = 0;
  2319. result.m[5] = 2.0 / (top - bottom);
  2320. result.m[4] = result.m[6] = result.m[7] = 0;
  2321. result.m[10] = 1.0 / (zfar - znear);
  2322. result.m[8] = result.m[9] = result.m[11] = 0;
  2323. result.m[12] = (left + right) / (left - right);
  2324. result.m[13] = (top + bottom) / (bottom - top);
  2325. result.m[14] = -znear / (zfar - znear);
  2326. result.m[15] = 1.0;
  2327. };
  2328. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  2329. var matrix = Matrix.Zero();
  2330. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  2331. return matrix;
  2332. };
  2333. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2334. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  2335. result.m[10] *= -1.0;
  2336. };
  2337. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2338. var matrix = Matrix.Zero();
  2339. matrix.m[0] = (2.0 * znear) / width;
  2340. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2341. matrix.m[5] = (2.0 * znear) / height;
  2342. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2343. matrix.m[10] = -zfar / (znear - zfar);
  2344. matrix.m[8] = matrix.m[9] = 0.0;
  2345. matrix.m[11] = 1.0;
  2346. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2347. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2348. return matrix;
  2349. };
  2350. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2351. var matrix = Matrix.Zero();
  2352. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2353. return matrix;
  2354. };
  2355. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2356. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2357. var tan = 1.0 / (Math.tan(fov * 0.5));
  2358. if (isVerticalFovFixed) {
  2359. result.m[0] = tan / aspect;
  2360. }
  2361. else {
  2362. result.m[0] = tan;
  2363. }
  2364. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2365. if (isVerticalFovFixed) {
  2366. result.m[5] = tan;
  2367. }
  2368. else {
  2369. result.m[5] = tan * aspect;
  2370. }
  2371. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2372. result.m[8] = result.m[9] = 0.0;
  2373. result.m[10] = zfar / (zfar - znear);
  2374. result.m[11] = 1.0;
  2375. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2376. result.m[14] = -(znear * zfar) / (zfar - znear);
  2377. };
  2378. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  2379. var matrix = Matrix.Zero();
  2380. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  2381. return matrix;
  2382. };
  2383. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2384. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2385. var tan = 1.0 / (Math.tan(fov * 0.5));
  2386. if (isVerticalFovFixed) {
  2387. result.m[0] = tan / aspect;
  2388. }
  2389. else {
  2390. result.m[0] = tan;
  2391. }
  2392. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2393. if (isVerticalFovFixed) {
  2394. result.m[5] = tan;
  2395. }
  2396. else {
  2397. result.m[5] = tan * aspect;
  2398. }
  2399. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2400. result.m[8] = result.m[9] = 0.0;
  2401. result.m[10] = zfar / (znear - zfar);
  2402. result.m[11] = -1.0;
  2403. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2404. result.m[14] = (znear * zfar) / (znear - zfar);
  2405. };
  2406. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, isVerticalFovFixed) {
  2407. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2408. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  2409. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  2410. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  2411. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  2412. var xScale = 2.0 / (leftTan + rightTan);
  2413. var yScale = 2.0 / (upTan + downTan);
  2414. result.m[0] = xScale;
  2415. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  2416. result.m[5] = yScale;
  2417. result.m[6] = result.m[7] = 0.0;
  2418. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  2419. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  2420. //result.m[10] = -(znear + zfar) / (zfar - znear);
  2421. result.m[10] = -zfar / (znear - zfar);
  2422. result.m[11] = 1.0;
  2423. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2424. //result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  2425. result.m[14] = (znear * zfar) / (znear - zfar);
  2426. };
  2427. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2428. var cw = viewport.width;
  2429. var ch = viewport.height;
  2430. var cx = viewport.x;
  2431. var cy = viewport.y;
  2432. 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);
  2433. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2434. };
  2435. Matrix.GetAsMatrix2x2 = function (matrix) {
  2436. return new Float32Array([
  2437. matrix.m[0], matrix.m[1],
  2438. matrix.m[4], matrix.m[5]
  2439. ]);
  2440. };
  2441. Matrix.GetAsMatrix3x3 = function (matrix) {
  2442. return new Float32Array([
  2443. matrix.m[0], matrix.m[1], matrix.m[2],
  2444. matrix.m[4], matrix.m[5], matrix.m[6],
  2445. matrix.m[8], matrix.m[9], matrix.m[10]
  2446. ]);
  2447. };
  2448. Matrix.Transpose = function (matrix) {
  2449. var result = new Matrix();
  2450. result.m[0] = matrix.m[0];
  2451. result.m[1] = matrix.m[4];
  2452. result.m[2] = matrix.m[8];
  2453. result.m[3] = matrix.m[12];
  2454. result.m[4] = matrix.m[1];
  2455. result.m[5] = matrix.m[5];
  2456. result.m[6] = matrix.m[9];
  2457. result.m[7] = matrix.m[13];
  2458. result.m[8] = matrix.m[2];
  2459. result.m[9] = matrix.m[6];
  2460. result.m[10] = matrix.m[10];
  2461. result.m[11] = matrix.m[14];
  2462. result.m[12] = matrix.m[3];
  2463. result.m[13] = matrix.m[7];
  2464. result.m[14] = matrix.m[11];
  2465. result.m[15] = matrix.m[15];
  2466. return result;
  2467. };
  2468. Matrix.Reflection = function (plane) {
  2469. var matrix = new Matrix();
  2470. Matrix.ReflectionToRef(plane, matrix);
  2471. return matrix;
  2472. };
  2473. Matrix.ReflectionToRef = function (plane, result) {
  2474. plane.normalize();
  2475. var x = plane.normal.x;
  2476. var y = plane.normal.y;
  2477. var z = plane.normal.z;
  2478. var temp = -2 * x;
  2479. var temp2 = -2 * y;
  2480. var temp3 = -2 * z;
  2481. result.m[0] = (temp * x) + 1;
  2482. result.m[1] = temp2 * x;
  2483. result.m[2] = temp3 * x;
  2484. result.m[3] = 0.0;
  2485. result.m[4] = temp * y;
  2486. result.m[5] = (temp2 * y) + 1;
  2487. result.m[6] = temp3 * y;
  2488. result.m[7] = 0.0;
  2489. result.m[8] = temp * z;
  2490. result.m[9] = temp2 * z;
  2491. result.m[10] = (temp3 * z) + 1;
  2492. result.m[11] = 0.0;
  2493. result.m[12] = temp * plane.d;
  2494. result.m[13] = temp2 * plane.d;
  2495. result.m[14] = temp3 * plane.d;
  2496. result.m[15] = 1.0;
  2497. };
  2498. Matrix._tempQuaternion = new Quaternion();
  2499. Matrix._xAxis = Vector3.Zero();
  2500. Matrix._yAxis = Vector3.Zero();
  2501. Matrix._zAxis = Vector3.Zero();
  2502. return Matrix;
  2503. })();
  2504. BABYLON.Matrix = Matrix;
  2505. var Plane = (function () {
  2506. function Plane(a, b, c, d) {
  2507. this.normal = new Vector3(a, b, c);
  2508. this.d = d;
  2509. }
  2510. Plane.prototype.asArray = function () {
  2511. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2512. };
  2513. // Methods
  2514. Plane.prototype.clone = function () {
  2515. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2516. };
  2517. Plane.prototype.getClassName = function () {
  2518. return "Plane";
  2519. };
  2520. Plane.prototype.getHashCode = function () {
  2521. var hash = this.normal.getHashCode();
  2522. hash = (hash * 397) ^ (this.d || 0);
  2523. return hash;
  2524. };
  2525. Plane.prototype.normalize = function () {
  2526. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2527. var magnitude = 0;
  2528. if (norm !== 0) {
  2529. magnitude = 1.0 / norm;
  2530. }
  2531. this.normal.x *= magnitude;
  2532. this.normal.y *= magnitude;
  2533. this.normal.z *= magnitude;
  2534. this.d *= magnitude;
  2535. return this;
  2536. };
  2537. Plane.prototype.transform = function (transformation) {
  2538. var transposedMatrix = Matrix.Transpose(transformation);
  2539. var x = this.normal.x;
  2540. var y = this.normal.y;
  2541. var z = this.normal.z;
  2542. var d = this.d;
  2543. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2544. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2545. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2546. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2547. return new Plane(normalX, normalY, normalZ, finalD);
  2548. };
  2549. Plane.prototype.dotCoordinate = function (point) {
  2550. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2551. };
  2552. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2553. var x1 = point2.x - point1.x;
  2554. var y1 = point2.y - point1.y;
  2555. var z1 = point2.z - point1.z;
  2556. var x2 = point3.x - point1.x;
  2557. var y2 = point3.y - point1.y;
  2558. var z2 = point3.z - point1.z;
  2559. var yz = (y1 * z2) - (z1 * y2);
  2560. var xz = (z1 * x2) - (x1 * z2);
  2561. var xy = (x1 * y2) - (y1 * x2);
  2562. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2563. var invPyth;
  2564. if (pyth !== 0) {
  2565. invPyth = 1.0 / pyth;
  2566. }
  2567. else {
  2568. invPyth = 0;
  2569. }
  2570. this.normal.x = yz * invPyth;
  2571. this.normal.y = xz * invPyth;
  2572. this.normal.z = xy * invPyth;
  2573. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2574. return this;
  2575. };
  2576. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2577. var dot = Vector3.Dot(this.normal, direction);
  2578. return (dot <= epsilon);
  2579. };
  2580. Plane.prototype.signedDistanceTo = function (point) {
  2581. return Vector3.Dot(point, this.normal) + this.d;
  2582. };
  2583. // Statics
  2584. Plane.FromArray = function (array) {
  2585. return new Plane(array[0], array[1], array[2], array[3]);
  2586. };
  2587. Plane.FromPoints = function (point1, point2, point3) {
  2588. var result = new Plane(0, 0, 0, 0);
  2589. result.copyFromPoints(point1, point2, point3);
  2590. return result;
  2591. };
  2592. Plane.FromPositionAndNormal = function (origin, normal) {
  2593. var result = new Plane(0, 0, 0, 0);
  2594. normal.normalize();
  2595. result.normal = normal;
  2596. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2597. return result;
  2598. };
  2599. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2600. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2601. return Vector3.Dot(point, normal) + d;
  2602. };
  2603. return Plane;
  2604. })();
  2605. BABYLON.Plane = Plane;
  2606. var Viewport = (function () {
  2607. function Viewport(x, y, width, height) {
  2608. this.x = x;
  2609. this.y = y;
  2610. this.width = width;
  2611. this.height = height;
  2612. }
  2613. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2614. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2615. };
  2616. return Viewport;
  2617. })();
  2618. BABYLON.Viewport = Viewport;
  2619. var Frustum = (function () {
  2620. function Frustum() {
  2621. }
  2622. Frustum.GetPlanes = function (transform) {
  2623. var frustumPlanes = [];
  2624. for (var index = 0; index < 6; index++) {
  2625. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2626. }
  2627. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2628. return frustumPlanes;
  2629. };
  2630. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2631. // Near
  2632. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2633. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2634. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2635. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2636. frustumPlanes[0].normalize();
  2637. // Far
  2638. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2639. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2640. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2641. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2642. frustumPlanes[1].normalize();
  2643. // Left
  2644. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2645. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2646. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2647. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2648. frustumPlanes[2].normalize();
  2649. // Right
  2650. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2651. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2652. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2653. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2654. frustumPlanes[3].normalize();
  2655. // Top
  2656. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2657. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2658. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2659. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2660. frustumPlanes[4].normalize();
  2661. // Bottom
  2662. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2663. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2664. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2665. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2666. frustumPlanes[5].normalize();
  2667. };
  2668. return Frustum;
  2669. })();
  2670. BABYLON.Frustum = Frustum;
  2671. (function (Space) {
  2672. Space[Space["LOCAL"] = 0] = "LOCAL";
  2673. Space[Space["WORLD"] = 1] = "WORLD";
  2674. })(BABYLON.Space || (BABYLON.Space = {}));
  2675. var Space = BABYLON.Space;
  2676. var Axis = (function () {
  2677. function Axis() {
  2678. }
  2679. Axis.X = new Vector3(1, 0, 0);
  2680. Axis.Y = new Vector3(0, 1, 0);
  2681. Axis.Z = new Vector3(0, 0, 1);
  2682. return Axis;
  2683. })();
  2684. BABYLON.Axis = Axis;
  2685. ;
  2686. var BezierCurve = (function () {
  2687. function BezierCurve() {
  2688. }
  2689. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2690. // Extract X (which is equal to time here)
  2691. var f0 = 1 - 3 * x2 + 3 * x1;
  2692. var f1 = 3 * x2 - 6 * x1;
  2693. var f2 = 3 * x1;
  2694. var refinedT = t;
  2695. for (var i = 0; i < 5; i++) {
  2696. var refinedT2 = refinedT * refinedT;
  2697. var refinedT3 = refinedT2 * refinedT;
  2698. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2699. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2700. refinedT -= (x - t) * slope;
  2701. refinedT = Math.min(1, Math.max(0, refinedT));
  2702. }
  2703. // Resolve cubic bezier for the given x
  2704. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2705. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2706. Math.pow(refinedT, 3);
  2707. };
  2708. return BezierCurve;
  2709. })();
  2710. BABYLON.BezierCurve = BezierCurve;
  2711. (function (Orientation) {
  2712. Orientation[Orientation["CW"] = 0] = "CW";
  2713. Orientation[Orientation["CCW"] = 1] = "CCW";
  2714. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2715. var Orientation = BABYLON.Orientation;
  2716. var Angle = (function () {
  2717. function Angle(radians) {
  2718. var _this = this;
  2719. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2720. this.radians = function () { return _this._radians; };
  2721. this._radians = radians;
  2722. if (this._radians < 0)
  2723. this._radians += (2 * Math.PI);
  2724. }
  2725. Angle.BetweenTwoPoints = function (a, b) {
  2726. var delta = b.subtract(a);
  2727. var theta = Math.atan2(delta.y, delta.x);
  2728. return new Angle(theta);
  2729. };
  2730. Angle.FromRadians = function (radians) {
  2731. return new Angle(radians);
  2732. };
  2733. Angle.FromDegrees = function (degrees) {
  2734. return new Angle(degrees * Math.PI / 180);
  2735. };
  2736. return Angle;
  2737. })();
  2738. BABYLON.Angle = Angle;
  2739. var Arc2 = (function () {
  2740. function Arc2(startPoint, midPoint, endPoint) {
  2741. this.startPoint = startPoint;
  2742. this.midPoint = midPoint;
  2743. this.endPoint = endPoint;
  2744. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2745. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2746. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2747. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2748. 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);
  2749. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2750. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2751. var a1 = this.startAngle.degrees();
  2752. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2753. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2754. // angles correction
  2755. if (a2 - a1 > +180.0)
  2756. a2 -= 360.0;
  2757. if (a2 - a1 < -180.0)
  2758. a2 += 360.0;
  2759. if (a3 - a2 > +180.0)
  2760. a3 -= 360.0;
  2761. if (a3 - a2 < -180.0)
  2762. a3 += 360.0;
  2763. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2764. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2765. }
  2766. return Arc2;
  2767. })();
  2768. BABYLON.Arc2 = Arc2;
  2769. var Path2 = (function () {
  2770. function Path2(x, y) {
  2771. this._points = new Array();
  2772. this._length = 0;
  2773. this.closed = false;
  2774. this._points.push(new Vector2(x, y));
  2775. }
  2776. Path2.prototype.addLineTo = function (x, y) {
  2777. if (closed) {
  2778. //Tools.Error("cannot add lines to closed paths");
  2779. return this;
  2780. }
  2781. var newPoint = new Vector2(x, y);
  2782. var previousPoint = this._points[this._points.length - 1];
  2783. this._points.push(newPoint);
  2784. this._length += newPoint.subtract(previousPoint).length();
  2785. return this;
  2786. };
  2787. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2788. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2789. if (closed) {
  2790. //Tools.Error("cannot add arcs to closed paths");
  2791. return this;
  2792. }
  2793. var startPoint = this._points[this._points.length - 1];
  2794. var midPoint = new Vector2(midX, midY);
  2795. var endPoint = new Vector2(endX, endY);
  2796. var arc = new Arc2(startPoint, midPoint, endPoint);
  2797. var increment = arc.angle.radians() / numberOfSegments;
  2798. if (arc.orientation === Orientation.CW)
  2799. increment *= -1;
  2800. var currentAngle = arc.startAngle.radians() + increment;
  2801. for (var i = 0; i < numberOfSegments; i++) {
  2802. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2803. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2804. this.addLineTo(x, y);
  2805. currentAngle += increment;
  2806. }
  2807. return this;
  2808. };
  2809. Path2.prototype.close = function () {
  2810. this.closed = true;
  2811. return this;
  2812. };
  2813. Path2.prototype.length = function () {
  2814. var result = this._length;
  2815. if (!this.closed) {
  2816. var lastPoint = this._points[this._points.length - 1];
  2817. var firstPoint = this._points[0];
  2818. result += (firstPoint.subtract(lastPoint).length());
  2819. }
  2820. return result;
  2821. };
  2822. Path2.prototype.getPoints = function () {
  2823. return this._points;
  2824. };
  2825. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2826. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2827. //Tools.Error("normalized length position should be between 0 and 1.");
  2828. return Vector2.Zero();
  2829. }
  2830. var lengthPosition = normalizedLengthPosition * this.length();
  2831. var previousOffset = 0;
  2832. for (var i = 0; i < this._points.length; i++) {
  2833. var j = (i + 1) % this._points.length;
  2834. var a = this._points[i];
  2835. var b = this._points[j];
  2836. var bToA = b.subtract(a);
  2837. var nextOffset = (bToA.length() + previousOffset);
  2838. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2839. var dir = bToA.normalize();
  2840. var localOffset = lengthPosition - previousOffset;
  2841. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2842. }
  2843. previousOffset = nextOffset;
  2844. }
  2845. //Tools.Error("internal error");
  2846. return Vector2.Zero();
  2847. };
  2848. Path2.StartingAt = function (x, y) {
  2849. return new Path2(x, y);
  2850. };
  2851. return Path2;
  2852. })();
  2853. BABYLON.Path2 = Path2;
  2854. var Path3D = (function () {
  2855. /**
  2856. * new Path3D(path, normal, raw)
  2857. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2858. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2859. * path : an array of Vector3, the curve axis of the Path3D
  2860. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2861. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2862. */
  2863. function Path3D(path, firstNormal, raw) {
  2864. this.path = path;
  2865. this._curve = new Array();
  2866. this._distances = new Array();
  2867. this._tangents = new Array();
  2868. this._normals = new Array();
  2869. this._binormals = new Array();
  2870. for (var p = 0; p < path.length; p++) {
  2871. this._curve[p] = path[p].clone(); // hard copy
  2872. }
  2873. this._raw = raw || false;
  2874. this._compute(firstNormal);
  2875. }
  2876. /**
  2877. * Returns the Path3D array of successive Vector3 designing its curve.
  2878. */
  2879. Path3D.prototype.getCurve = function () {
  2880. return this._curve;
  2881. };
  2882. /**
  2883. * Returns an array populated with tangent vectors on each Path3D curve point.
  2884. */
  2885. Path3D.prototype.getTangents = function () {
  2886. return this._tangents;
  2887. };
  2888. /**
  2889. * Returns an array populated with normal vectors on each Path3D curve point.
  2890. */
  2891. Path3D.prototype.getNormals = function () {
  2892. return this._normals;
  2893. };
  2894. /**
  2895. * Returns an array populated with binormal vectors on each Path3D curve point.
  2896. */
  2897. Path3D.prototype.getBinormals = function () {
  2898. return this._binormals;
  2899. };
  2900. /**
  2901. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2902. */
  2903. Path3D.prototype.getDistances = function () {
  2904. return this._distances;
  2905. };
  2906. /**
  2907. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2908. * Returns the same object updated.
  2909. */
  2910. Path3D.prototype.update = function (path, firstNormal) {
  2911. for (var p = 0; p < path.length; p++) {
  2912. this._curve[p].x = path[p].x;
  2913. this._curve[p].y = path[p].y;
  2914. this._curve[p].z = path[p].z;
  2915. }
  2916. this._compute(firstNormal);
  2917. return this;
  2918. };
  2919. // private function compute() : computes tangents, normals and binormals
  2920. Path3D.prototype._compute = function (firstNormal) {
  2921. var l = this._curve.length;
  2922. // first and last tangents
  2923. this._tangents[0] = this._getFirstNonNullVector(0);
  2924. if (!this._raw) {
  2925. this._tangents[0].normalize();
  2926. }
  2927. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2928. if (!this._raw) {
  2929. this._tangents[l - 1].normalize();
  2930. }
  2931. // normals and binormals at first point : arbitrary vector with _normalVector()
  2932. var tg0 = this._tangents[0];
  2933. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2934. this._normals[0] = pp0;
  2935. if (!this._raw) {
  2936. this._normals[0].normalize();
  2937. }
  2938. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2939. if (!this._raw) {
  2940. this._binormals[0].normalize();
  2941. }
  2942. this._distances[0] = 0.0;
  2943. // normals and binormals : next points
  2944. var prev; // previous vector (segment)
  2945. var cur; // current vector (segment)
  2946. var curTang; // current tangent
  2947. // previous normal
  2948. var prevBinor; // previous binormal
  2949. for (var i = 1; i < l; i++) {
  2950. // tangents
  2951. prev = this._getLastNonNullVector(i);
  2952. if (i < l - 1) {
  2953. cur = this._getFirstNonNullVector(i);
  2954. this._tangents[i] = prev.add(cur);
  2955. this._tangents[i].normalize();
  2956. }
  2957. this._distances[i] = this._distances[i - 1] + prev.length();
  2958. // normals and binormals
  2959. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2960. curTang = this._tangents[i];
  2961. prevBinor = this._binormals[i - 1];
  2962. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2963. if (!this._raw) {
  2964. this._normals[i].normalize();
  2965. }
  2966. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2967. if (!this._raw) {
  2968. this._binormals[i].normalize();
  2969. }
  2970. }
  2971. };
  2972. // private function getFirstNonNullVector(index)
  2973. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2974. Path3D.prototype._getFirstNonNullVector = function (index) {
  2975. var i = 1;
  2976. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2977. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2978. i++;
  2979. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2980. }
  2981. return nNVector;
  2982. };
  2983. // private function getLastNonNullVector(index)
  2984. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2985. Path3D.prototype._getLastNonNullVector = function (index) {
  2986. var i = 1;
  2987. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2988. while (nLVector.length() === 0 && index > i + 1) {
  2989. i++;
  2990. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2991. }
  2992. return nLVector;
  2993. };
  2994. // private function normalVector(v0, vt, va) :
  2995. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2996. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2997. Path3D.prototype._normalVector = function (v0, vt, va) {
  2998. var normal0;
  2999. var tgl = vt.length();
  3000. if (tgl === 0.0) {
  3001. tgl = 1.0;
  3002. }
  3003. if (va === undefined || va === null) {
  3004. var point;
  3005. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  3006. point = new Vector3(0.0, -1.0, 0.0);
  3007. }
  3008. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  3009. point = new Vector3(1.0, 0.0, 0.0);
  3010. }
  3011. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  3012. point = new Vector3(0.0, 0.0, 1.0);
  3013. }
  3014. normal0 = Vector3.Cross(vt, point);
  3015. }
  3016. else {
  3017. normal0 = Vector3.Cross(vt, va);
  3018. Vector3.CrossToRef(normal0, vt, normal0);
  3019. }
  3020. normal0.normalize();
  3021. return normal0;
  3022. };
  3023. return Path3D;
  3024. })();
  3025. BABYLON.Path3D = Path3D;
  3026. var Curve3 = (function () {
  3027. /**
  3028. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  3029. * A Curve3 is designed from a series of successive Vector3.
  3030. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  3031. */
  3032. function Curve3(points) {
  3033. this._length = 0.0;
  3034. this._points = points;
  3035. this._length = this._computeLength(points);
  3036. }
  3037. /**
  3038. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  3039. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  3040. * @param v1 (Vector3) the control point
  3041. * @param v2 (Vector3) the end point of the Quadratic Bezier
  3042. * @param nbPoints (integer) the wanted number of points in the curve
  3043. */
  3044. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  3045. nbPoints = nbPoints > 2 ? nbPoints : 3;
  3046. var bez = new Array();
  3047. var equation = function (t, val0, val1, val2) {
  3048. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  3049. return res;
  3050. };
  3051. for (var i = 0; i <= nbPoints; i++) {
  3052. 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)));
  3053. }
  3054. return new Curve3(bez);
  3055. };
  3056. /**
  3057. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  3058. * @param v0 (Vector3) the origin point of the Cubic Bezier
  3059. * @param v1 (Vector3) the first control point
  3060. * @param v2 (Vector3) the second control point
  3061. * @param v3 (Vector3) the end point of the Cubic Bezier
  3062. * @param nbPoints (integer) the wanted number of points in the curve
  3063. */
  3064. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3065. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3066. var bez = new Array();
  3067. var equation = function (t, val0, val1, val2, val3) {
  3068. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  3069. return res;
  3070. };
  3071. for (var i = 0; i <= nbPoints; i++) {
  3072. 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)));
  3073. }
  3074. return new Curve3(bez);
  3075. };
  3076. /**
  3077. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  3078. * @param p1 (Vector3) the origin point of the Hermite Spline
  3079. * @param t1 (Vector3) the tangent vector at the origin point
  3080. * @param p2 (Vector3) the end point of the Hermite Spline
  3081. * @param t2 (Vector3) the tangent vector at the end point
  3082. * @param nbPoints (integer) the wanted number of points in the curve
  3083. */
  3084. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3085. var hermite = new Array();
  3086. var step = 1.0 / nbPoints;
  3087. for (var i = 0; i <= nbPoints; i++) {
  3088. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3089. }
  3090. return new Curve3(hermite);
  3091. };
  3092. /**
  3093. * Returns the Curve3 stored array of successive Vector3
  3094. */
  3095. Curve3.prototype.getPoints = function () {
  3096. return this._points;
  3097. };
  3098. /**
  3099. * Returns the computed length (float) of the curve.
  3100. */
  3101. Curve3.prototype.length = function () {
  3102. return this._length;
  3103. };
  3104. /**
  3105. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  3106. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  3107. * curveA and curveB keep unchanged.
  3108. */
  3109. Curve3.prototype.continue = function (curve) {
  3110. var lastPoint = this._points[this._points.length - 1];
  3111. var continuedPoints = this._points.slice();
  3112. var curvePoints = curve.getPoints();
  3113. for (var i = 1; i < curvePoints.length; i++) {
  3114. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3115. }
  3116. var continuedCurve = new Curve3(continuedPoints);
  3117. return continuedCurve;
  3118. };
  3119. Curve3.prototype._computeLength = function (path) {
  3120. var l = 0;
  3121. for (var i = 1; i < path.length; i++) {
  3122. l += (path[i].subtract(path[i - 1])).length();
  3123. }
  3124. return l;
  3125. };
  3126. return Curve3;
  3127. })();
  3128. BABYLON.Curve3 = Curve3;
  3129. // SphericalHarmonics
  3130. var SphericalHarmonics = (function () {
  3131. function SphericalHarmonics() {
  3132. this.L00 = Vector3.Zero();
  3133. this.L1_1 = Vector3.Zero();
  3134. this.L10 = Vector3.Zero();
  3135. this.L11 = Vector3.Zero();
  3136. this.L2_2 = Vector3.Zero();
  3137. this.L2_1 = Vector3.Zero();
  3138. this.L20 = Vector3.Zero();
  3139. this.L21 = Vector3.Zero();
  3140. this.L22 = Vector3.Zero();
  3141. }
  3142. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3143. var colorVector = new Vector3(color.r, color.g, color.b);
  3144. var c = colorVector.scale(deltaSolidAngle);
  3145. this.L00 = this.L00.add(c.scale(0.282095));
  3146. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3147. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3148. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3149. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3150. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3151. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3152. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3153. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3154. };
  3155. SphericalHarmonics.prototype.scale = function (scale) {
  3156. this.L00 = this.L00.scale(scale);
  3157. this.L1_1 = this.L1_1.scale(scale);
  3158. this.L10 = this.L10.scale(scale);
  3159. this.L11 = this.L11.scale(scale);
  3160. this.L2_2 = this.L2_2.scale(scale);
  3161. this.L2_1 = this.L2_1.scale(scale);
  3162. this.L20 = this.L20.scale(scale);
  3163. this.L21 = this.L21.scale(scale);
  3164. this.L22 = this.L22.scale(scale);
  3165. };
  3166. return SphericalHarmonics;
  3167. })();
  3168. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3169. // SphericalPolynomial
  3170. var SphericalPolynomial = (function () {
  3171. function SphericalPolynomial() {
  3172. this.x = Vector3.Zero();
  3173. this.y = Vector3.Zero();
  3174. this.z = Vector3.Zero();
  3175. this.xx = Vector3.Zero();
  3176. this.yy = Vector3.Zero();
  3177. this.zz = Vector3.Zero();
  3178. this.xy = Vector3.Zero();
  3179. this.yz = Vector3.Zero();
  3180. this.zx = Vector3.Zero();
  3181. }
  3182. SphericalPolynomial.prototype.addAmbient = function (color) {
  3183. var colorVector = new Vector3(color.r, color.g, color.b);
  3184. this.xx = this.xx.add(colorVector);
  3185. this.yy = this.yy.add(colorVector);
  3186. this.zz = this.zz.add(colorVector);
  3187. };
  3188. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3189. var result = new SphericalPolynomial();
  3190. result.x = harmonics.L11.scale(1.02333);
  3191. result.y = harmonics.L1_1.scale(1.02333);
  3192. result.z = harmonics.L10.scale(1.02333);
  3193. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3194. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3195. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3196. result.yz = harmonics.L2_1.scale(0.858086);
  3197. result.zx = harmonics.L21.scale(0.858086);
  3198. result.xy = harmonics.L2_2.scale(0.858086);
  3199. return result;
  3200. };
  3201. return SphericalPolynomial;
  3202. })();
  3203. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3204. // Vertex formats
  3205. var PositionNormalVertex = (function () {
  3206. function PositionNormalVertex(position, normal) {
  3207. if (position === void 0) { position = Vector3.Zero(); }
  3208. if (normal === void 0) { normal = Vector3.Up(); }
  3209. this.position = position;
  3210. this.normal = normal;
  3211. }
  3212. PositionNormalVertex.prototype.clone = function () {
  3213. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3214. };
  3215. return PositionNormalVertex;
  3216. })();
  3217. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3218. var PositionNormalTextureVertex = (function () {
  3219. function PositionNormalTextureVertex(position, normal, uv) {
  3220. if (position === void 0) { position = Vector3.Zero(); }
  3221. if (normal === void 0) { normal = Vector3.Up(); }
  3222. if (uv === void 0) { uv = Vector2.Zero(); }
  3223. this.position = position;
  3224. this.normal = normal;
  3225. this.uv = uv;
  3226. }
  3227. PositionNormalTextureVertex.prototype.clone = function () {
  3228. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3229. };
  3230. return PositionNormalTextureVertex;
  3231. })();
  3232. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3233. // Temporary pre-allocated objects for engine internal use
  3234. // usage in any internal function :
  3235. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3236. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3237. var Tmp = (function () {
  3238. function Tmp() {
  3239. }
  3240. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3241. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3242. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3243. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3244. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3245. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3246. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3247. Matrix.Zero(), Matrix.Zero(),
  3248. Matrix.Zero(), Matrix.Zero(),
  3249. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3250. return Tmp;
  3251. })();
  3252. BABYLON.Tmp = Tmp;
  3253. })(BABYLON || (BABYLON = {}));
  3254. var BABYLON;
  3255. (function (BABYLON) {
  3256. function generateSerializableMember(type, sourceName) {
  3257. return function (target, propertyKey) {
  3258. if (!target.__serializableMembers) {
  3259. target.__serializableMembers = {};
  3260. }
  3261. if (!target.__serializableMembers[propertyKey]) {
  3262. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3263. }
  3264. };
  3265. }
  3266. function serialize(sourceName) {
  3267. return generateSerializableMember(0, sourceName); // value member
  3268. }
  3269. BABYLON.serialize = serialize;
  3270. function serializeAsTexture(sourceName) {
  3271. return generateSerializableMember(1, sourceName); // texture member
  3272. }
  3273. BABYLON.serializeAsTexture = serializeAsTexture;
  3274. function serializeAsColor3(sourceName) {
  3275. return generateSerializableMember(2, sourceName); // color3 member
  3276. }
  3277. BABYLON.serializeAsColor3 = serializeAsColor3;
  3278. function serializeAsFresnelParameters(sourceName) {
  3279. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3280. }
  3281. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3282. function serializeAsVector2(sourceName) {
  3283. return generateSerializableMember(4, sourceName); // vector2 member
  3284. }
  3285. BABYLON.serializeAsVector2 = serializeAsVector2;
  3286. function serializeAsVector3(sourceName) {
  3287. return generateSerializableMember(5, sourceName); // vector3 member
  3288. }
  3289. BABYLON.serializeAsVector3 = serializeAsVector3;
  3290. function serializeAsMeshReference(sourceName) {
  3291. return generateSerializableMember(6, sourceName); // mesh reference member
  3292. }
  3293. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3294. function serializeAsColorCurves(sourceName) {
  3295. return generateSerializableMember(7, sourceName); // color curves
  3296. }
  3297. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3298. var SerializationHelper = (function () {
  3299. function SerializationHelper() {
  3300. }
  3301. SerializationHelper.Serialize = function (entity, serializationObject) {
  3302. if (!serializationObject) {
  3303. serializationObject = {};
  3304. }
  3305. // Tags
  3306. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3307. // Properties
  3308. for (var property in entity.__serializableMembers) {
  3309. var propertyDescriptor = entity.__serializableMembers[property];
  3310. var targetPropertyName = propertyDescriptor.sourceName || property;
  3311. var propertyType = propertyDescriptor.type;
  3312. var sourceProperty = entity[property];
  3313. if (sourceProperty !== undefined && sourceProperty !== null) {
  3314. switch (propertyType) {
  3315. case 0:
  3316. serializationObject[targetPropertyName] = sourceProperty;
  3317. break;
  3318. case 1:
  3319. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3320. break;
  3321. case 2:
  3322. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3323. break;
  3324. case 3:
  3325. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3326. break;
  3327. case 4:
  3328. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3329. break;
  3330. case 5:
  3331. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3332. break;
  3333. case 6:
  3334. serializationObject[targetPropertyName] = sourceProperty.id;
  3335. break;
  3336. case 7:
  3337. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3338. break;
  3339. }
  3340. }
  3341. }
  3342. return serializationObject;
  3343. };
  3344. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3345. var destination = creationFunction();
  3346. // Tags
  3347. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3348. // Properties
  3349. for (var property in destination.__serializableMembers) {
  3350. var propertyDescriptor = destination.__serializableMembers[property];
  3351. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3352. var propertyType = propertyDescriptor.type;
  3353. if (sourceProperty !== undefined && sourceProperty !== null) {
  3354. switch (propertyType) {
  3355. case 0:
  3356. destination[property] = sourceProperty;
  3357. break;
  3358. case 1:
  3359. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3360. break;
  3361. case 2:
  3362. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3363. break;
  3364. case 3:
  3365. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3366. break;
  3367. case 4:
  3368. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3369. break;
  3370. case 5:
  3371. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3372. break;
  3373. case 6:
  3374. destination[property] = scene.getLastMeshByID(sourceProperty);
  3375. break;
  3376. case 7:
  3377. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3378. break;
  3379. }
  3380. }
  3381. }
  3382. return destination;
  3383. };
  3384. SerializationHelper.Clone = function (creationFunction, source) {
  3385. var destination = creationFunction();
  3386. // Tags
  3387. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3388. // Properties
  3389. for (var property in destination.__serializableMembers) {
  3390. var propertyDescriptor = destination.__serializableMembers[property];
  3391. var sourceProperty = source[property];
  3392. var propertyType = propertyDescriptor.type;
  3393. if (sourceProperty !== undefined && sourceProperty !== null) {
  3394. switch (propertyType) {
  3395. case 0: // Value
  3396. case 6:
  3397. destination[property] = sourceProperty;
  3398. break;
  3399. case 1: // Texture
  3400. case 2: // Color3
  3401. case 3: // FresnelParameters
  3402. case 4: // Vector2
  3403. case 5: // Vector3
  3404. case 7:
  3405. destination[property] = sourceProperty.clone();
  3406. break;
  3407. }
  3408. }
  3409. }
  3410. return destination;
  3411. };
  3412. return SerializationHelper;
  3413. })();
  3414. BABYLON.SerializationHelper = SerializationHelper;
  3415. })(BABYLON || (BABYLON = {}));
  3416. var BABYLON;
  3417. (function (BABYLON) {
  3418. /**
  3419. * A class serves as a medium between the observable and its observers
  3420. */
  3421. var EventState = (function () {
  3422. /**
  3423. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3424. */
  3425. function EventState(mask, skipNextObservers) {
  3426. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3427. this.initalize(mask, skipNextObservers);
  3428. }
  3429. EventState.prototype.initalize = function (mask, skipNextObservers) {
  3430. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3431. this.mask = mask;
  3432. this.skipNextObservers = skipNextObservers;
  3433. return this;
  3434. };
  3435. return EventState;
  3436. })();
  3437. BABYLON.EventState = EventState;
  3438. /**
  3439. * Represent an Observer registered to a given Observable object.
  3440. */
  3441. var Observer = (function () {
  3442. function Observer(callback, mask) {
  3443. this.callback = callback;
  3444. this.mask = mask;
  3445. }
  3446. return Observer;
  3447. })();
  3448. BABYLON.Observer = Observer;
  3449. /**
  3450. * The Observable class is a simple implementation of the Observable pattern.
  3451. * 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.
  3452. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3453. * 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).
  3454. * 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.
  3455. */
  3456. var Observable = (function () {
  3457. function Observable() {
  3458. this._observers = new Array();
  3459. this._eventState = new EventState(0);
  3460. }
  3461. /**
  3462. * Create a new Observer with the specified callback
  3463. * @param callback the callback that will be executed for that Observer
  3464. * @param mask the mask used to filter observers
  3465. * @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.
  3466. */
  3467. Observable.prototype.add = function (callback, mask, insertFirst) {
  3468. if (mask === void 0) { mask = -1; }
  3469. if (insertFirst === void 0) { insertFirst = false; }
  3470. if (!callback) {
  3471. return null;
  3472. }
  3473. var observer = new Observer(callback, mask);
  3474. if (insertFirst) {
  3475. this._observers.unshift(observer);
  3476. }
  3477. else {
  3478. this._observers.push(observer);
  3479. }
  3480. return observer;
  3481. };
  3482. /**
  3483. * Remove an Observer from the Observable object
  3484. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3485. */
  3486. Observable.prototype.remove = function (observer) {
  3487. var index = this._observers.indexOf(observer);
  3488. if (index !== -1) {
  3489. this._observers.splice(index, 1);
  3490. return true;
  3491. }
  3492. return false;
  3493. };
  3494. /**
  3495. * Remove a callback from the Observable object
  3496. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3497. */
  3498. Observable.prototype.removeCallback = function (callback) {
  3499. for (var index = 0; index < this._observers.length; index++) {
  3500. if (this._observers[index].callback === callback) {
  3501. this._observers.splice(index, 1);
  3502. return true;
  3503. }
  3504. }
  3505. return false;
  3506. };
  3507. /**
  3508. * Notify all Observers by calling their respective callback with the given data
  3509. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  3510. * @param eventData
  3511. * @param mask
  3512. */
  3513. Observable.prototype.notifyObservers = function (eventData, mask) {
  3514. if (mask === void 0) { mask = -1; }
  3515. var state = this._eventState;
  3516. state.mask = mask;
  3517. state.skipNextObservers = false;
  3518. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3519. var obs = _a[_i];
  3520. if (obs.mask & mask) {
  3521. obs.callback(eventData, state);
  3522. }
  3523. if (state.skipNextObservers) {
  3524. return false;
  3525. }
  3526. }
  3527. return true;
  3528. };
  3529. /**
  3530. * return true is the Observable has at least one Observer registered
  3531. */
  3532. Observable.prototype.hasObservers = function () {
  3533. return this._observers.length > 0;
  3534. };
  3535. /**
  3536. * Clear the list of observers
  3537. */
  3538. Observable.prototype.clear = function () {
  3539. this._observers = new Array();
  3540. };
  3541. /**
  3542. * Clone the current observable
  3543. */
  3544. Observable.prototype.clone = function () {
  3545. var result = new Observable();
  3546. result._observers = this._observers.slice(0);
  3547. return result;
  3548. };
  3549. return Observable;
  3550. })();
  3551. BABYLON.Observable = Observable;
  3552. })(BABYLON || (BABYLON = {}));
  3553. var BABYLON;
  3554. (function (BABYLON) {
  3555. var Database = (function () {
  3556. function Database(urlToScene, callbackManifestChecked) {
  3557. // Handling various flavors of prefixed version of IndexedDB
  3558. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3559. this.callbackManifestChecked = callbackManifestChecked;
  3560. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3561. this.db = null;
  3562. this.enableSceneOffline = false;
  3563. this.enableTexturesOffline = false;
  3564. this.manifestVersionFound = 0;
  3565. this.mustUpdateRessources = false;
  3566. this.hasReachedQuota = false;
  3567. if (!Database.IDBStorageEnabled) {
  3568. this.callbackManifestChecked(true);
  3569. }
  3570. else {
  3571. this.checkManifestFile();
  3572. }
  3573. }
  3574. Database.prototype.checkManifestFile = function () {
  3575. var _this = this;
  3576. function noManifestFile() {
  3577. that.enableSceneOffline = false;
  3578. that.enableTexturesOffline = false;
  3579. that.callbackManifestChecked(false);
  3580. }
  3581. var that = this;
  3582. var timeStampUsed = false;
  3583. var manifestURL = this.currentSceneUrl + ".manifest";
  3584. var xhr = new XMLHttpRequest();
  3585. if (navigator.onLine) {
  3586. // Adding a timestamp to by-pass browsers' cache
  3587. timeStampUsed = true;
  3588. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3589. }
  3590. xhr.open("GET", manifestURL, true);
  3591. xhr.addEventListener("load", function () {
  3592. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3593. try {
  3594. var manifestFile = JSON.parse(xhr.response);
  3595. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3596. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3597. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3598. _this.manifestVersionFound = manifestFile.version;
  3599. }
  3600. if (_this.callbackManifestChecked) {
  3601. _this.callbackManifestChecked(true);
  3602. }
  3603. }
  3604. catch (ex) {
  3605. noManifestFile();
  3606. }
  3607. }
  3608. else {
  3609. noManifestFile();
  3610. }
  3611. }, false);
  3612. xhr.addEventListener("error", function (event) {
  3613. if (timeStampUsed) {
  3614. timeStampUsed = false;
  3615. // Let's retry without the timeStamp
  3616. // It could fail when coupled with HTML5 Offline API
  3617. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3618. xhr.open("GET", retryManifestURL, true);
  3619. xhr.send();
  3620. }
  3621. else {
  3622. noManifestFile();
  3623. }
  3624. }, false);
  3625. try {
  3626. xhr.send();
  3627. }
  3628. catch (ex) {
  3629. BABYLON.Tools.Error("Error on XHR send request.");
  3630. that.callbackManifestChecked(false);
  3631. }
  3632. };
  3633. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3634. var _this = this;
  3635. function handleError() {
  3636. that.isSupported = false;
  3637. if (errorCallback)
  3638. errorCallback();
  3639. }
  3640. var that = this;
  3641. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3642. // Your browser doesn't support IndexedDB
  3643. this.isSupported = false;
  3644. if (errorCallback)
  3645. errorCallback();
  3646. }
  3647. else {
  3648. // If the DB hasn't been opened or created yet
  3649. if (!this.db) {
  3650. this.hasReachedQuota = false;
  3651. this.isSupported = true;
  3652. var request = this.idbFactory.open("babylonjs", 1);
  3653. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3654. request.onerror = function (event) {
  3655. handleError();
  3656. };
  3657. // executes when a version change transaction cannot complete due to other active transactions
  3658. request.onblocked = function (event) {
  3659. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3660. handleError();
  3661. };
  3662. // DB has been opened successfully
  3663. request.onsuccess = function (event) {
  3664. _this.db = request.result;
  3665. successCallback();
  3666. };
  3667. // Initialization of the DB. Creating Scenes & Textures stores
  3668. request.onupgradeneeded = function (event) {
  3669. _this.db = (event.target).result;
  3670. try {
  3671. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3672. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3673. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3674. }
  3675. catch (ex) {
  3676. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3677. handleError();
  3678. }
  3679. };
  3680. }
  3681. else {
  3682. if (successCallback)
  3683. successCallback();
  3684. }
  3685. }
  3686. };
  3687. Database.prototype.loadImageFromDB = function (url, image) {
  3688. var _this = this;
  3689. var completeURL = Database.ReturnFullUrlLocation(url);
  3690. var saveAndLoadImage = function () {
  3691. if (!_this.hasReachedQuota && _this.db !== null) {
  3692. // the texture is not yet in the DB, let's try to save it
  3693. _this._saveImageIntoDBAsync(completeURL, image);
  3694. }
  3695. else {
  3696. image.src = url;
  3697. }
  3698. };
  3699. if (!this.mustUpdateRessources) {
  3700. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3701. }
  3702. else {
  3703. saveAndLoadImage();
  3704. }
  3705. };
  3706. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3707. if (this.isSupported && this.db !== null) {
  3708. var texture;
  3709. var transaction = this.db.transaction(["textures"]);
  3710. transaction.onabort = function (event) {
  3711. image.src = url;
  3712. };
  3713. transaction.oncomplete = function (event) {
  3714. var blobTextureURL;
  3715. if (texture) {
  3716. var URL = window.URL || window.webkitURL;
  3717. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3718. image.onerror = function () {
  3719. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3720. image.src = url;
  3721. };
  3722. image.src = blobTextureURL;
  3723. }
  3724. else {
  3725. notInDBCallback();
  3726. }
  3727. };
  3728. var getRequest = transaction.objectStore("textures").get(url);
  3729. getRequest.onsuccess = function (event) {
  3730. texture = (event.target).result;
  3731. };
  3732. getRequest.onerror = function (event) {
  3733. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3734. image.src = url;
  3735. };
  3736. }
  3737. else {
  3738. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3739. image.src = url;
  3740. }
  3741. };
  3742. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3743. var _this = this;
  3744. if (this.isSupported) {
  3745. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3746. var generateBlobUrl = function () {
  3747. var blobTextureURL;
  3748. if (blob) {
  3749. var URL = window.URL || window.webkitURL;
  3750. try {
  3751. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3752. }
  3753. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3754. catch (ex) {
  3755. blobTextureURL = URL.createObjectURL(blob);
  3756. }
  3757. }
  3758. image.src = blobTextureURL;
  3759. };
  3760. if (Database.IsUASupportingBlobStorage) {
  3761. var xhr = new XMLHttpRequest(), blob;
  3762. xhr.open("GET", url, true);
  3763. xhr.responseType = "blob";
  3764. xhr.addEventListener("load", function () {
  3765. if (xhr.status === 200) {
  3766. // Blob as response (XHR2)
  3767. blob = xhr.response;
  3768. var transaction = _this.db.transaction(["textures"], "readwrite");
  3769. // the transaction could abort because of a QuotaExceededError error
  3770. transaction.onabort = function (event) {
  3771. try {
  3772. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3773. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3774. this.hasReachedQuota = true;
  3775. }
  3776. }
  3777. catch (ex) { }
  3778. generateBlobUrl();
  3779. };
  3780. transaction.oncomplete = function (event) {
  3781. generateBlobUrl();
  3782. };
  3783. var newTexture = { textureUrl: url, data: blob };
  3784. try {
  3785. // Put the blob into the dabase
  3786. var addRequest = transaction.objectStore("textures").put(newTexture);
  3787. addRequest.onsuccess = function (event) {
  3788. };
  3789. addRequest.onerror = function (event) {
  3790. generateBlobUrl();
  3791. };
  3792. }
  3793. catch (ex) {
  3794. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3795. if (ex.code === 25) {
  3796. Database.IsUASupportingBlobStorage = false;
  3797. }
  3798. image.src = url;
  3799. }
  3800. }
  3801. else {
  3802. image.src = url;
  3803. }
  3804. }, false);
  3805. xhr.addEventListener("error", function (event) {
  3806. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3807. image.src = url;
  3808. }, false);
  3809. xhr.send();
  3810. }
  3811. else {
  3812. image.src = url;
  3813. }
  3814. }
  3815. else {
  3816. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3817. image.src = url;
  3818. }
  3819. };
  3820. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3821. var _this = this;
  3822. var updateVersion = function (event) {
  3823. // the version is not yet in the DB or we need to update it
  3824. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3825. };
  3826. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3827. };
  3828. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3829. var _this = this;
  3830. if (this.isSupported) {
  3831. var version;
  3832. try {
  3833. var transaction = this.db.transaction(["versions"]);
  3834. transaction.oncomplete = function (event) {
  3835. if (version) {
  3836. // If the version in the JSON file is > than the version in DB
  3837. if (_this.manifestVersionFound > version.data) {
  3838. _this.mustUpdateRessources = true;
  3839. updateInDBCallback();
  3840. }
  3841. else {
  3842. callback(version.data);
  3843. }
  3844. }
  3845. else {
  3846. _this.mustUpdateRessources = true;
  3847. updateInDBCallback();
  3848. }
  3849. };
  3850. transaction.onabort = function (event) {
  3851. callback(-1);
  3852. };
  3853. var getRequest = transaction.objectStore("versions").get(url);
  3854. getRequest.onsuccess = function (event) {
  3855. version = (event.target).result;
  3856. };
  3857. getRequest.onerror = function (event) {
  3858. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3859. callback(-1);
  3860. };
  3861. }
  3862. catch (ex) {
  3863. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3864. callback(-1);
  3865. }
  3866. }
  3867. else {
  3868. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3869. callback(-1);
  3870. }
  3871. };
  3872. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3873. var _this = this;
  3874. if (this.isSupported && !this.hasReachedQuota) {
  3875. try {
  3876. // Open a transaction to the database
  3877. var transaction = this.db.transaction(["versions"], "readwrite");
  3878. // the transaction could abort because of a QuotaExceededError error
  3879. transaction.onabort = function (event) {
  3880. try {
  3881. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3882. _this.hasReachedQuota = true;
  3883. }
  3884. }
  3885. catch (ex) { }
  3886. callback(-1);
  3887. };
  3888. transaction.oncomplete = function (event) {
  3889. callback(_this.manifestVersionFound);
  3890. };
  3891. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3892. // Put the scene into the database
  3893. var addRequest = transaction.objectStore("versions").put(newVersion);
  3894. addRequest.onsuccess = function (event) {
  3895. };
  3896. addRequest.onerror = function (event) {
  3897. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3898. };
  3899. }
  3900. catch (ex) {
  3901. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3902. callback(-1);
  3903. }
  3904. }
  3905. else {
  3906. callback(-1);
  3907. }
  3908. };
  3909. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3910. var _this = this;
  3911. var completeUrl = Database.ReturnFullUrlLocation(url);
  3912. var saveAndLoadFile = function (event) {
  3913. // the scene is not yet in the DB, let's try to save it
  3914. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3915. };
  3916. this._checkVersionFromDB(completeUrl, function (version) {
  3917. if (version !== -1) {
  3918. if (!_this.mustUpdateRessources) {
  3919. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3920. }
  3921. else {
  3922. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3923. }
  3924. }
  3925. else {
  3926. errorCallback();
  3927. }
  3928. });
  3929. };
  3930. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3931. if (this.isSupported) {
  3932. var targetStore;
  3933. if (url.indexOf(".babylon") !== -1) {
  3934. targetStore = "scenes";
  3935. }
  3936. else {
  3937. targetStore = "textures";
  3938. }
  3939. var file;
  3940. var transaction = this.db.transaction([targetStore]);
  3941. transaction.oncomplete = function (event) {
  3942. if (file) {
  3943. callback(file.data);
  3944. }
  3945. else {
  3946. notInDBCallback();
  3947. }
  3948. };
  3949. transaction.onabort = function (event) {
  3950. notInDBCallback();
  3951. };
  3952. var getRequest = transaction.objectStore(targetStore).get(url);
  3953. getRequest.onsuccess = function (event) {
  3954. file = (event.target).result;
  3955. };
  3956. getRequest.onerror = function (event) {
  3957. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3958. notInDBCallback();
  3959. };
  3960. }
  3961. else {
  3962. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3963. callback();
  3964. }
  3965. };
  3966. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3967. var _this = this;
  3968. if (this.isSupported) {
  3969. var targetStore;
  3970. if (url.indexOf(".babylon") !== -1) {
  3971. targetStore = "scenes";
  3972. }
  3973. else {
  3974. targetStore = "textures";
  3975. }
  3976. // Create XHR
  3977. var xhr = new XMLHttpRequest(), fileData;
  3978. xhr.open("GET", url, true);
  3979. if (useArrayBuffer) {
  3980. xhr.responseType = "arraybuffer";
  3981. }
  3982. xhr.onprogress = progressCallback;
  3983. xhr.addEventListener("load", function () {
  3984. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3985. // Blob as response (XHR2)
  3986. //fileData = xhr.responseText;
  3987. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3988. if (!_this.hasReachedQuota) {
  3989. // Open a transaction to the database
  3990. var transaction = _this.db.transaction([targetStore], "readwrite");
  3991. // the transaction could abort because of a QuotaExceededError error
  3992. transaction.onabort = function (event) {
  3993. try {
  3994. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3995. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3996. this.hasReachedQuota = true;
  3997. }
  3998. }
  3999. catch (ex) { }
  4000. callback(fileData);
  4001. };
  4002. transaction.oncomplete = function (event) {
  4003. callback(fileData);
  4004. };
  4005. var newFile;
  4006. if (targetStore === "scenes") {
  4007. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  4008. }
  4009. else {
  4010. newFile = { textureUrl: url, data: fileData };
  4011. }
  4012. try {
  4013. // Put the scene into the database
  4014. var addRequest = transaction.objectStore(targetStore).put(newFile);
  4015. addRequest.onsuccess = function (event) {
  4016. };
  4017. addRequest.onerror = function (event) {
  4018. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  4019. };
  4020. }
  4021. catch (ex) {
  4022. callback(fileData);
  4023. }
  4024. }
  4025. else {
  4026. callback(fileData);
  4027. }
  4028. }
  4029. else {
  4030. callback();
  4031. }
  4032. }, false);
  4033. xhr.addEventListener("error", function (event) {
  4034. BABYLON.Tools.Error("error on XHR request.");
  4035. callback();
  4036. }, false);
  4037. xhr.send();
  4038. }
  4039. else {
  4040. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4041. callback();
  4042. }
  4043. };
  4044. Database.IsUASupportingBlobStorage = true;
  4045. Database.IDBStorageEnabled = true;
  4046. Database.parseURL = function (url) {
  4047. var a = document.createElement('a');
  4048. a.href = url;
  4049. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  4050. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  4051. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  4052. return absLocation;
  4053. };
  4054. Database.ReturnFullUrlLocation = function (url) {
  4055. if (url.indexOf("http:/") === -1) {
  4056. return (Database.parseURL(window.location.href) + url);
  4057. }
  4058. else {
  4059. return url;
  4060. }
  4061. };
  4062. return Database;
  4063. })();
  4064. BABYLON.Database = Database;
  4065. })(BABYLON || (BABYLON = {}));
  4066. var BABYLON;
  4067. (function (BABYLON) {
  4068. var Internals;
  4069. (function (Internals) {
  4070. /*
  4071. * Based on jsTGALoader - Javascript loader for TGA file
  4072. * By Vincent Thibault
  4073. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  4074. */
  4075. var TGATools = (function () {
  4076. function TGATools() {
  4077. }
  4078. TGATools.GetTGAHeader = function (data) {
  4079. var offset = 0;
  4080. var header = {
  4081. id_length: data[offset++],
  4082. colormap_type: data[offset++],
  4083. image_type: data[offset++],
  4084. colormap_index: data[offset++] | data[offset++] << 8,
  4085. colormap_length: data[offset++] | data[offset++] << 8,
  4086. colormap_size: data[offset++],
  4087. origin: [
  4088. data[offset++] | data[offset++] << 8,
  4089. data[offset++] | data[offset++] << 8
  4090. ],
  4091. width: data[offset++] | data[offset++] << 8,
  4092. height: data[offset++] | data[offset++] << 8,
  4093. pixel_size: data[offset++],
  4094. flags: data[offset++]
  4095. };
  4096. return header;
  4097. };
  4098. TGATools.UploadContent = function (gl, data) {
  4099. // Not enough data to contain header ?
  4100. if (data.length < 19) {
  4101. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  4102. return;
  4103. }
  4104. // Read Header
  4105. var offset = 18;
  4106. var header = TGATools.GetTGAHeader(data);
  4107. // Assume it's a valid Targa file.
  4108. if (header.id_length + offset > data.length) {
  4109. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  4110. return;
  4111. }
  4112. // Skip not needed data
  4113. offset += header.id_length;
  4114. var use_rle = false;
  4115. var use_pal = false;
  4116. var use_rgb = false;
  4117. var use_grey = false;
  4118. // Get some informations.
  4119. switch (header.image_type) {
  4120. case TGATools._TYPE_RLE_INDEXED:
  4121. use_rle = true;
  4122. case TGATools._TYPE_INDEXED:
  4123. use_pal = true;
  4124. break;
  4125. case TGATools._TYPE_RLE_RGB:
  4126. use_rle = true;
  4127. case TGATools._TYPE_RGB:
  4128. use_rgb = true;
  4129. break;
  4130. case TGATools._TYPE_RLE_GREY:
  4131. use_rle = true;
  4132. case TGATools._TYPE_GREY:
  4133. use_grey = true;
  4134. break;
  4135. }
  4136. var pixel_data;
  4137. var numAlphaBits = header.flags & 0xf;
  4138. var pixel_size = header.pixel_size >> 3;
  4139. var pixel_total = header.width * header.height * pixel_size;
  4140. // Read palettes
  4141. var palettes;
  4142. if (use_pal) {
  4143. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4144. }
  4145. // Read LRE
  4146. if (use_rle) {
  4147. pixel_data = new Uint8Array(pixel_total);
  4148. var c, count, i;
  4149. var localOffset = 0;
  4150. var pixels = new Uint8Array(pixel_size);
  4151. while (offset < pixel_total && localOffset < pixel_total) {
  4152. c = data[offset++];
  4153. count = (c & 0x7f) + 1;
  4154. // RLE pixels
  4155. if (c & 0x80) {
  4156. // Bind pixel tmp array
  4157. for (i = 0; i < pixel_size; ++i) {
  4158. pixels[i] = data[offset++];
  4159. }
  4160. // Copy pixel array
  4161. for (i = 0; i < count; ++i) {
  4162. pixel_data.set(pixels, localOffset + i * pixel_size);
  4163. }
  4164. localOffset += pixel_size * count;
  4165. }
  4166. else {
  4167. count *= pixel_size;
  4168. for (i = 0; i < count; ++i) {
  4169. pixel_data[localOffset + i] = data[offset++];
  4170. }
  4171. localOffset += count;
  4172. }
  4173. }
  4174. }
  4175. else {
  4176. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4177. }
  4178. // Load to texture
  4179. var x_start, y_start, x_step, y_step, y_end, x_end;
  4180. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4181. default:
  4182. case TGATools._ORIGIN_UL:
  4183. x_start = 0;
  4184. x_step = 1;
  4185. x_end = header.width;
  4186. y_start = 0;
  4187. y_step = 1;
  4188. y_end = header.height;
  4189. break;
  4190. case TGATools._ORIGIN_BL:
  4191. x_start = 0;
  4192. x_step = 1;
  4193. x_end = header.width;
  4194. y_start = header.height - 1;
  4195. y_step = -1;
  4196. y_end = -1;
  4197. break;
  4198. case TGATools._ORIGIN_UR:
  4199. x_start = header.width - 1;
  4200. x_step = -1;
  4201. x_end = -1;
  4202. y_start = 0;
  4203. y_step = 1;
  4204. y_end = header.height;
  4205. break;
  4206. case TGATools._ORIGIN_BR:
  4207. x_start = header.width - 1;
  4208. x_step = -1;
  4209. x_end = -1;
  4210. y_start = header.height - 1;
  4211. y_step = -1;
  4212. y_end = -1;
  4213. break;
  4214. }
  4215. // Load the specify method
  4216. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4217. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4218. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4219. };
  4220. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4221. var image = pixel_data, colormap = palettes;
  4222. var width = header.width, height = header.height;
  4223. var color, i = 0, x, y;
  4224. var imageData = new Uint8Array(width * height * 4);
  4225. for (y = y_start; y !== y_end; y += y_step) {
  4226. for (x = x_start; x !== x_end; x += x_step, i++) {
  4227. color = image[i];
  4228. imageData[(x + width * y) * 4 + 3] = 255;
  4229. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4230. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4231. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4232. }
  4233. }
  4234. return imageData;
  4235. };
  4236. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4237. var image = pixel_data;
  4238. var width = header.width, height = header.height;
  4239. var color, i = 0, x, y;
  4240. var imageData = new Uint8Array(width * height * 4);
  4241. for (y = y_start; y !== y_end; y += y_step) {
  4242. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4243. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4244. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4245. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4246. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4247. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4248. }
  4249. }
  4250. return imageData;
  4251. };
  4252. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4253. var image = pixel_data;
  4254. var width = header.width, height = header.height;
  4255. var i = 0, x, y;
  4256. var imageData = new Uint8Array(width * height * 4);
  4257. for (y = y_start; y !== y_end; y += y_step) {
  4258. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4259. imageData[(x + width * y) * 4 + 3] = 255;
  4260. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4261. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4262. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4263. }
  4264. }
  4265. return imageData;
  4266. };
  4267. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4268. var image = pixel_data;
  4269. var width = header.width, height = header.height;
  4270. var i = 0, x, y;
  4271. var imageData = new Uint8Array(width * height * 4);
  4272. for (y = y_start; y !== y_end; y += y_step) {
  4273. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4274. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4275. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4276. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4277. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4278. }
  4279. }
  4280. return imageData;
  4281. };
  4282. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4283. var image = pixel_data;
  4284. var width = header.width, height = header.height;
  4285. var color, i = 0, x, y;
  4286. var imageData = new Uint8Array(width * height * 4);
  4287. for (y = y_start; y !== y_end; y += y_step) {
  4288. for (x = x_start; x !== x_end; x += x_step, i++) {
  4289. color = image[i];
  4290. imageData[(x + width * y) * 4 + 0] = color;
  4291. imageData[(x + width * y) * 4 + 1] = color;
  4292. imageData[(x + width * y) * 4 + 2] = color;
  4293. imageData[(x + width * y) * 4 + 3] = 255;
  4294. }
  4295. }
  4296. return imageData;
  4297. };
  4298. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4299. var image = pixel_data;
  4300. var width = header.width, height = header.height;
  4301. var i = 0, x, y;
  4302. var imageData = new Uint8Array(width * height * 4);
  4303. for (y = y_start; y !== y_end; y += y_step) {
  4304. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4305. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4306. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4307. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4308. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4309. }
  4310. }
  4311. return imageData;
  4312. };
  4313. TGATools._TYPE_NO_DATA = 0;
  4314. TGATools._TYPE_INDEXED = 1;
  4315. TGATools._TYPE_RGB = 2;
  4316. TGATools._TYPE_GREY = 3;
  4317. TGATools._TYPE_RLE_INDEXED = 9;
  4318. TGATools._TYPE_RLE_RGB = 10;
  4319. TGATools._TYPE_RLE_GREY = 11;
  4320. TGATools._ORIGIN_MASK = 0x30;
  4321. TGATools._ORIGIN_SHIFT = 0x04;
  4322. TGATools._ORIGIN_BL = 0x00;
  4323. TGATools._ORIGIN_BR = 0x01;
  4324. TGATools._ORIGIN_UL = 0x02;
  4325. TGATools._ORIGIN_UR = 0x03;
  4326. return TGATools;
  4327. })();
  4328. Internals.TGATools = TGATools;
  4329. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4330. })(BABYLON || (BABYLON = {}));
  4331. var BABYLON;
  4332. (function (BABYLON) {
  4333. var SmartArray = (function () {
  4334. function SmartArray(capacity) {
  4335. this.length = 0;
  4336. this._duplicateId = 0;
  4337. this.data = new Array(capacity);
  4338. this._id = SmartArray._GlobalId++;
  4339. }
  4340. SmartArray.prototype.push = function (value) {
  4341. this.data[this.length++] = value;
  4342. if (this.length > this.data.length) {
  4343. this.data.length *= 2;
  4344. }
  4345. if (!value.__smartArrayFlags) {
  4346. value.__smartArrayFlags = {};
  4347. }
  4348. value.__smartArrayFlags[this._id] = this._duplicateId;
  4349. };
  4350. SmartArray.prototype.pushNoDuplicate = function (value) {
  4351. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4352. return false;
  4353. }
  4354. this.push(value);
  4355. return true;
  4356. };
  4357. SmartArray.prototype.sort = function (compareFn) {
  4358. this.data.sort(compareFn);
  4359. };
  4360. SmartArray.prototype.reset = function () {
  4361. this.length = 0;
  4362. this._duplicateId++;
  4363. };
  4364. SmartArray.prototype.concat = function (array) {
  4365. if (array.length === 0) {
  4366. return;
  4367. }
  4368. if (this.length + array.length > this.data.length) {
  4369. this.data.length = (this.length + array.length) * 2;
  4370. }
  4371. for (var index = 0; index < array.length; index++) {
  4372. this.data[this.length++] = (array.data || array)[index];
  4373. }
  4374. };
  4375. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4376. if (array.length === 0) {
  4377. return;
  4378. }
  4379. if (this.length + array.length > this.data.length) {
  4380. this.data.length = (this.length + array.length) * 2;
  4381. }
  4382. for (var index = 0; index < array.length; index++) {
  4383. var item = (array.data || array)[index];
  4384. this.pushNoDuplicate(item);
  4385. }
  4386. };
  4387. SmartArray.prototype.indexOf = function (value) {
  4388. var position = this.data.indexOf(value);
  4389. if (position >= this.length) {
  4390. return -1;
  4391. }
  4392. return position;
  4393. };
  4394. // Statics
  4395. SmartArray._GlobalId = 0;
  4396. return SmartArray;
  4397. })();
  4398. BABYLON.SmartArray = SmartArray;
  4399. })(BABYLON || (BABYLON = {}));
  4400. var BABYLON;
  4401. (function (BABYLON) {
  4402. /**
  4403. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4404. * The underlying implementation relies on an associative array to ensure the best performances.
  4405. * The value can be anything including 'null' but except 'undefined'
  4406. */
  4407. var StringDictionary = (function () {
  4408. function StringDictionary() {
  4409. this._count = 0;
  4410. this._data = {};
  4411. }
  4412. /**
  4413. * Get a value based from its key
  4414. * @param key the given key to get the matching value from
  4415. * @return the value if found, otherwise undefined is returned
  4416. */
  4417. StringDictionary.prototype.get = function (key) {
  4418. var val = this._data[key];
  4419. if (val !== undefined) {
  4420. return val;
  4421. }
  4422. return undefined;
  4423. };
  4424. /**
  4425. * Get a value from its key or add it if it doesn't exist.
  4426. * This method will ensure you that a given key/data will be present in the dictionary.
  4427. * @param key the given key to get the matching value from
  4428. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4429. * The factory will only be invoked if there's no data for the given key.
  4430. * @return the value corresponding to the key.
  4431. */
  4432. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4433. var val = this.get(key);
  4434. if (val !== undefined) {
  4435. return val;
  4436. }
  4437. val = factory(key);
  4438. if (val) {
  4439. this.add(key, val);
  4440. }
  4441. return val;
  4442. };
  4443. /**
  4444. * Get a value from its key if present in the dictionary otherwise add it
  4445. * @param key the key to get the value from
  4446. * @param val if there's no such key/value pair in the dictionary add it with this value
  4447. * @return the value corresponding to the key
  4448. */
  4449. StringDictionary.prototype.getOrAdd = function (key, val) {
  4450. var curVal = this.get(key);
  4451. if (curVal !== undefined) {
  4452. return curVal;
  4453. }
  4454. this.add(key, val);
  4455. return val;
  4456. };
  4457. /**
  4458. * Check if there's a given key in the dictionary
  4459. * @param key the key to check for
  4460. * @return true if the key is present, false otherwise
  4461. */
  4462. StringDictionary.prototype.contains = function (key) {
  4463. return this._data[key] !== undefined;
  4464. };
  4465. /**
  4466. * Add a new key and its corresponding value
  4467. * @param key the key to add
  4468. * @param value the value corresponding to the key
  4469. * @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
  4470. */
  4471. StringDictionary.prototype.add = function (key, value) {
  4472. if (this._data[key] !== undefined) {
  4473. return false;
  4474. }
  4475. this._data[key] = value;
  4476. ++this._count;
  4477. return true;
  4478. };
  4479. StringDictionary.prototype.set = function (key, value) {
  4480. if (this._data[key] === undefined) {
  4481. return false;
  4482. }
  4483. this._data[key] = value;
  4484. return true;
  4485. };
  4486. /**
  4487. * Remove a key/value from the dictionary.
  4488. * @param key the key to remove
  4489. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4490. */
  4491. StringDictionary.prototype.remove = function (key) {
  4492. if (this.contains(key)) {
  4493. delete this._data[key];
  4494. --this._count;
  4495. return true;
  4496. }
  4497. return false;
  4498. };
  4499. /**
  4500. * Clear the whole content of the dictionary
  4501. */
  4502. StringDictionary.prototype.clear = function () {
  4503. this._data = {};
  4504. this._count = 0;
  4505. };
  4506. Object.defineProperty(StringDictionary.prototype, "count", {
  4507. get: function () {
  4508. return this._count;
  4509. },
  4510. enumerable: true,
  4511. configurable: true
  4512. });
  4513. /**
  4514. * Execute a callback on each key/val of the dictionary.
  4515. * Note that you can remove any element in this dictionary in the callback implementation
  4516. * @param callback the callback to execute on a given key/value pair
  4517. */
  4518. StringDictionary.prototype.forEach = function (callback) {
  4519. for (var cur in this._data) {
  4520. var val = this._data[cur];
  4521. callback(cur, val);
  4522. }
  4523. };
  4524. /**
  4525. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4526. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4527. * Note that you can remove any element in this dictionary in the callback implementation
  4528. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4529. */
  4530. StringDictionary.prototype.first = function (callback) {
  4531. for (var cur in this._data) {
  4532. var val = this._data[cur];
  4533. var res = callback(cur, val);
  4534. if (res) {
  4535. return res;
  4536. }
  4537. }
  4538. return null;
  4539. };
  4540. return StringDictionary;
  4541. })();
  4542. BABYLON.StringDictionary = StringDictionary;
  4543. })(BABYLON || (BABYLON = {}));
  4544. var BABYLON;
  4545. (function (BABYLON) {
  4546. // Screenshots
  4547. var screenshotCanvas;
  4548. var cloneValue = function (source, destinationObject) {
  4549. if (!source)
  4550. return null;
  4551. if (source instanceof BABYLON.Mesh) {
  4552. return null;
  4553. }
  4554. if (source instanceof BABYLON.SubMesh) {
  4555. return source.clone(destinationObject);
  4556. }
  4557. else if (source.clone) {
  4558. return source.clone();
  4559. }
  4560. return null;
  4561. };
  4562. var Tools = (function () {
  4563. function Tools() {
  4564. }
  4565. Tools.Instantiate = function (className) {
  4566. var arr = className.split(".");
  4567. var fn = (window || this);
  4568. for (var i = 0, len = arr.length; i < len; i++) {
  4569. fn = fn[arr[i]];
  4570. }
  4571. if (typeof fn !== "function") {
  4572. return null;
  4573. }
  4574. return fn;
  4575. };
  4576. Tools.SetImmediate = function (action) {
  4577. if (window.setImmediate) {
  4578. window.setImmediate(action);
  4579. }
  4580. else {
  4581. setTimeout(action, 1);
  4582. }
  4583. };
  4584. Tools.IsExponentOfTwo = function (value) {
  4585. var count = 1;
  4586. do {
  4587. count *= 2;
  4588. } while (count < value);
  4589. return count === value;
  4590. };
  4591. Tools.GetExponentOfTwo = function (value, max) {
  4592. var count = 1;
  4593. do {
  4594. count *= 2;
  4595. } while (count < value);
  4596. if (count > max)
  4597. count = max;
  4598. return count;
  4599. };
  4600. Tools.GetFilename = function (path) {
  4601. var index = path.lastIndexOf("/");
  4602. if (index < 0)
  4603. return path;
  4604. return path.substring(index + 1);
  4605. };
  4606. Tools.GetDOMTextContent = function (element) {
  4607. var result = "";
  4608. var child = element.firstChild;
  4609. while (child) {
  4610. if (child.nodeType === 3) {
  4611. result += child.textContent;
  4612. }
  4613. child = child.nextSibling;
  4614. }
  4615. return result;
  4616. };
  4617. Tools.ToDegrees = function (angle) {
  4618. return angle * 180 / Math.PI;
  4619. };
  4620. Tools.ToRadians = function (angle) {
  4621. return angle * Math.PI / 180;
  4622. };
  4623. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4624. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4625. var output = "";
  4626. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4627. var i = 0;
  4628. var bytes = new Uint8Array(buffer);
  4629. while (i < bytes.length) {
  4630. chr1 = bytes[i++];
  4631. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4632. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4633. enc1 = chr1 >> 2;
  4634. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4635. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4636. enc4 = chr3 & 63;
  4637. if (isNaN(chr2)) {
  4638. enc3 = enc4 = 64;
  4639. }
  4640. else if (isNaN(chr3)) {
  4641. enc4 = 64;
  4642. }
  4643. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4644. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4645. }
  4646. return "data:image/png;base64," + output;
  4647. };
  4648. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4649. if (bias === void 0) { bias = null; }
  4650. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4651. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4652. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4653. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4654. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4655. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4656. }
  4657. if (bias) {
  4658. minimum.x -= minimum.x * bias.x + bias.y;
  4659. minimum.y -= minimum.y * bias.x + bias.y;
  4660. minimum.z -= minimum.z * bias.x + bias.y;
  4661. maximum.x += maximum.x * bias.x + bias.y;
  4662. maximum.y += maximum.y * bias.x + bias.y;
  4663. maximum.z += maximum.z * bias.x + bias.y;
  4664. }
  4665. return {
  4666. minimum: minimum,
  4667. maximum: maximum
  4668. };
  4669. };
  4670. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4671. if (bias === void 0) { bias = null; }
  4672. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4673. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4674. if (!stride) {
  4675. stride = 3;
  4676. }
  4677. for (var index = start; index < start + count; index++) {
  4678. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4679. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4680. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4681. }
  4682. if (bias) {
  4683. minimum.x -= minimum.x * bias.x + bias.y;
  4684. minimum.y -= minimum.y * bias.x + bias.y;
  4685. minimum.z -= minimum.z * bias.x + bias.y;
  4686. maximum.x += maximum.x * bias.x + bias.y;
  4687. maximum.y += maximum.y * bias.x + bias.y;
  4688. maximum.z += maximum.z * bias.x + bias.y;
  4689. }
  4690. return {
  4691. minimum: minimum,
  4692. maximum: maximum
  4693. };
  4694. };
  4695. Tools.Vector2ArrayFeeder = function (array) {
  4696. return function (index) {
  4697. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4698. var length = isFloatArray ? array.length / 2 : array.length;
  4699. if (index >= length) {
  4700. return null;
  4701. }
  4702. if (isFloatArray) {
  4703. var fa = array;
  4704. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4705. }
  4706. var a = array;
  4707. return a[index];
  4708. };
  4709. };
  4710. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4711. if (bias === void 0) { bias = null; }
  4712. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4713. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4714. var i = 0;
  4715. var cur = feeder(i++);
  4716. while (cur) {
  4717. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4718. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4719. cur = feeder(i++);
  4720. }
  4721. if (bias) {
  4722. minimum.x -= minimum.x * bias.x + bias.y;
  4723. minimum.y -= minimum.y * bias.x + bias.y;
  4724. maximum.x += maximum.x * bias.x + bias.y;
  4725. maximum.y += maximum.y * bias.x + bias.y;
  4726. }
  4727. return {
  4728. minimum: minimum,
  4729. maximum: maximum
  4730. };
  4731. };
  4732. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4733. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4734. return undefined;
  4735. return Array.isArray(obj) ? obj : [obj];
  4736. };
  4737. // Misc.
  4738. Tools.GetPointerPrefix = function () {
  4739. var eventPrefix = "pointer";
  4740. // Check if pointer events are supported
  4741. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4742. eventPrefix = "mouse";
  4743. }
  4744. return eventPrefix;
  4745. };
  4746. /**
  4747. * @param func - the function to be called
  4748. * @param requester - the object that will request the next frame. Falls back to window.
  4749. */
  4750. Tools.QueueNewFrame = function (func, requester) {
  4751. if (requester === void 0) { requester = window; }
  4752. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  4753. /*if(requester.isPresenting) {
  4754. return;
  4755. } else*/ if (requester.requestAnimationFrame)
  4756. requester.requestAnimationFrame(func);
  4757. else if (requester.msRequestAnimationFrame)
  4758. requester.msRequestAnimationFrame(func);
  4759. else if (requester.webkitRequestAnimationFrame)
  4760. requester.webkitRequestAnimationFrame(func);
  4761. else if (requester.mozRequestAnimationFrame)
  4762. requester.mozRequestAnimationFrame(func);
  4763. else if (requester.oRequestAnimationFrame)
  4764. requester.oRequestAnimationFrame(func);
  4765. else {
  4766. window.setTimeout(func, 16);
  4767. }
  4768. };
  4769. Tools.RequestFullscreen = function (element) {
  4770. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4771. if (!requestFunction)
  4772. return;
  4773. requestFunction.call(element);
  4774. };
  4775. Tools.ExitFullscreen = function () {
  4776. if (document.exitFullscreen) {
  4777. document.exitFullscreen();
  4778. }
  4779. else if (document.mozCancelFullScreen) {
  4780. document.mozCancelFullScreen();
  4781. }
  4782. else if (document.webkitCancelFullScreen) {
  4783. document.webkitCancelFullScreen();
  4784. }
  4785. else if (document.msCancelFullScreen) {
  4786. document.msCancelFullScreen();
  4787. }
  4788. };
  4789. Tools.SetCorsBehavior = function (url, img) {
  4790. if (Tools.CorsBehavior) {
  4791. switch (typeof (Tools.CorsBehavior)) {
  4792. case "function":
  4793. var result = Tools.CorsBehavior(url);
  4794. if (result) {
  4795. return result;
  4796. }
  4797. break;
  4798. case "string":
  4799. default:
  4800. img.crossOrigin = Tools.CorsBehavior;
  4801. break;
  4802. }
  4803. }
  4804. };
  4805. // External files
  4806. Tools.CleanUrl = function (url) {
  4807. url = url.replace(/#/mg, "%23");
  4808. return url;
  4809. };
  4810. Tools.LoadImage = function (url, onload, onerror, database) {
  4811. if (url instanceof ArrayBuffer) {
  4812. url = Tools.EncodeArrayBufferTobase64(url);
  4813. }
  4814. url = Tools.CleanUrl(url);
  4815. var img = new Image();
  4816. if (url.substr(0, 5) !== "data:") {
  4817. Tools.SetCorsBehavior(url, img);
  4818. }
  4819. img.onload = function () {
  4820. onload(img);
  4821. };
  4822. img.onerror = function (err) {
  4823. Tools.Error("Error while trying to load texture: " + url);
  4824. if (Tools.UseFallbackTexture) {
  4825. 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";
  4826. onload(img);
  4827. }
  4828. else {
  4829. onerror();
  4830. }
  4831. };
  4832. var noIndexedDB = function () {
  4833. img.src = url;
  4834. };
  4835. var loadFromIndexedDB = function () {
  4836. database.loadImageFromDB(url, img);
  4837. };
  4838. //ANY database to do!
  4839. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4840. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4841. }
  4842. else {
  4843. if (url.indexOf("file:") === -1) {
  4844. noIndexedDB();
  4845. }
  4846. else {
  4847. try {
  4848. var textureName = url.substring(5).toLowerCase();
  4849. var blobURL;
  4850. try {
  4851. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4852. }
  4853. catch (ex) {
  4854. // Chrome doesn't support oneTimeOnly parameter
  4855. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4856. }
  4857. img.src = blobURL;
  4858. }
  4859. catch (e) {
  4860. img.src = null;
  4861. }
  4862. }
  4863. }
  4864. return img;
  4865. };
  4866. //ANY
  4867. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4868. url = Tools.CleanUrl(url);
  4869. var noIndexedDB = function () {
  4870. var request = new XMLHttpRequest();
  4871. var loadUrl = Tools.BaseUrl + url;
  4872. request.open('GET', loadUrl, true);
  4873. if (useArrayBuffer) {
  4874. request.responseType = "arraybuffer";
  4875. }
  4876. request.onprogress = progressCallBack;
  4877. request.onreadystatechange = function () {
  4878. if (request.readyState === 4) {
  4879. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  4880. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  4881. callback(!useArrayBuffer ? request.responseText : request.response);
  4882. }
  4883. else {
  4884. if (onError) {
  4885. onError();
  4886. }
  4887. else {
  4888. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4889. }
  4890. }
  4891. }
  4892. };
  4893. request.send(null);
  4894. };
  4895. var loadFromIndexedDB = function () {
  4896. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4897. };
  4898. if (url.indexOf("file:") !== -1) {
  4899. var fileName = url.substring(5).toLowerCase();
  4900. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4901. }
  4902. else {
  4903. // Caching all files
  4904. if (database && database.enableSceneOffline) {
  4905. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4906. }
  4907. else {
  4908. noIndexedDB();
  4909. }
  4910. }
  4911. };
  4912. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4913. var reader = new FileReader();
  4914. reader.onload = function (e) {
  4915. //target doesn't have result from ts 1.3
  4916. callback(e.target['result']);
  4917. };
  4918. reader.onprogress = progressCallback;
  4919. reader.readAsDataURL(fileToLoad);
  4920. };
  4921. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4922. var reader = new FileReader();
  4923. reader.onerror = function (e) {
  4924. Tools.Log("Error while reading file: " + fileToLoad.name);
  4925. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4926. };
  4927. reader.onload = function (e) {
  4928. //target doesn't have result from ts 1.3
  4929. callback(e.target['result']);
  4930. };
  4931. reader.onprogress = progressCallBack;
  4932. if (!useArrayBuffer) {
  4933. // Asynchronous read
  4934. reader.readAsText(fileToLoad);
  4935. }
  4936. else {
  4937. reader.readAsArrayBuffer(fileToLoad);
  4938. }
  4939. };
  4940. //returns a downloadable url to a file content.
  4941. Tools.FileAsURL = function (content) {
  4942. var fileBlob = new Blob([content]);
  4943. var url = window.URL || window.webkitURL;
  4944. var link = url.createObjectURL(fileBlob);
  4945. return link;
  4946. };
  4947. // Misc.
  4948. Tools.Format = function (value, decimals) {
  4949. if (decimals === void 0) { decimals = 2; }
  4950. return value.toFixed(decimals);
  4951. };
  4952. Tools.CheckExtends = function (v, min, max) {
  4953. if (v.x < min.x)
  4954. min.x = v.x;
  4955. if (v.y < min.y)
  4956. min.y = v.y;
  4957. if (v.z < min.z)
  4958. min.z = v.z;
  4959. if (v.x > max.x)
  4960. max.x = v.x;
  4961. if (v.y > max.y)
  4962. max.y = v.y;
  4963. if (v.z > max.z)
  4964. max.z = v.z;
  4965. };
  4966. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4967. for (var prop in source) {
  4968. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4969. continue;
  4970. }
  4971. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4972. continue;
  4973. }
  4974. var sourceValue = source[prop];
  4975. var typeOfSourceValue = typeof sourceValue;
  4976. if (typeOfSourceValue === "function") {
  4977. continue;
  4978. }
  4979. if (typeOfSourceValue === "object") {
  4980. if (sourceValue instanceof Array) {
  4981. destination[prop] = [];
  4982. if (sourceValue.length > 0) {
  4983. if (typeof sourceValue[0] == "object") {
  4984. for (var index = 0; index < sourceValue.length; index++) {
  4985. var clonedValue = cloneValue(sourceValue[index], destination);
  4986. if (destination[prop].indexOf(clonedValue) === -1) {
  4987. destination[prop].push(clonedValue);
  4988. }
  4989. }
  4990. }
  4991. else {
  4992. destination[prop] = sourceValue.slice(0);
  4993. }
  4994. }
  4995. }
  4996. else {
  4997. destination[prop] = cloneValue(sourceValue, destination);
  4998. }
  4999. }
  5000. else {
  5001. destination[prop] = sourceValue;
  5002. }
  5003. }
  5004. };
  5005. Tools.IsEmpty = function (obj) {
  5006. for (var i in obj) {
  5007. return false;
  5008. }
  5009. return true;
  5010. };
  5011. Tools.RegisterTopRootEvents = function (events) {
  5012. for (var index = 0; index < events.length; index++) {
  5013. var event = events[index];
  5014. window.addEventListener(event.name, event.handler, false);
  5015. try {
  5016. if (window.parent) {
  5017. window.parent.addEventListener(event.name, event.handler, false);
  5018. }
  5019. }
  5020. catch (e) {
  5021. }
  5022. }
  5023. };
  5024. Tools.UnregisterTopRootEvents = function (events) {
  5025. for (var index = 0; index < events.length; index++) {
  5026. var event = events[index];
  5027. window.removeEventListener(event.name, event.handler);
  5028. try {
  5029. if (window.parent) {
  5030. window.parent.removeEventListener(event.name, event.handler);
  5031. }
  5032. }
  5033. catch (e) {
  5034. }
  5035. }
  5036. };
  5037. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5038. if (mimeType === void 0) { mimeType = "image/png"; }
  5039. // Read the contents of the framebuffer
  5040. var numberOfChannelsByLine = width * 4;
  5041. var halfHeight = height / 2;
  5042. //Reading datas from WebGL
  5043. var data = engine.readPixels(0, 0, width, height);
  5044. //To flip image on Y axis.
  5045. for (var i = 0; i < halfHeight; i++) {
  5046. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5047. var currentCell = j + i * numberOfChannelsByLine;
  5048. var targetLine = height - i - 1;
  5049. var targetCell = j + targetLine * numberOfChannelsByLine;
  5050. var temp = data[currentCell];
  5051. data[currentCell] = data[targetCell];
  5052. data[targetCell] = temp;
  5053. }
  5054. }
  5055. // Create a 2D canvas to store the result
  5056. if (!screenshotCanvas) {
  5057. screenshotCanvas = document.createElement('canvas');
  5058. }
  5059. screenshotCanvas.width = width;
  5060. screenshotCanvas.height = height;
  5061. var context = screenshotCanvas.getContext('2d');
  5062. // Copy the pixels to a 2D canvas
  5063. var imageData = context.createImageData(width, height);
  5064. var castData = (imageData.data);
  5065. castData.set(data);
  5066. context.putImageData(imageData, 0, 0);
  5067. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5068. };
  5069. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5070. if (mimeType === void 0) { mimeType = "image/png"; }
  5071. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5072. if (successCallback) {
  5073. successCallback(base64Image);
  5074. }
  5075. else {
  5076. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5077. if (("download" in document.createElement("a"))) {
  5078. var a = window.document.createElement("a");
  5079. a.href = base64Image;
  5080. var date = new Date();
  5081. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5082. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5083. window.document.body.appendChild(a);
  5084. a.addEventListener("click", function () {
  5085. a.parentElement.removeChild(a);
  5086. });
  5087. a.click();
  5088. }
  5089. else {
  5090. var newWindow = window.open("");
  5091. var img = newWindow.document.createElement("img");
  5092. img.src = base64Image;
  5093. newWindow.document.body.appendChild(img);
  5094. }
  5095. }
  5096. };
  5097. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5098. if (mimeType === void 0) { mimeType = "image/png"; }
  5099. var width;
  5100. var height;
  5101. // If a precision value is specified
  5102. if (size.precision) {
  5103. width = Math.round(engine.getRenderWidth() * size.precision);
  5104. height = Math.round(width / engine.getAspectRatio(camera));
  5105. }
  5106. else if (size.width && size.height) {
  5107. width = size.width;
  5108. height = size.height;
  5109. }
  5110. else if (size.width && !size.height) {
  5111. width = size.width;
  5112. height = Math.round(width / engine.getAspectRatio(camera));
  5113. }
  5114. else if (size.height && !size.width) {
  5115. height = size.height;
  5116. width = Math.round(height * engine.getAspectRatio(camera));
  5117. }
  5118. else if (!isNaN(size)) {
  5119. height = size;
  5120. width = size;
  5121. }
  5122. else {
  5123. Tools.Error("Invalid 'size' parameter !");
  5124. return;
  5125. }
  5126. if (!screenshotCanvas) {
  5127. screenshotCanvas = document.createElement('canvas');
  5128. }
  5129. screenshotCanvas.width = width;
  5130. screenshotCanvas.height = height;
  5131. var renderContext = screenshotCanvas.getContext("2d");
  5132. renderContext.drawImage(engine.getRenderingCanvas(), 0, 0, width, height);
  5133. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5134. };
  5135. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType) {
  5136. if (mimeType === void 0) { mimeType = "image/png"; }
  5137. var width;
  5138. var height;
  5139. //If a precision value is specified
  5140. if (size.precision) {
  5141. width = Math.round(engine.getRenderWidth() * size.precision);
  5142. height = Math.round(width / engine.getAspectRatio(camera));
  5143. size = { width: width, height: height };
  5144. }
  5145. else if (size.width && size.height) {
  5146. width = size.width;
  5147. height = size.height;
  5148. }
  5149. else if (size.width && !size.height) {
  5150. width = size.width;
  5151. height = Math.round(width / engine.getAspectRatio(camera));
  5152. size = { width: width, height: height };
  5153. }
  5154. else if (size.height && !size.width) {
  5155. height = size.height;
  5156. width = Math.round(height * engine.getAspectRatio(camera));
  5157. size = { width: width, height: height };
  5158. }
  5159. else if (!isNaN(size)) {
  5160. height = size;
  5161. width = size;
  5162. }
  5163. else {
  5164. Tools.Error("Invalid 'size' parameter !");
  5165. return;
  5166. }
  5167. var scene = camera.getScene();
  5168. var previousCamera = null;
  5169. if (scene.activeCamera !== camera) {
  5170. previousCamera = scene.activeCamera;
  5171. scene.activeCamera = camera;
  5172. }
  5173. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5174. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  5175. texture.renderList = scene.meshes;
  5176. texture.onAfterRenderObservable.add(function () {
  5177. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5178. });
  5179. scene.incrementRenderId();
  5180. scene.resetCachedMaterial();
  5181. texture.render(true);
  5182. texture.dispose();
  5183. if (previousCamera) {
  5184. scene.activeCamera = previousCamera;
  5185. }
  5186. camera.getProjectionMatrix(true); // Force cache refresh;
  5187. };
  5188. // XHR response validator for local file scenario
  5189. Tools.ValidateXHRData = function (xhr, dataType) {
  5190. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5191. if (dataType === void 0) { dataType = 7; }
  5192. try {
  5193. if (dataType & 1) {
  5194. if (xhr.responseText && xhr.responseText.length > 0) {
  5195. return true;
  5196. }
  5197. else if (dataType === 1) {
  5198. return false;
  5199. }
  5200. }
  5201. if (dataType & 2) {
  5202. // Check header width and height since there is no "TGA" magic number
  5203. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5204. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5205. return true;
  5206. }
  5207. else if (dataType === 2) {
  5208. return false;
  5209. }
  5210. }
  5211. if (dataType & 4) {
  5212. // Check for the "DDS" magic number
  5213. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5214. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5215. return true;
  5216. }
  5217. else {
  5218. return false;
  5219. }
  5220. }
  5221. }
  5222. catch (e) {
  5223. }
  5224. return false;
  5225. };
  5226. /**
  5227. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5228. * Be aware Math.random() could cause collisions, but:
  5229. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  5230. */
  5231. Tools.RandomId = function () {
  5232. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5233. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5234. return v.toString(16);
  5235. });
  5236. };
  5237. Object.defineProperty(Tools, "NoneLogLevel", {
  5238. get: function () {
  5239. return Tools._NoneLogLevel;
  5240. },
  5241. enumerable: true,
  5242. configurable: true
  5243. });
  5244. Object.defineProperty(Tools, "MessageLogLevel", {
  5245. get: function () {
  5246. return Tools._MessageLogLevel;
  5247. },
  5248. enumerable: true,
  5249. configurable: true
  5250. });
  5251. Object.defineProperty(Tools, "WarningLogLevel", {
  5252. get: function () {
  5253. return Tools._WarningLogLevel;
  5254. },
  5255. enumerable: true,
  5256. configurable: true
  5257. });
  5258. Object.defineProperty(Tools, "ErrorLogLevel", {
  5259. get: function () {
  5260. return Tools._ErrorLogLevel;
  5261. },
  5262. enumerable: true,
  5263. configurable: true
  5264. });
  5265. Object.defineProperty(Tools, "AllLogLevel", {
  5266. get: function () {
  5267. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5268. },
  5269. enumerable: true,
  5270. configurable: true
  5271. });
  5272. Tools._AddLogEntry = function (entry) {
  5273. Tools._LogCache = entry + Tools._LogCache;
  5274. if (Tools.OnNewCacheEntry) {
  5275. Tools.OnNewCacheEntry(entry);
  5276. }
  5277. };
  5278. Tools._FormatMessage = function (message) {
  5279. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5280. var date = new Date();
  5281. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5282. };
  5283. Tools._LogDisabled = function (message) {
  5284. // nothing to do
  5285. };
  5286. Tools._LogEnabled = function (message) {
  5287. var formattedMessage = Tools._FormatMessage(message);
  5288. console.log("BJS - " + formattedMessage);
  5289. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5290. Tools._AddLogEntry(entry);
  5291. };
  5292. Tools._WarnDisabled = function (message) {
  5293. // nothing to do
  5294. };
  5295. Tools._WarnEnabled = function (message) {
  5296. var formattedMessage = Tools._FormatMessage(message);
  5297. console.warn("BJS - " + formattedMessage);
  5298. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5299. Tools._AddLogEntry(entry);
  5300. };
  5301. Tools._ErrorDisabled = function (message) {
  5302. // nothing to do
  5303. };
  5304. Tools._ErrorEnabled = function (message) {
  5305. Tools.errorsCount++;
  5306. var formattedMessage = Tools._FormatMessage(message);
  5307. console.error("BJS - " + formattedMessage);
  5308. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5309. Tools._AddLogEntry(entry);
  5310. };
  5311. Object.defineProperty(Tools, "LogCache", {
  5312. get: function () {
  5313. return Tools._LogCache;
  5314. },
  5315. enumerable: true,
  5316. configurable: true
  5317. });
  5318. Tools.ClearLogCache = function () {
  5319. Tools._LogCache = "";
  5320. Tools.errorsCount = 0;
  5321. };
  5322. Object.defineProperty(Tools, "LogLevels", {
  5323. set: function (level) {
  5324. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5325. Tools.Log = Tools._LogEnabled;
  5326. }
  5327. else {
  5328. Tools.Log = Tools._LogDisabled;
  5329. }
  5330. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5331. Tools.Warn = Tools._WarnEnabled;
  5332. }
  5333. else {
  5334. Tools.Warn = Tools._WarnDisabled;
  5335. }
  5336. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5337. Tools.Error = Tools._ErrorEnabled;
  5338. }
  5339. else {
  5340. Tools.Error = Tools._ErrorDisabled;
  5341. }
  5342. },
  5343. enumerable: true,
  5344. configurable: true
  5345. });
  5346. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5347. get: function () {
  5348. return Tools._PerformanceNoneLogLevel;
  5349. },
  5350. enumerable: true,
  5351. configurable: true
  5352. });
  5353. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5354. get: function () {
  5355. return Tools._PerformanceUserMarkLogLevel;
  5356. },
  5357. enumerable: true,
  5358. configurable: true
  5359. });
  5360. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5361. get: function () {
  5362. return Tools._PerformanceConsoleLogLevel;
  5363. },
  5364. enumerable: true,
  5365. configurable: true
  5366. });
  5367. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5368. set: function (level) {
  5369. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5370. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5371. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5372. return;
  5373. }
  5374. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5375. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5376. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5377. return;
  5378. }
  5379. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5380. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5381. },
  5382. enumerable: true,
  5383. configurable: true
  5384. });
  5385. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5386. };
  5387. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5388. };
  5389. Tools._StartUserMark = function (counterName, condition) {
  5390. if (condition === void 0) { condition = true; }
  5391. if (!condition || !Tools._performance.mark) {
  5392. return;
  5393. }
  5394. Tools._performance.mark(counterName + "-Begin");
  5395. };
  5396. Tools._EndUserMark = function (counterName, condition) {
  5397. if (condition === void 0) { condition = true; }
  5398. if (!condition || !Tools._performance.mark) {
  5399. return;
  5400. }
  5401. Tools._performance.mark(counterName + "-End");
  5402. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5403. };
  5404. Tools._StartPerformanceConsole = function (counterName, condition) {
  5405. if (condition === void 0) { condition = true; }
  5406. if (!condition) {
  5407. return;
  5408. }
  5409. Tools._StartUserMark(counterName, condition);
  5410. if (console.time) {
  5411. console.time(counterName);
  5412. }
  5413. };
  5414. Tools._EndPerformanceConsole = function (counterName, condition) {
  5415. if (condition === void 0) { condition = true; }
  5416. if (!condition) {
  5417. return;
  5418. }
  5419. Tools._EndUserMark(counterName, condition);
  5420. if (console.time) {
  5421. console.timeEnd(counterName);
  5422. }
  5423. };
  5424. Object.defineProperty(Tools, "Now", {
  5425. get: function () {
  5426. if (window.performance && window.performance.now) {
  5427. return window.performance.now();
  5428. }
  5429. return new Date().getTime();
  5430. },
  5431. enumerable: true,
  5432. configurable: true
  5433. });
  5434. /**
  5435. * This method will return the name of the class used to create the instance of the given object.
  5436. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5437. * @param object the object to get the class name from
  5438. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5439. */
  5440. Tools.getClassName = function (object, isType) {
  5441. if (isType === void 0) { isType = false; }
  5442. var name = null;
  5443. if (!isType && object.getClassName) {
  5444. name = object.getClassName();
  5445. }
  5446. else {
  5447. if (object instanceof Object) {
  5448. var classObj = isType ? object : Object.getPrototypeOf(object);
  5449. name = classObj.constructor["__bjsclassName__"];
  5450. }
  5451. if (!name) {
  5452. name = typeof object;
  5453. }
  5454. }
  5455. return name;
  5456. };
  5457. Tools.first = function (array, predicate) {
  5458. for (var _i = 0; _i < array.length; _i++) {
  5459. var el = array[_i];
  5460. if (predicate(el)) {
  5461. return el;
  5462. }
  5463. }
  5464. };
  5465. /**
  5466. * 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.
  5467. * @param array
  5468. */
  5469. Tools.arrayOrStringFeeder = function (array) {
  5470. return function (index) {
  5471. if (index >= array.length) {
  5472. return null;
  5473. }
  5474. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5475. if (val && val.getHashCode) {
  5476. val = val.getHashCode();
  5477. }
  5478. if (typeof val === "string") {
  5479. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5480. }
  5481. return val;
  5482. };
  5483. };
  5484. /**
  5485. * Compute the hashCode of a stream of number
  5486. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5487. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5488. * @return the hash code computed
  5489. */
  5490. Tools.hashCodeFromStream = function (feeder) {
  5491. // Based from here: http://stackoverflow.com/a/7616484/802124
  5492. var hash = 0;
  5493. var index = 0;
  5494. var chr = feeder(index++);
  5495. while (chr != null) {
  5496. hash = ((hash << 5) - hash) + chr;
  5497. hash |= 0; // Convert to 32bit integer
  5498. chr = feeder(index++);
  5499. }
  5500. return hash;
  5501. };
  5502. Tools.BaseUrl = "";
  5503. Tools.CorsBehavior = "anonymous";
  5504. Tools.UseFallbackTexture = true;
  5505. // Logs
  5506. Tools._NoneLogLevel = 0;
  5507. Tools._MessageLogLevel = 1;
  5508. Tools._WarningLogLevel = 2;
  5509. Tools._ErrorLogLevel = 4;
  5510. Tools._LogCache = "";
  5511. Tools.errorsCount = 0;
  5512. Tools.Log = Tools._LogEnabled;
  5513. Tools.Warn = Tools._WarnEnabled;
  5514. Tools.Error = Tools._ErrorEnabled;
  5515. // Performances
  5516. Tools._PerformanceNoneLogLevel = 0;
  5517. Tools._PerformanceUserMarkLogLevel = 1;
  5518. Tools._PerformanceConsoleLogLevel = 2;
  5519. Tools._performance = window.performance;
  5520. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5521. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5522. return Tools;
  5523. })();
  5524. BABYLON.Tools = Tools;
  5525. /**
  5526. * This class is used to track a performance counter which is number based.
  5527. * The user has access to many properties which give statistics of different nature
  5528. *
  5529. * The implementer can track two kinds of Performance Counter: time and count
  5530. * 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.
  5531. * 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.
  5532. */
  5533. var PerfCounter = (function () {
  5534. function PerfCounter() {
  5535. this._startMonitoringTime = 0;
  5536. this._min = 0;
  5537. this._max = 0;
  5538. this._average = 0;
  5539. this._lastSecAverage = 0;
  5540. this._current = 0;
  5541. this._totalValueCount = 0;
  5542. this._totalAccumulated = 0;
  5543. this._lastSecAccumulated = 0;
  5544. this._lastSecTime = 0;
  5545. this._lastSecValueCount = 0;
  5546. }
  5547. Object.defineProperty(PerfCounter.prototype, "min", {
  5548. /**
  5549. * Returns the smallest value ever
  5550. */
  5551. get: function () {
  5552. return this._min;
  5553. },
  5554. enumerable: true,
  5555. configurable: true
  5556. });
  5557. Object.defineProperty(PerfCounter.prototype, "max", {
  5558. /**
  5559. * Returns the biggest value ever
  5560. */
  5561. get: function () {
  5562. return this._max;
  5563. },
  5564. enumerable: true,
  5565. configurable: true
  5566. });
  5567. Object.defineProperty(PerfCounter.prototype, "average", {
  5568. /**
  5569. * Returns the average value since the performance counter is running
  5570. */
  5571. get: function () {
  5572. return this._average;
  5573. },
  5574. enumerable: true,
  5575. configurable: true
  5576. });
  5577. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5578. /**
  5579. * Returns the average value of the last second the counter was monitored
  5580. */
  5581. get: function () {
  5582. return this._lastSecAverage;
  5583. },
  5584. enumerable: true,
  5585. configurable: true
  5586. });
  5587. Object.defineProperty(PerfCounter.prototype, "current", {
  5588. /**
  5589. * Returns the current value
  5590. */
  5591. get: function () {
  5592. return this._current;
  5593. },
  5594. enumerable: true,
  5595. configurable: true
  5596. });
  5597. Object.defineProperty(PerfCounter.prototype, "total", {
  5598. get: function () {
  5599. return this._totalAccumulated;
  5600. },
  5601. enumerable: true,
  5602. configurable: true
  5603. });
  5604. /**
  5605. * Call this method to start monitoring a new frame.
  5606. * 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.
  5607. */
  5608. PerfCounter.prototype.fetchNewFrame = function () {
  5609. this._totalValueCount++;
  5610. this._current = 0;
  5611. this._lastSecValueCount++;
  5612. };
  5613. /**
  5614. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5615. * @param newCount the count value to add to the monitored count
  5616. * @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.
  5617. */
  5618. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5619. this._current += newCount;
  5620. if (fetchResult) {
  5621. this._fetchResult();
  5622. }
  5623. };
  5624. /**
  5625. * Start monitoring this performance counter
  5626. */
  5627. PerfCounter.prototype.beginMonitoring = function () {
  5628. this._startMonitoringTime = Tools.Now;
  5629. };
  5630. /**
  5631. * Compute the time lapsed since the previous beginMonitoring() call.
  5632. * @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
  5633. */
  5634. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5635. if (newFrame === void 0) { newFrame = true; }
  5636. if (newFrame) {
  5637. this.fetchNewFrame();
  5638. }
  5639. var currentTime = Tools.Now;
  5640. this._current = currentTime - this._startMonitoringTime;
  5641. if (newFrame) {
  5642. this._fetchResult();
  5643. }
  5644. };
  5645. PerfCounter.prototype._fetchResult = function () {
  5646. this._totalAccumulated += this._current;
  5647. this._lastSecAccumulated += this._current;
  5648. // Min/Max update
  5649. this._min = Math.min(this._min, this._current);
  5650. this._max = Math.max(this._max, this._current);
  5651. this._average = this._totalAccumulated / this._totalValueCount;
  5652. // Reset last sec?
  5653. var now = Tools.Now;
  5654. if ((now - this._lastSecTime) > 1000) {
  5655. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5656. this._lastSecTime = now;
  5657. this._lastSecAccumulated = 0;
  5658. this._lastSecValueCount = 0;
  5659. }
  5660. };
  5661. return PerfCounter;
  5662. })();
  5663. BABYLON.PerfCounter = PerfCounter;
  5664. /**
  5665. * Use this className as a decorator on a given class definition to add it a name.
  5666. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5667. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5668. * @param name
  5669. */
  5670. function className(name) {
  5671. return function (target) {
  5672. target["__bjsclassName__"] = name;
  5673. };
  5674. }
  5675. BABYLON.className = className;
  5676. /**
  5677. * An implementation of a loop for asynchronous functions.
  5678. */
  5679. var AsyncLoop = (function () {
  5680. /**
  5681. * Constroctor.
  5682. * @param iterations the number of iterations.
  5683. * @param _fn the function to run each iteration
  5684. * @param _successCallback the callback that will be called upon succesful execution
  5685. * @param offset starting offset.
  5686. */
  5687. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5688. if (offset === void 0) { offset = 0; }
  5689. this.iterations = iterations;
  5690. this._fn = _fn;
  5691. this._successCallback = _successCallback;
  5692. this.index = offset - 1;
  5693. this._done = false;
  5694. }
  5695. /**
  5696. * Execute the next iteration. Must be called after the last iteration was finished.
  5697. */
  5698. AsyncLoop.prototype.executeNext = function () {
  5699. if (!this._done) {
  5700. if (this.index + 1 < this.iterations) {
  5701. ++this.index;
  5702. this._fn(this);
  5703. }
  5704. else {
  5705. this.breakLoop();
  5706. }
  5707. }
  5708. };
  5709. /**
  5710. * Break the loop and run the success callback.
  5711. */
  5712. AsyncLoop.prototype.breakLoop = function () {
  5713. this._done = true;
  5714. this._successCallback();
  5715. };
  5716. /**
  5717. * Helper function
  5718. */
  5719. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5720. if (offset === void 0) { offset = 0; }
  5721. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5722. loop.executeNext();
  5723. return loop;
  5724. };
  5725. /**
  5726. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5727. * @param iterations total number of iterations
  5728. * @param syncedIterations number of synchronous iterations in each async iteration.
  5729. * @param fn the function to call each iteration.
  5730. * @param callback a success call back that will be called when iterating stops.
  5731. * @param breakFunction a break condition (optional)
  5732. * @param timeout timeout settings for the setTimeout function. default - 0.
  5733. * @constructor
  5734. */
  5735. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5736. if (timeout === void 0) { timeout = 0; }
  5737. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5738. if (breakFunction && breakFunction())
  5739. loop.breakLoop();
  5740. else {
  5741. setTimeout(function () {
  5742. for (var i = 0; i < syncedIterations; ++i) {
  5743. var iteration = (loop.index * syncedIterations) + i;
  5744. if (iteration >= iterations)
  5745. break;
  5746. fn(iteration);
  5747. if (breakFunction && breakFunction()) {
  5748. loop.breakLoop();
  5749. break;
  5750. }
  5751. }
  5752. loop.executeNext();
  5753. }, timeout);
  5754. }
  5755. }, callback);
  5756. };
  5757. return AsyncLoop;
  5758. })();
  5759. BABYLON.AsyncLoop = AsyncLoop;
  5760. })(BABYLON || (BABYLON = {}));
  5761. var BABYLON;
  5762. (function (BABYLON) {
  5763. var Internals;
  5764. (function (Internals) {
  5765. var _AlphaState = (function () {
  5766. function _AlphaState() {
  5767. this._isAlphaBlendDirty = false;
  5768. this._isBlendFunctionParametersDirty = false;
  5769. this._alphaBlend = false;
  5770. this._blendFunctionParameters = new Array(4);
  5771. }
  5772. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5773. get: function () {
  5774. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5775. },
  5776. enumerable: true,
  5777. configurable: true
  5778. });
  5779. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5780. get: function () {
  5781. return this._alphaBlend;
  5782. },
  5783. set: function (value) {
  5784. if (this._alphaBlend === value) {
  5785. return;
  5786. }
  5787. this._alphaBlend = value;
  5788. this._isAlphaBlendDirty = true;
  5789. },
  5790. enumerable: true,
  5791. configurable: true
  5792. });
  5793. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5794. if (this._blendFunctionParameters[0] === value0 &&
  5795. this._blendFunctionParameters[1] === value1 &&
  5796. this._blendFunctionParameters[2] === value2 &&
  5797. this._blendFunctionParameters[3] === value3) {
  5798. return;
  5799. }
  5800. this._blendFunctionParameters[0] = value0;
  5801. this._blendFunctionParameters[1] = value1;
  5802. this._blendFunctionParameters[2] = value2;
  5803. this._blendFunctionParameters[3] = value3;
  5804. this._isBlendFunctionParametersDirty = true;
  5805. };
  5806. _AlphaState.prototype.reset = function () {
  5807. this._alphaBlend = false;
  5808. this._blendFunctionParameters[0] = null;
  5809. this._blendFunctionParameters[1] = null;
  5810. this._blendFunctionParameters[2] = null;
  5811. this._blendFunctionParameters[3] = null;
  5812. this._isAlphaBlendDirty = true;
  5813. this._isBlendFunctionParametersDirty = false;
  5814. };
  5815. _AlphaState.prototype.apply = function (gl) {
  5816. if (!this.isDirty) {
  5817. return;
  5818. }
  5819. // Alpha blend
  5820. if (this._isAlphaBlendDirty) {
  5821. if (this._alphaBlend) {
  5822. gl.enable(gl.BLEND);
  5823. }
  5824. else {
  5825. gl.disable(gl.BLEND);
  5826. }
  5827. this._isAlphaBlendDirty = false;
  5828. }
  5829. // Alpha function
  5830. if (this._isBlendFunctionParametersDirty) {
  5831. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5832. this._isBlendFunctionParametersDirty = false;
  5833. }
  5834. };
  5835. return _AlphaState;
  5836. })();
  5837. Internals._AlphaState = _AlphaState;
  5838. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5839. })(BABYLON || (BABYLON = {}));
  5840. var BABYLON;
  5841. (function (BABYLON) {
  5842. var Internals;
  5843. (function (Internals) {
  5844. var _DepthCullingState = (function () {
  5845. function _DepthCullingState() {
  5846. this._isDepthTestDirty = false;
  5847. this._isDepthMaskDirty = false;
  5848. this._isDepthFuncDirty = false;
  5849. this._isCullFaceDirty = false;
  5850. this._isCullDirty = false;
  5851. this._isZOffsetDirty = false;
  5852. }
  5853. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5854. get: function () {
  5855. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5856. },
  5857. enumerable: true,
  5858. configurable: true
  5859. });
  5860. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5861. get: function () {
  5862. return this._zOffset;
  5863. },
  5864. set: function (value) {
  5865. if (this._zOffset === value) {
  5866. return;
  5867. }
  5868. this._zOffset = value;
  5869. this._isZOffsetDirty = true;
  5870. },
  5871. enumerable: true,
  5872. configurable: true
  5873. });
  5874. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5875. get: function () {
  5876. return this._cullFace;
  5877. },
  5878. set: function (value) {
  5879. if (this._cullFace === value) {
  5880. return;
  5881. }
  5882. this._cullFace = value;
  5883. this._isCullFaceDirty = true;
  5884. },
  5885. enumerable: true,
  5886. configurable: true
  5887. });
  5888. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5889. get: function () {
  5890. return this._cull;
  5891. },
  5892. set: function (value) {
  5893. if (this._cull === value) {
  5894. return;
  5895. }
  5896. this._cull = value;
  5897. this._isCullDirty = true;
  5898. },
  5899. enumerable: true,
  5900. configurable: true
  5901. });
  5902. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5903. get: function () {
  5904. return this._depthFunc;
  5905. },
  5906. set: function (value) {
  5907. if (this._depthFunc === value) {
  5908. return;
  5909. }
  5910. this._depthFunc = value;
  5911. this._isDepthFuncDirty = true;
  5912. },
  5913. enumerable: true,
  5914. configurable: true
  5915. });
  5916. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5917. get: function () {
  5918. return this._depthMask;
  5919. },
  5920. set: function (value) {
  5921. if (this._depthMask === value) {
  5922. return;
  5923. }
  5924. this._depthMask = value;
  5925. this._isDepthMaskDirty = true;
  5926. },
  5927. enumerable: true,
  5928. configurable: true
  5929. });
  5930. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5931. get: function () {
  5932. return this._depthTest;
  5933. },
  5934. set: function (value) {
  5935. if (this._depthTest === value) {
  5936. return;
  5937. }
  5938. this._depthTest = value;
  5939. this._isDepthTestDirty = true;
  5940. },
  5941. enumerable: true,
  5942. configurable: true
  5943. });
  5944. _DepthCullingState.prototype.reset = function () {
  5945. this._depthMask = true;
  5946. this._depthTest = true;
  5947. this._depthFunc = null;
  5948. this._cullFace = null;
  5949. this._cull = null;
  5950. this._zOffset = 0;
  5951. this._isDepthTestDirty = true;
  5952. this._isDepthMaskDirty = true;
  5953. this._isDepthFuncDirty = false;
  5954. this._isCullFaceDirty = false;
  5955. this._isCullDirty = false;
  5956. this._isZOffsetDirty = false;
  5957. };
  5958. _DepthCullingState.prototype.apply = function (gl) {
  5959. if (!this.isDirty) {
  5960. return;
  5961. }
  5962. // Cull
  5963. if (this._isCullDirty) {
  5964. if (this.cull) {
  5965. gl.enable(gl.CULL_FACE);
  5966. }
  5967. else {
  5968. gl.disable(gl.CULL_FACE);
  5969. }
  5970. this._isCullDirty = false;
  5971. }
  5972. // Cull face
  5973. if (this._isCullFaceDirty) {
  5974. gl.cullFace(this.cullFace);
  5975. this._isCullFaceDirty = false;
  5976. }
  5977. // Depth mask
  5978. if (this._isDepthMaskDirty) {
  5979. gl.depthMask(this.depthMask);
  5980. this._isDepthMaskDirty = false;
  5981. }
  5982. // Depth test
  5983. if (this._isDepthTestDirty) {
  5984. if (this.depthTest) {
  5985. gl.enable(gl.DEPTH_TEST);
  5986. }
  5987. else {
  5988. gl.disable(gl.DEPTH_TEST);
  5989. }
  5990. this._isDepthTestDirty = false;
  5991. }
  5992. // Depth func
  5993. if (this._isDepthFuncDirty) {
  5994. gl.depthFunc(this.depthFunc);
  5995. this._isDepthFuncDirty = false;
  5996. }
  5997. // zOffset
  5998. if (this._isZOffsetDirty) {
  5999. if (this.zOffset) {
  6000. gl.enable(gl.POLYGON_OFFSET_FILL);
  6001. gl.polygonOffset(this.zOffset, 0);
  6002. }
  6003. else {
  6004. gl.disable(gl.POLYGON_OFFSET_FILL);
  6005. }
  6006. this._isZOffsetDirty = false;
  6007. }
  6008. };
  6009. return _DepthCullingState;
  6010. })();
  6011. Internals._DepthCullingState = _DepthCullingState;
  6012. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6013. })(BABYLON || (BABYLON = {}));
  6014. var BABYLON;
  6015. (function (BABYLON) {
  6016. var Internals;
  6017. (function (Internals) {
  6018. var _StencilState = (function () {
  6019. function _StencilState() {
  6020. this._isStencilTestDirty = false;
  6021. this._isStencilMaskDirty = false;
  6022. this._isStencilFuncDirty = false;
  6023. this._isStencilOpDirty = false;
  6024. this.reset();
  6025. }
  6026. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6027. get: function () {
  6028. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6029. },
  6030. enumerable: true,
  6031. configurable: true
  6032. });
  6033. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6034. get: function () {
  6035. return this._stencilFunc;
  6036. },
  6037. set: function (value) {
  6038. if (this._stencilFunc === value) {
  6039. return;
  6040. }
  6041. this._stencilFunc = value;
  6042. this._isStencilFuncDirty = true;
  6043. },
  6044. enumerable: true,
  6045. configurable: true
  6046. });
  6047. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6048. get: function () {
  6049. return this._stencilFuncRef;
  6050. },
  6051. set: function (value) {
  6052. if (this._stencilFuncRef === value) {
  6053. return;
  6054. }
  6055. this._stencilFuncRef = value;
  6056. this._isStencilFuncDirty = true;
  6057. },
  6058. enumerable: true,
  6059. configurable: true
  6060. });
  6061. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6062. get: function () {
  6063. return this._stencilFuncMask;
  6064. },
  6065. set: function (value) {
  6066. if (this._stencilFuncMask === value) {
  6067. return;
  6068. }
  6069. this._stencilFuncMask = value;
  6070. this._isStencilFuncDirty = true;
  6071. },
  6072. enumerable: true,
  6073. configurable: true
  6074. });
  6075. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6076. get: function () {
  6077. return this._stencilOpStencilFail;
  6078. },
  6079. set: function (value) {
  6080. if (this._stencilOpStencilFail === value) {
  6081. return;
  6082. }
  6083. this._stencilOpStencilFail = value;
  6084. this._isStencilOpDirty = true;
  6085. },
  6086. enumerable: true,
  6087. configurable: true
  6088. });
  6089. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6090. get: function () {
  6091. return this._stencilOpDepthFail;
  6092. },
  6093. set: function (value) {
  6094. if (this._stencilOpDepthFail === value) {
  6095. return;
  6096. }
  6097. this._stencilOpDepthFail = value;
  6098. this._isStencilOpDirty = true;
  6099. },
  6100. enumerable: true,
  6101. configurable: true
  6102. });
  6103. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6104. get: function () {
  6105. return this._stencilOpStencilDepthPass;
  6106. },
  6107. set: function (value) {
  6108. if (this._stencilOpStencilDepthPass === value) {
  6109. return;
  6110. }
  6111. this._stencilOpStencilDepthPass = value;
  6112. this._isStencilOpDirty = true;
  6113. },
  6114. enumerable: true,
  6115. configurable: true
  6116. });
  6117. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6118. get: function () {
  6119. return this._stencilMask;
  6120. },
  6121. set: function (value) {
  6122. if (this._stencilMask === value) {
  6123. return;
  6124. }
  6125. this._stencilMask = value;
  6126. this._isStencilMaskDirty = true;
  6127. },
  6128. enumerable: true,
  6129. configurable: true
  6130. });
  6131. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6132. get: function () {
  6133. return this._stencilTest;
  6134. },
  6135. set: function (value) {
  6136. if (this._stencilTest === value) {
  6137. return;
  6138. }
  6139. this._stencilTest = value;
  6140. this._isStencilTestDirty = true;
  6141. },
  6142. enumerable: true,
  6143. configurable: true
  6144. });
  6145. _StencilState.prototype.reset = function () {
  6146. this._stencilTest = false;
  6147. this._stencilMask = 0xFF;
  6148. this._stencilFunc = 0x0207; //WebGLRenderingContext.ALWAYS;
  6149. this._stencilFuncRef = 1;
  6150. this._stencilFuncMask = 0xFF;
  6151. this._stencilOpStencilFail = 0x1E00; //WebGLRenderingContext.KEEP;
  6152. this._stencilOpDepthFail = 0x1E00; //WebGLRenderingContext.KEEP;
  6153. this._stencilOpStencilDepthPass = 0x1E01; //WebGLRenderingContext.REPLACE;
  6154. this._isStencilTestDirty = true;
  6155. this._isStencilMaskDirty = true;
  6156. this._isStencilFuncDirty = true;
  6157. this._isStencilOpDirty = true;
  6158. };
  6159. _StencilState.prototype.apply = function (gl) {
  6160. if (!this.isDirty) {
  6161. return;
  6162. }
  6163. // Stencil test
  6164. if (this._isStencilTestDirty) {
  6165. if (this.stencilTest) {
  6166. gl.enable(gl.STENCIL_TEST);
  6167. }
  6168. else {
  6169. gl.disable(gl.STENCIL_TEST);
  6170. }
  6171. this._isStencilTestDirty = false;
  6172. }
  6173. // Stencil mask
  6174. if (this._isStencilMaskDirty) {
  6175. gl.stencilMask(this.stencilMask);
  6176. this._isStencilMaskDirty = false;
  6177. }
  6178. // Stencil func
  6179. if (this._isStencilFuncDirty) {
  6180. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6181. this._isStencilFuncDirty = false;
  6182. }
  6183. // Stencil op
  6184. if (this._isStencilOpDirty) {
  6185. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6186. this._isStencilOpDirty = false;
  6187. }
  6188. };
  6189. return _StencilState;
  6190. })();
  6191. Internals._StencilState = _StencilState;
  6192. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6193. })(BABYLON || (BABYLON = {}));
  6194. var BABYLON;
  6195. (function (BABYLON) {
  6196. var compileShader = function (gl, source, type, defines) {
  6197. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6198. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  6199. gl.compileShader(shader);
  6200. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6201. throw new Error(gl.getShaderInfoLog(shader));
  6202. }
  6203. return shader;
  6204. };
  6205. var HALF_FLOAT_OES = 0x8D61;
  6206. var getWebGLTextureType = function (gl, type) {
  6207. if (type === Engine.TEXTURETYPE_FLOAT) {
  6208. return gl.FLOAT;
  6209. }
  6210. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  6211. // Add Half Float Constant.
  6212. return HALF_FLOAT_OES;
  6213. }
  6214. return gl.UNSIGNED_BYTE;
  6215. };
  6216. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6217. var magFilter = gl.NEAREST;
  6218. var minFilter = gl.NEAREST;
  6219. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6220. magFilter = gl.LINEAR;
  6221. if (generateMipMaps) {
  6222. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6223. }
  6224. else {
  6225. minFilter = gl.LINEAR;
  6226. }
  6227. }
  6228. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6229. magFilter = gl.LINEAR;
  6230. if (generateMipMaps) {
  6231. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6232. }
  6233. else {
  6234. minFilter = gl.LINEAR;
  6235. }
  6236. }
  6237. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6238. magFilter = gl.NEAREST;
  6239. if (generateMipMaps) {
  6240. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6241. }
  6242. else {
  6243. minFilter = gl.NEAREST;
  6244. }
  6245. }
  6246. return {
  6247. min: minFilter,
  6248. mag: magFilter
  6249. };
  6250. };
  6251. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6252. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6253. var engine = scene.getEngine();
  6254. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6255. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6256. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6257. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6258. texture._baseWidth = width;
  6259. texture._baseHeight = height;
  6260. texture._width = potWidth;
  6261. texture._height = potHeight;
  6262. texture.isReady = true;
  6263. processFunction(potWidth, potHeight);
  6264. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6265. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6266. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6267. if (!noMipmap && !isCompressed) {
  6268. gl.generateMipmap(gl.TEXTURE_2D);
  6269. }
  6270. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6271. engine.resetTextureCache();
  6272. scene._removePendingData(texture);
  6273. texture.onLoadedCallbacks.forEach(function (callback) {
  6274. callback();
  6275. });
  6276. texture.onLoadedCallbacks = [];
  6277. };
  6278. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  6279. var img;
  6280. var onload = function () {
  6281. loadedImages[index] = img;
  6282. loadedImages._internalCount++;
  6283. scene._removePendingData(img);
  6284. if (loadedImages._internalCount === 6) {
  6285. onfinish(loadedImages);
  6286. }
  6287. };
  6288. var onerror = function () {
  6289. scene._removePendingData(img);
  6290. };
  6291. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6292. scene._addPendingData(img);
  6293. };
  6294. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  6295. var loadedImages = [];
  6296. loadedImages._internalCount = 0;
  6297. for (var index = 0; index < 6; index++) {
  6298. partialLoad(files[index], index, loadedImages, scene, onfinish);
  6299. }
  6300. };
  6301. var InstancingAttributeInfo = (function () {
  6302. function InstancingAttributeInfo() {
  6303. }
  6304. return InstancingAttributeInfo;
  6305. })();
  6306. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6307. var EngineCapabilities = (function () {
  6308. function EngineCapabilities() {
  6309. }
  6310. return EngineCapabilities;
  6311. })();
  6312. BABYLON.EngineCapabilities = EngineCapabilities;
  6313. /**
  6314. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6315. */
  6316. var Engine = (function () {
  6317. /**
  6318. * @constructor
  6319. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6320. * @param {boolean} [antialias] - enable antialias
  6321. * @param options - further options to be sent to the getContext function
  6322. */
  6323. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  6324. var _this = this;
  6325. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  6326. // Public members
  6327. this.isFullscreen = false;
  6328. this.isPointerLock = false;
  6329. this.cullBackFaces = true;
  6330. this.renderEvenInBackground = true;
  6331. // To enable/disable IDB support and avoid XHR on .manifest
  6332. this.enableOfflineSupport = true;
  6333. this.scenes = new Array();
  6334. this._windowIsBackground = false;
  6335. this._webGLVersion = "1.0";
  6336. this._drawCalls = new BABYLON.PerfCounter();
  6337. this._renderingQueueLaunched = false;
  6338. this._activeRenderLoops = [];
  6339. // FPS
  6340. this.fpsRange = 60;
  6341. this.previousFramesDuration = [];
  6342. this.fps = 60;
  6343. this.deltaTime = 0;
  6344. // States
  6345. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  6346. this._stencilState = new BABYLON.Internals._StencilState();
  6347. this._alphaState = new BABYLON.Internals._AlphaState();
  6348. this._alphaMode = Engine.ALPHA_DISABLE;
  6349. // Cache
  6350. this._loadedTexturesCache = new Array();
  6351. this._maxTextureChannels = 16;
  6352. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6353. this._compiledEffects = {};
  6354. this._vertexAttribArraysEnabled = [];
  6355. this._uintIndicesCurrentlySet = false;
  6356. this._currentBoundBuffer = new Array();
  6357. this._currentBufferPointers = [];
  6358. this._currentInstanceLocations = new Array();
  6359. this._currentInstanceBuffers = new Array();
  6360. this._onVRFullScreenTriggered = function () {
  6361. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  6362. //get the old size before we change
  6363. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  6364. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  6365. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  6366. //But actually, no browser follow the specs...
  6367. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  6368. //get the width and height, change the render size
  6369. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  6370. var width, height;
  6371. _this.setHardwareScalingLevel(1);
  6372. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  6373. }
  6374. else {
  6375. //When the specs are implemented, need to uncomment this.
  6376. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  6377. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  6378. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  6379. _this._vrDisplayEnabled = undefined;
  6380. }
  6381. };
  6382. this._renderingCanvas = canvas;
  6383. this._externalData = new BABYLON.StringDictionary();
  6384. options = options || {};
  6385. if (antialias != null) {
  6386. options.antialias = antialias;
  6387. }
  6388. if (options.preserveDrawingBuffer === undefined) {
  6389. options.preserveDrawingBuffer = false;
  6390. }
  6391. // Checks if some of the format renders first to allow the use of webgl inspector.
  6392. var renderToFullFloat = this._canRenderToFloatTexture();
  6393. var renderToHalfFloat = this._canRenderToHalfFloatTexture();
  6394. // GL
  6395. //try {
  6396. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6397. // if (this._gl) {
  6398. // this._webGLVersion = "2.0";
  6399. // }
  6400. //} catch (e) {
  6401. // // Do nothing
  6402. //}
  6403. if (!this._gl) {
  6404. try {
  6405. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6406. }
  6407. catch (e) {
  6408. throw new Error("WebGL not supported");
  6409. }
  6410. }
  6411. if (!this._gl) {
  6412. throw new Error("WebGL not supported");
  6413. }
  6414. this._onBlur = function () {
  6415. _this._windowIsBackground = true;
  6416. };
  6417. this._onFocus = function () {
  6418. _this._windowIsBackground = false;
  6419. };
  6420. window.addEventListener("blur", this._onBlur);
  6421. window.addEventListener("focus", this._onFocus);
  6422. // Viewport
  6423. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6424. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6425. this.resize();
  6426. // Caps
  6427. this._isStencilEnable = options.stencil;
  6428. this._caps = new EngineCapabilities();
  6429. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6430. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6431. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6432. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6433. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  6434. // Infos
  6435. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6436. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6437. if (rendererInfo != null) {
  6438. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6439. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6440. }
  6441. if (!this._glVendor) {
  6442. this._glVendor = "Unknown vendor";
  6443. }
  6444. if (!this._glRenderer) {
  6445. this._glRenderer = "Unknown renderer";
  6446. }
  6447. // Extensions
  6448. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  6449. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  6450. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  6451. 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');
  6452. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6453. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  6454. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  6455. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  6456. this._caps.highPrecisionShaderSupported = true;
  6457. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  6458. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  6459. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  6460. this._caps.textureFloatRender = renderToFullFloat;
  6461. this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
  6462. this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
  6463. this._caps.textureHalfFloatRender = renderToHalfFloat;
  6464. if (this._gl.getShaderPrecisionFormat) {
  6465. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6466. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6467. }
  6468. // Depth buffer
  6469. this.setDepthBuffer(true);
  6470. this.setDepthFunctionToLessOrEqual();
  6471. this.setDepthWrite(true);
  6472. // Fullscreen
  6473. this._onFullscreenChange = function () {
  6474. if (document.fullscreen !== undefined) {
  6475. _this.isFullscreen = document.fullscreen;
  6476. }
  6477. else if (document.mozFullScreen !== undefined) {
  6478. _this.isFullscreen = document.mozFullScreen;
  6479. }
  6480. else if (document.webkitIsFullScreen !== undefined) {
  6481. _this.isFullscreen = document.webkitIsFullScreen;
  6482. }
  6483. else if (document.msIsFullScreen !== undefined) {
  6484. _this.isFullscreen = document.msIsFullScreen;
  6485. }
  6486. // Pointer lock
  6487. if (_this.isFullscreen && _this._pointerLockRequested) {
  6488. canvas.requestPointerLock = canvas.requestPointerLock ||
  6489. canvas.msRequestPointerLock ||
  6490. canvas.mozRequestPointerLock ||
  6491. canvas.webkitRequestPointerLock;
  6492. if (canvas.requestPointerLock) {
  6493. canvas.requestPointerLock();
  6494. }
  6495. }
  6496. };
  6497. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6498. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6499. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6500. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6501. // Pointer lock
  6502. this._onPointerLockChange = function () {
  6503. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6504. document.webkitPointerLockElement === canvas ||
  6505. document.msPointerLockElement === canvas ||
  6506. document.pointerLockElement === canvas);
  6507. };
  6508. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6509. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6510. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6511. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6512. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6513. Engine.audioEngine = new BABYLON.AudioEngine();
  6514. }
  6515. //default loading screen
  6516. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6517. //Load WebVR Devices
  6518. if (options.autoEnableWebVR) {
  6519. this.initWebVR();
  6520. }
  6521. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6522. }
  6523. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6524. get: function () {
  6525. return Engine._ALPHA_DISABLE;
  6526. },
  6527. enumerable: true,
  6528. configurable: true
  6529. });
  6530. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6531. get: function () {
  6532. return Engine._ALPHA_ONEONE;
  6533. },
  6534. enumerable: true,
  6535. configurable: true
  6536. });
  6537. Object.defineProperty(Engine, "ALPHA_ADD", {
  6538. get: function () {
  6539. return Engine._ALPHA_ADD;
  6540. },
  6541. enumerable: true,
  6542. configurable: true
  6543. });
  6544. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6545. get: function () {
  6546. return Engine._ALPHA_COMBINE;
  6547. },
  6548. enumerable: true,
  6549. configurable: true
  6550. });
  6551. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6552. get: function () {
  6553. return Engine._ALPHA_SUBTRACT;
  6554. },
  6555. enumerable: true,
  6556. configurable: true
  6557. });
  6558. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6559. get: function () {
  6560. return Engine._ALPHA_MULTIPLY;
  6561. },
  6562. enumerable: true,
  6563. configurable: true
  6564. });
  6565. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6566. get: function () {
  6567. return Engine._ALPHA_MAXIMIZED;
  6568. },
  6569. enumerable: true,
  6570. configurable: true
  6571. });
  6572. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6573. get: function () {
  6574. return Engine._DELAYLOADSTATE_NONE;
  6575. },
  6576. enumerable: true,
  6577. configurable: true
  6578. });
  6579. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6580. get: function () {
  6581. return Engine._DELAYLOADSTATE_LOADED;
  6582. },
  6583. enumerable: true,
  6584. configurable: true
  6585. });
  6586. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6587. get: function () {
  6588. return Engine._DELAYLOADSTATE_LOADING;
  6589. },
  6590. enumerable: true,
  6591. configurable: true
  6592. });
  6593. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6594. get: function () {
  6595. return Engine._DELAYLOADSTATE_NOTLOADED;
  6596. },
  6597. enumerable: true,
  6598. configurable: true
  6599. });
  6600. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6601. get: function () {
  6602. return Engine._TEXTUREFORMAT_ALPHA;
  6603. },
  6604. enumerable: true,
  6605. configurable: true
  6606. });
  6607. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6608. get: function () {
  6609. return Engine._TEXTUREFORMAT_LUMINANCE;
  6610. },
  6611. enumerable: true,
  6612. configurable: true
  6613. });
  6614. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6615. get: function () {
  6616. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6617. },
  6618. enumerable: true,
  6619. configurable: true
  6620. });
  6621. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6622. get: function () {
  6623. return Engine._TEXTUREFORMAT_RGB;
  6624. },
  6625. enumerable: true,
  6626. configurable: true
  6627. });
  6628. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6629. get: function () {
  6630. return Engine._TEXTUREFORMAT_RGBA;
  6631. },
  6632. enumerable: true,
  6633. configurable: true
  6634. });
  6635. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6636. get: function () {
  6637. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6638. },
  6639. enumerable: true,
  6640. configurable: true
  6641. });
  6642. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6643. get: function () {
  6644. return Engine._TEXTURETYPE_FLOAT;
  6645. },
  6646. enumerable: true,
  6647. configurable: true
  6648. });
  6649. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  6650. get: function () {
  6651. return Engine._TEXTURETYPE_HALF_FLOAT;
  6652. },
  6653. enumerable: true,
  6654. configurable: true
  6655. });
  6656. Object.defineProperty(Engine, "Version", {
  6657. get: function () {
  6658. return "2.5.-alpha";
  6659. },
  6660. enumerable: true,
  6661. configurable: true
  6662. });
  6663. Object.defineProperty(Engine.prototype, "webGLVersion", {
  6664. get: function () {
  6665. return this._webGLVersion;
  6666. },
  6667. enumerable: true,
  6668. configurable: true
  6669. });
  6670. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  6671. /**
  6672. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  6673. */
  6674. get: function () {
  6675. return this._isStencilEnable;
  6676. },
  6677. enumerable: true,
  6678. configurable: true
  6679. });
  6680. Engine.prototype._prepareWorkingCanvas = function () {
  6681. if (this._workingCanvas) {
  6682. return;
  6683. }
  6684. this._workingCanvas = document.createElement("canvas");
  6685. this._workingContext = this._workingCanvas.getContext("2d");
  6686. };
  6687. Engine.prototype.resetTextureCache = function () {
  6688. for (var index = 0; index < this._maxTextureChannels; index++) {
  6689. this._activeTexturesCache[index] = null;
  6690. }
  6691. };
  6692. Engine.prototype.getGlInfo = function () {
  6693. return {
  6694. vendor: this._glVendor,
  6695. renderer: this._glRenderer,
  6696. version: this._glVersion
  6697. };
  6698. };
  6699. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  6700. if (useScreen === void 0) { useScreen = false; }
  6701. var viewport = camera.viewport;
  6702. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  6703. };
  6704. Engine.prototype.getRenderWidth = function (useScreen) {
  6705. if (useScreen === void 0) { useScreen = false; }
  6706. if (!useScreen && this._currentRenderTarget) {
  6707. return this._currentRenderTarget._width;
  6708. }
  6709. return this._renderingCanvas.width;
  6710. };
  6711. Engine.prototype.getRenderHeight = function (useScreen) {
  6712. if (useScreen === void 0) { useScreen = false; }
  6713. if (!useScreen && this._currentRenderTarget) {
  6714. return this._currentRenderTarget._height;
  6715. }
  6716. return this._renderingCanvas.height;
  6717. };
  6718. Engine.prototype.getRenderingCanvas = function () {
  6719. return this._renderingCanvas;
  6720. };
  6721. Engine.prototype.getRenderingCanvasClientRect = function () {
  6722. return this._renderingCanvas.getBoundingClientRect();
  6723. };
  6724. Engine.prototype.setHardwareScalingLevel = function (level) {
  6725. this._hardwareScalingLevel = level;
  6726. this.resize();
  6727. };
  6728. Engine.prototype.getHardwareScalingLevel = function () {
  6729. return this._hardwareScalingLevel;
  6730. };
  6731. Engine.prototype.getLoadedTexturesCache = function () {
  6732. return this._loadedTexturesCache;
  6733. };
  6734. Engine.prototype.getCaps = function () {
  6735. return this._caps;
  6736. };
  6737. Object.defineProperty(Engine.prototype, "drawCalls", {
  6738. get: function () {
  6739. return this._drawCalls.current;
  6740. },
  6741. enumerable: true,
  6742. configurable: true
  6743. });
  6744. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  6745. get: function () {
  6746. return this._drawCalls;
  6747. },
  6748. enumerable: true,
  6749. configurable: true
  6750. });
  6751. Engine.prototype.getDepthFunction = function () {
  6752. return this._depthCullingState.depthFunc;
  6753. };
  6754. Engine.prototype.setDepthFunction = function (depthFunc) {
  6755. this._depthCullingState.depthFunc = depthFunc;
  6756. };
  6757. Engine.prototype.setDepthFunctionToGreater = function () {
  6758. this._depthCullingState.depthFunc = this._gl.GREATER;
  6759. };
  6760. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  6761. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  6762. };
  6763. Engine.prototype.setDepthFunctionToLess = function () {
  6764. this._depthCullingState.depthFunc = this._gl.LESS;
  6765. };
  6766. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  6767. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  6768. };
  6769. Engine.prototype.getStencilBuffer = function () {
  6770. return this._stencilState.stencilTest;
  6771. };
  6772. Engine.prototype.setStencilBuffer = function (enable) {
  6773. this._stencilState.stencilTest = enable;
  6774. };
  6775. Engine.prototype.getStencilMask = function () {
  6776. return this._stencilState.stencilMask;
  6777. };
  6778. Engine.prototype.setStencilMask = function (mask) {
  6779. this._stencilState.stencilMask = mask;
  6780. };
  6781. Engine.prototype.getStencilFunction = function () {
  6782. return this._stencilState.stencilFunc;
  6783. };
  6784. Engine.prototype.getStencilFunctionReference = function () {
  6785. return this._stencilState.stencilFuncRef;
  6786. };
  6787. Engine.prototype.getStencilFunctionMask = function () {
  6788. return this._stencilState.stencilFuncMask;
  6789. };
  6790. Engine.prototype.setStencilFunction = function (stencilFunc) {
  6791. this._stencilState.stencilFunc = stencilFunc;
  6792. };
  6793. Engine.prototype.setStencilFunctionReference = function (reference) {
  6794. this._stencilState.stencilFuncRef = reference;
  6795. };
  6796. Engine.prototype.setStencilFunctionMask = function (mask) {
  6797. this._stencilState.stencilFuncMask = mask;
  6798. };
  6799. Engine.prototype.getStencilOperationFail = function () {
  6800. return this._stencilState.stencilOpStencilFail;
  6801. };
  6802. Engine.prototype.getStencilOperationDepthFail = function () {
  6803. return this._stencilState.stencilOpDepthFail;
  6804. };
  6805. Engine.prototype.getStencilOperationPass = function () {
  6806. return this._stencilState.stencilOpStencilDepthPass;
  6807. };
  6808. Engine.prototype.setStencilOperationFail = function (operation) {
  6809. this._stencilState.stencilOpStencilFail = operation;
  6810. };
  6811. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  6812. this._stencilState.stencilOpDepthFail = operation;
  6813. };
  6814. Engine.prototype.setStencilOperationPass = function (operation) {
  6815. this._stencilState.stencilOpStencilDepthPass = operation;
  6816. };
  6817. /**
  6818. * stop executing a render loop function and remove it from the execution array
  6819. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  6820. */
  6821. Engine.prototype.stopRenderLoop = function (renderFunction) {
  6822. if (!renderFunction) {
  6823. this._activeRenderLoops = [];
  6824. return;
  6825. }
  6826. var index = this._activeRenderLoops.indexOf(renderFunction);
  6827. if (index >= 0) {
  6828. this._activeRenderLoops.splice(index, 1);
  6829. }
  6830. };
  6831. Engine.prototype._renderLoop = function () {
  6832. var shouldRender = true;
  6833. if (!this.renderEvenInBackground && this._windowIsBackground) {
  6834. shouldRender = false;
  6835. }
  6836. if (shouldRender) {
  6837. // Start new frame
  6838. this.beginFrame();
  6839. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  6840. var renderFunction = this._activeRenderLoops[index];
  6841. renderFunction();
  6842. }
  6843. // Present
  6844. this.endFrame();
  6845. }
  6846. if (this._activeRenderLoops.length > 0) {
  6847. // Register new frame
  6848. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  6849. }
  6850. else {
  6851. this._renderingQueueLaunched = false;
  6852. }
  6853. };
  6854. /**
  6855. * Register and execute a render loop. The engine can have more than one render function.
  6856. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  6857. * @example
  6858. * engine.runRenderLoop(function () {
  6859. * scene.render()
  6860. * })
  6861. */
  6862. Engine.prototype.runRenderLoop = function (renderFunction) {
  6863. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  6864. return;
  6865. }
  6866. this._activeRenderLoops.push(renderFunction);
  6867. if (!this._renderingQueueLaunched) {
  6868. this._renderingQueueLaunched = true;
  6869. this._bindedRenderFunction = this._renderLoop.bind(this);
  6870. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6871. }
  6872. };
  6873. /**
  6874. * Toggle full screen mode.
  6875. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  6876. * @param {any} options - an options object to be sent to the requestFullscreen function
  6877. */
  6878. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  6879. if (this.isFullscreen) {
  6880. BABYLON.Tools.ExitFullscreen();
  6881. }
  6882. else {
  6883. this._pointerLockRequested = requestPointerLock;
  6884. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  6885. }
  6886. };
  6887. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  6888. if (stencil === void 0) { stencil = false; }
  6889. this.applyStates();
  6890. var mode = 0;
  6891. if (backBuffer) {
  6892. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  6893. mode |= this._gl.COLOR_BUFFER_BIT;
  6894. }
  6895. if (depth) {
  6896. this._gl.clearDepth(1.0);
  6897. mode |= this._gl.DEPTH_BUFFER_BIT;
  6898. }
  6899. if (stencil) {
  6900. this._gl.clearStencil(0);
  6901. mode |= this._gl.STENCIL_BUFFER_BIT;
  6902. }
  6903. this._gl.clear(mode);
  6904. };
  6905. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  6906. var gl = this._gl;
  6907. // Save state
  6908. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  6909. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  6910. // Change state
  6911. gl.enable(gl.SCISSOR_TEST);
  6912. gl.scissor(x, y, width, height);
  6913. // Clear
  6914. this.clear(clearColor, true, true, true);
  6915. // Restore state
  6916. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  6917. if (curScissor === true) {
  6918. gl.enable(gl.SCISSOR_TEST);
  6919. }
  6920. else {
  6921. gl.disable(gl.SCISSOR_TEST);
  6922. }
  6923. };
  6924. /**
  6925. * Set the WebGL's viewport
  6926. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  6927. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  6928. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  6929. */
  6930. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  6931. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  6932. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  6933. var x = viewport.x || 0;
  6934. var y = viewport.y || 0;
  6935. this._cachedViewport = viewport;
  6936. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  6937. };
  6938. /**
  6939. * Directly set the WebGL Viewport
  6940. * The x, y, width & height are directly passed to the WebGL call
  6941. * @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.
  6942. */
  6943. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  6944. var currentViewport = this._cachedViewport;
  6945. this._cachedViewport = null;
  6946. this._gl.viewport(x, y, width, height);
  6947. return currentViewport;
  6948. };
  6949. Engine.prototype.beginFrame = function () {
  6950. this._measureFps();
  6951. };
  6952. Engine.prototype.endFrame = function () {
  6953. //this.flushFramebuffer();
  6954. //submit frame to the vr device, if enabled
  6955. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  6956. this._vrDisplayEnabled.submitFrame();
  6957. }
  6958. };
  6959. /**
  6960. * resize the view according to the canvas' size.
  6961. * @example
  6962. * window.addEventListener("resize", function () {
  6963. * engine.resize();
  6964. * });
  6965. */
  6966. Engine.prototype.resize = function () {
  6967. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  6968. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  6969. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  6970. for (var index = 0; index < this.scenes.length; index++) {
  6971. var scene = this.scenes[index];
  6972. if (BABYLON.DebugLayer && scene.debugLayer.isVisible()) {
  6973. scene.debugLayer._syncPositions();
  6974. }
  6975. }
  6976. };
  6977. /**
  6978. * force a specific size of the canvas
  6979. * @param {number} width - the new canvas' width
  6980. * @param {number} height - the new canvas' height
  6981. */
  6982. Engine.prototype.setSize = function (width, height) {
  6983. this._renderingCanvas.width = width;
  6984. this._renderingCanvas.height = height;
  6985. for (var index = 0; index < this.scenes.length; index++) {
  6986. var scene = this.scenes[index];
  6987. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  6988. var cam = scene.cameras[camIndex];
  6989. cam._currentRenderId = 0;
  6990. }
  6991. }
  6992. };
  6993. //WebVR functions
  6994. Engine.prototype.initWebVR = function () {
  6995. if (!this.vrDisplaysPromise) {
  6996. this._getVRDisplays();
  6997. }
  6998. };
  6999. Engine.prototype.enableVR = function (vrDevice) {
  7000. this._vrDisplayEnabled = vrDevice;
  7001. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  7002. };
  7003. Engine.prototype.disableVR = function () {
  7004. if (this._vrDisplayEnabled) {
  7005. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  7006. }
  7007. };
  7008. Engine.prototype._getVRDisplays = function () {
  7009. var _this = this;
  7010. var getWebVRDevices = function (devices) {
  7011. var size = devices.length;
  7012. var i = 0;
  7013. _this._vrDisplays = devices.filter(function (device) {
  7014. return devices[i] instanceof VRDisplay;
  7015. });
  7016. return _this._vrDisplays;
  7017. };
  7018. //using a key due to typescript
  7019. if (navigator.getVRDisplays) {
  7020. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  7021. }
  7022. };
  7023. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  7024. this._currentRenderTarget = texture;
  7025. this.bindUnboundFramebuffer(texture._framebuffer);
  7026. var gl = this._gl;
  7027. if (texture.isCube) {
  7028. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  7029. }
  7030. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  7031. this.wipeCaches();
  7032. };
  7033. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  7034. if (this._currentFramebuffer !== framebuffer) {
  7035. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  7036. this._currentFramebuffer = framebuffer;
  7037. }
  7038. };
  7039. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  7040. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  7041. this._currentRenderTarget = null;
  7042. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  7043. var gl = this._gl;
  7044. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7045. gl.generateMipmap(gl.TEXTURE_2D);
  7046. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7047. }
  7048. this.bindUnboundFramebuffer(null);
  7049. };
  7050. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  7051. if (texture.generateMipMaps) {
  7052. var gl = this._gl;
  7053. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7054. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7055. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7056. }
  7057. };
  7058. Engine.prototype.flushFramebuffer = function () {
  7059. this._gl.flush();
  7060. };
  7061. Engine.prototype.restoreDefaultFramebuffer = function () {
  7062. this._currentRenderTarget = null;
  7063. this.bindUnboundFramebuffer(null);
  7064. this.setViewport(this._cachedViewport);
  7065. this.wipeCaches();
  7066. };
  7067. // VBOs
  7068. Engine.prototype._resetVertexBufferBinding = function () {
  7069. this.bindArrayBuffer(null);
  7070. this._cachedVertexBuffers = null;
  7071. };
  7072. Engine.prototype.createVertexBuffer = function (vertices) {
  7073. var vbo = this._gl.createBuffer();
  7074. this.bindArrayBuffer(vbo);
  7075. if (vertices instanceof Float32Array) {
  7076. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  7077. }
  7078. else {
  7079. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  7080. }
  7081. this._resetVertexBufferBinding();
  7082. vbo.references = 1;
  7083. return vbo;
  7084. };
  7085. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  7086. var vbo = this._gl.createBuffer();
  7087. this.bindArrayBuffer(vbo);
  7088. if (vertices instanceof Float32Array) {
  7089. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  7090. }
  7091. else {
  7092. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  7093. }
  7094. this._resetVertexBufferBinding();
  7095. vbo.references = 1;
  7096. return vbo;
  7097. };
  7098. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  7099. this.bindArrayBuffer(vertexBuffer);
  7100. if (offset === undefined) {
  7101. offset = 0;
  7102. }
  7103. if (count === undefined) {
  7104. if (vertices instanceof Float32Array) {
  7105. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  7106. }
  7107. else {
  7108. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  7109. }
  7110. }
  7111. else {
  7112. if (vertices instanceof Float32Array) {
  7113. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  7114. }
  7115. else {
  7116. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  7117. }
  7118. }
  7119. this._resetVertexBufferBinding();
  7120. };
  7121. Engine.prototype._resetIndexBufferBinding = function () {
  7122. this.bindIndexBuffer(null);
  7123. this._cachedIndexBuffer = null;
  7124. };
  7125. Engine.prototype.createIndexBuffer = function (indices) {
  7126. var vbo = this._gl.createBuffer();
  7127. this.bindIndexBuffer(vbo);
  7128. // Check for 32 bits indices
  7129. var arrayBuffer;
  7130. var need32Bits = false;
  7131. if (this._caps.uintIndices) {
  7132. for (var index = 0; index < indices.length; index++) {
  7133. if (indices[index] > 65535) {
  7134. need32Bits = true;
  7135. break;
  7136. }
  7137. }
  7138. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  7139. }
  7140. else {
  7141. arrayBuffer = new Uint16Array(indices);
  7142. }
  7143. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  7144. this._resetIndexBufferBinding();
  7145. vbo.references = 1;
  7146. vbo.is32Bits = need32Bits;
  7147. return vbo;
  7148. };
  7149. Engine.prototype.bindArrayBuffer = function (buffer) {
  7150. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  7151. };
  7152. Engine.prototype.bindIndexBuffer = function (buffer) {
  7153. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  7154. };
  7155. Engine.prototype.bindBuffer = function (buffer, target) {
  7156. if (this._currentBoundBuffer[target] !== buffer) {
  7157. this._gl.bindBuffer(target, buffer);
  7158. this._currentBoundBuffer[target] = buffer;
  7159. }
  7160. };
  7161. Engine.prototype.updateArrayBuffer = function (data) {
  7162. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7163. };
  7164. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  7165. var pointer = this._currentBufferPointers[indx];
  7166. var changed = false;
  7167. if (!pointer) {
  7168. changed = true;
  7169. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  7170. }
  7171. else {
  7172. if (pointer.buffer !== buffer) {
  7173. pointer.buffer = buffer;
  7174. changed = true;
  7175. }
  7176. if (pointer.size !== size) {
  7177. pointer.size = size;
  7178. changed = true;
  7179. }
  7180. if (pointer.type !== type) {
  7181. pointer.type = type;
  7182. changed = true;
  7183. }
  7184. if (pointer.normalized !== normalized) {
  7185. pointer.normalized = normalized;
  7186. changed = true;
  7187. }
  7188. if (pointer.stride !== stride) {
  7189. pointer.stride = stride;
  7190. changed = true;
  7191. }
  7192. if (pointer.offset !== offset) {
  7193. pointer.offset = offset;
  7194. changed = true;
  7195. }
  7196. }
  7197. if (changed) {
  7198. this.bindArrayBuffer(buffer);
  7199. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  7200. }
  7201. };
  7202. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  7203. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  7204. this._cachedVertexBuffers = vertexBuffer;
  7205. this._cachedEffectForVertexBuffers = effect;
  7206. var attributesCount = effect.getAttributesCount();
  7207. var offset = 0;
  7208. for (var index = 0; index < attributesCount; index++) {
  7209. if (index < vertexDeclaration.length) {
  7210. var order = effect.getAttributeLocation(index);
  7211. if (order >= 0) {
  7212. if (!this._vertexAttribArraysEnabled[order]) {
  7213. this._gl.enableVertexAttribArray(order);
  7214. this._vertexAttribArraysEnabled[order] = true;
  7215. }
  7216. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  7217. }
  7218. offset += vertexDeclaration[index] * 4;
  7219. }
  7220. else {
  7221. //disable effect attributes that have no data
  7222. var order = effect.getAttributeLocation(index);
  7223. if (this._vertexAttribArraysEnabled[order]) {
  7224. this._gl.disableVertexAttribArray(order);
  7225. this._vertexAttribArraysEnabled[order] = false;
  7226. }
  7227. }
  7228. }
  7229. }
  7230. if (this._cachedIndexBuffer !== indexBuffer) {
  7231. this._cachedIndexBuffer = indexBuffer;
  7232. this.bindIndexBuffer(indexBuffer);
  7233. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7234. }
  7235. };
  7236. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  7237. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  7238. this._cachedVertexBuffers = vertexBuffers;
  7239. this._cachedEffectForVertexBuffers = effect;
  7240. var attributes = effect.getAttributesNames();
  7241. for (var index = 0; index < attributes.length; index++) {
  7242. var order = effect.getAttributeLocation(index);
  7243. if (order >= 0) {
  7244. var vertexBuffer = vertexBuffers[attributes[index]];
  7245. if (!vertexBuffer) {
  7246. if (this._vertexAttribArraysEnabled[order]) {
  7247. this._gl.disableVertexAttribArray(order);
  7248. this._vertexAttribArraysEnabled[order] = false;
  7249. }
  7250. continue;
  7251. }
  7252. if (!this._vertexAttribArraysEnabled[order]) {
  7253. this._gl.enableVertexAttribArray(order);
  7254. this._vertexAttribArraysEnabled[order] = true;
  7255. }
  7256. var buffer = vertexBuffer.getBuffer();
  7257. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  7258. if (vertexBuffer.getIsInstanced()) {
  7259. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  7260. this._currentInstanceLocations.push(order);
  7261. this._currentInstanceBuffers.push(buffer);
  7262. }
  7263. }
  7264. }
  7265. }
  7266. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  7267. this._cachedIndexBuffer = indexBuffer;
  7268. this.bindIndexBuffer(indexBuffer);
  7269. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7270. }
  7271. };
  7272. Engine.prototype.unbindInstanceAttributes = function () {
  7273. var boundBuffer;
  7274. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  7275. var instancesBuffer = this._currentInstanceBuffers[i];
  7276. if (boundBuffer != instancesBuffer) {
  7277. boundBuffer = instancesBuffer;
  7278. this.bindArrayBuffer(instancesBuffer);
  7279. }
  7280. var offsetLocation = this._currentInstanceLocations[i];
  7281. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  7282. }
  7283. this._currentInstanceBuffers.length = 0;
  7284. this._currentInstanceLocations.length = 0;
  7285. };
  7286. Engine.prototype._releaseBuffer = function (buffer) {
  7287. buffer.references--;
  7288. if (buffer.references === 0) {
  7289. this._gl.deleteBuffer(buffer);
  7290. return true;
  7291. }
  7292. return false;
  7293. };
  7294. Engine.prototype.createInstancesBuffer = function (capacity) {
  7295. var buffer = this._gl.createBuffer();
  7296. buffer.capacity = capacity;
  7297. this.bindArrayBuffer(buffer);
  7298. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  7299. return buffer;
  7300. };
  7301. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  7302. this._gl.deleteBuffer(buffer);
  7303. };
  7304. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  7305. this.bindArrayBuffer(instancesBuffer);
  7306. if (data) {
  7307. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7308. }
  7309. if (offsetLocations[0].index !== undefined) {
  7310. var stride = 0;
  7311. for (var i = 0; i < offsetLocations.length; i++) {
  7312. var ai = offsetLocations[i];
  7313. stride += ai.attributeSize * 4;
  7314. }
  7315. for (var i = 0; i < offsetLocations.length; i++) {
  7316. var ai = offsetLocations[i];
  7317. if (!this._vertexAttribArraysEnabled[ai.index]) {
  7318. this._gl.enableVertexAttribArray(ai.index);
  7319. this._vertexAttribArraysEnabled[ai.index] = true;
  7320. }
  7321. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  7322. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  7323. this._currentInstanceLocations.push(ai.index);
  7324. this._currentInstanceBuffers.push(instancesBuffer);
  7325. }
  7326. }
  7327. else {
  7328. for (var index = 0; index < 4; index++) {
  7329. var offsetLocation = offsetLocations[index];
  7330. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  7331. this._gl.enableVertexAttribArray(offsetLocation);
  7332. this._vertexAttribArraysEnabled[offsetLocation] = true;
  7333. }
  7334. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  7335. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  7336. this._currentInstanceLocations.push(offsetLocation);
  7337. this._currentInstanceBuffers.push(instancesBuffer);
  7338. }
  7339. }
  7340. };
  7341. Engine.prototype.applyStates = function () {
  7342. this._depthCullingState.apply(this._gl);
  7343. this._stencilState.apply(this._gl);
  7344. this._alphaState.apply(this._gl);
  7345. };
  7346. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  7347. // Apply states
  7348. this.applyStates();
  7349. this._drawCalls.addCount(1, false);
  7350. // Render
  7351. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  7352. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  7353. if (instancesCount) {
  7354. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  7355. return;
  7356. }
  7357. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  7358. };
  7359. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  7360. // Apply states
  7361. this.applyStates();
  7362. this._drawCalls.addCount(1, false);
  7363. if (instancesCount) {
  7364. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  7365. return;
  7366. }
  7367. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  7368. };
  7369. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  7370. // Apply states
  7371. this.applyStates();
  7372. this._drawCalls.addCount(1, false);
  7373. if (instancesCount) {
  7374. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  7375. return;
  7376. }
  7377. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  7378. };
  7379. // Shaders
  7380. Engine.prototype._releaseEffect = function (effect) {
  7381. if (this._compiledEffects[effect._key]) {
  7382. delete this._compiledEffects[effect._key];
  7383. if (effect.getProgram()) {
  7384. this._gl.deleteProgram(effect.getProgram());
  7385. }
  7386. }
  7387. };
  7388. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  7389. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  7390. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  7391. var name = vertex + "+" + fragment + "@" + defines;
  7392. if (this._compiledEffects[name]) {
  7393. return this._compiledEffects[name];
  7394. }
  7395. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  7396. effect._key = name;
  7397. this._compiledEffects[name] = effect;
  7398. return effect;
  7399. };
  7400. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  7401. if (uniformsNames === void 0) { uniformsNames = []; }
  7402. if (samplers === void 0) { samplers = []; }
  7403. if (defines === void 0) { defines = ""; }
  7404. return this.createEffect({
  7405. vertex: "particles",
  7406. fragmentElement: fragmentName
  7407. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  7408. };
  7409. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  7410. context = context || this._gl;
  7411. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  7412. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  7413. var shaderProgram = context.createProgram();
  7414. context.attachShader(shaderProgram, vertexShader);
  7415. context.attachShader(shaderProgram, fragmentShader);
  7416. context.linkProgram(shaderProgram);
  7417. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  7418. if (!linked) {
  7419. var error = context.getProgramInfoLog(shaderProgram);
  7420. if (error) {
  7421. throw new Error(error);
  7422. }
  7423. }
  7424. context.deleteShader(vertexShader);
  7425. context.deleteShader(fragmentShader);
  7426. return shaderProgram;
  7427. };
  7428. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  7429. var results = [];
  7430. for (var index = 0; index < uniformsNames.length; index++) {
  7431. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  7432. }
  7433. return results;
  7434. };
  7435. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  7436. var results = [];
  7437. for (var index = 0; index < attributesNames.length; index++) {
  7438. try {
  7439. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  7440. }
  7441. catch (e) {
  7442. results.push(-1);
  7443. }
  7444. }
  7445. return results;
  7446. };
  7447. Engine.prototype.enableEffect = function (effect) {
  7448. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  7449. if (effect && effect.onBind) {
  7450. effect.onBind(effect);
  7451. }
  7452. return;
  7453. }
  7454. // Use program
  7455. this.setProgram(effect.getProgram());
  7456. this._currentEffect = effect;
  7457. if (effect.onBind) {
  7458. effect.onBind(effect);
  7459. }
  7460. };
  7461. Engine.prototype.setIntArray = function (uniform, array) {
  7462. if (!uniform)
  7463. return;
  7464. this._gl.uniform1iv(uniform, array);
  7465. };
  7466. Engine.prototype.setIntArray2 = function (uniform, array) {
  7467. if (!uniform || array.length % 2 !== 0)
  7468. return;
  7469. this._gl.uniform2iv(uniform, array);
  7470. };
  7471. Engine.prototype.setIntArray3 = function (uniform, array) {
  7472. if (!uniform || array.length % 3 !== 0)
  7473. return;
  7474. this._gl.uniform3iv(uniform, array);
  7475. };
  7476. Engine.prototype.setIntArray4 = function (uniform, array) {
  7477. if (!uniform || array.length % 4 !== 0)
  7478. return;
  7479. this._gl.uniform4iv(uniform, array);
  7480. };
  7481. Engine.prototype.setFloatArray = function (uniform, array) {
  7482. if (!uniform)
  7483. return;
  7484. this._gl.uniform1fv(uniform, array);
  7485. };
  7486. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7487. if (!uniform || array.length % 2 !== 0)
  7488. return;
  7489. this._gl.uniform2fv(uniform, array);
  7490. };
  7491. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7492. if (!uniform || array.length % 3 !== 0)
  7493. return;
  7494. this._gl.uniform3fv(uniform, array);
  7495. };
  7496. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7497. if (!uniform || array.length % 4 !== 0)
  7498. return;
  7499. this._gl.uniform4fv(uniform, array);
  7500. };
  7501. Engine.prototype.setArray = function (uniform, array) {
  7502. if (!uniform)
  7503. return;
  7504. this._gl.uniform1fv(uniform, array);
  7505. };
  7506. Engine.prototype.setArray2 = function (uniform, array) {
  7507. if (!uniform || array.length % 2 !== 0)
  7508. return;
  7509. this._gl.uniform2fv(uniform, array);
  7510. };
  7511. Engine.prototype.setArray3 = function (uniform, array) {
  7512. if (!uniform || array.length % 3 !== 0)
  7513. return;
  7514. this._gl.uniform3fv(uniform, array);
  7515. };
  7516. Engine.prototype.setArray4 = function (uniform, array) {
  7517. if (!uniform || array.length % 4 !== 0)
  7518. return;
  7519. this._gl.uniform4fv(uniform, array);
  7520. };
  7521. Engine.prototype.setMatrices = function (uniform, matrices) {
  7522. if (!uniform)
  7523. return;
  7524. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7525. };
  7526. Engine.prototype.setMatrix = function (uniform, matrix) {
  7527. if (!uniform)
  7528. return;
  7529. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7530. };
  7531. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7532. if (!uniform)
  7533. return;
  7534. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7535. };
  7536. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7537. if (!uniform)
  7538. return;
  7539. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7540. };
  7541. Engine.prototype.setFloat = function (uniform, value) {
  7542. if (!uniform)
  7543. return;
  7544. this._gl.uniform1f(uniform, value);
  7545. };
  7546. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7547. if (!uniform)
  7548. return;
  7549. this._gl.uniform2f(uniform, x, y);
  7550. };
  7551. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7552. if (!uniform)
  7553. return;
  7554. this._gl.uniform3f(uniform, x, y, z);
  7555. };
  7556. Engine.prototype.setBool = function (uniform, bool) {
  7557. if (!uniform)
  7558. return;
  7559. this._gl.uniform1i(uniform, bool);
  7560. };
  7561. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7562. if (!uniform)
  7563. return;
  7564. this._gl.uniform4f(uniform, x, y, z, w);
  7565. };
  7566. Engine.prototype.setColor3 = function (uniform, color3) {
  7567. if (!uniform)
  7568. return;
  7569. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7570. };
  7571. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7572. if (!uniform)
  7573. return;
  7574. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7575. };
  7576. // States
  7577. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7578. if (zOffset === void 0) { zOffset = 0; }
  7579. if (reverseSide === void 0) { reverseSide = false; }
  7580. // Culling
  7581. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7582. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7583. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7584. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7585. if (culling) {
  7586. this._depthCullingState.cullFace = cullFace;
  7587. this._depthCullingState.cull = true;
  7588. }
  7589. else {
  7590. this._depthCullingState.cull = false;
  7591. }
  7592. }
  7593. // Z offset
  7594. this._depthCullingState.zOffset = zOffset;
  7595. };
  7596. Engine.prototype.setDepthBuffer = function (enable) {
  7597. this._depthCullingState.depthTest = enable;
  7598. };
  7599. Engine.prototype.getDepthWrite = function () {
  7600. return this._depthCullingState.depthMask;
  7601. };
  7602. Engine.prototype.setDepthWrite = function (enable) {
  7603. this._depthCullingState.depthMask = enable;
  7604. };
  7605. Engine.prototype.setColorWrite = function (enable) {
  7606. this._gl.colorMask(enable, enable, enable, enable);
  7607. };
  7608. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7609. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7610. if (this._alphaMode === mode) {
  7611. return;
  7612. }
  7613. switch (mode) {
  7614. case Engine.ALPHA_DISABLE:
  7615. this._alphaState.alphaBlend = false;
  7616. break;
  7617. case Engine.ALPHA_COMBINE:
  7618. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7619. this._alphaState.alphaBlend = true;
  7620. break;
  7621. case Engine.ALPHA_ONEONE:
  7622. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7623. this._alphaState.alphaBlend = true;
  7624. break;
  7625. case Engine.ALPHA_ADD:
  7626. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7627. this._alphaState.alphaBlend = true;
  7628. break;
  7629. case Engine.ALPHA_SUBTRACT:
  7630. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7631. this._alphaState.alphaBlend = true;
  7632. break;
  7633. case Engine.ALPHA_MULTIPLY:
  7634. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7635. this._alphaState.alphaBlend = true;
  7636. break;
  7637. case Engine.ALPHA_MAXIMIZED:
  7638. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7639. this._alphaState.alphaBlend = true;
  7640. break;
  7641. }
  7642. if (!noDepthWriteChange) {
  7643. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7644. }
  7645. this._alphaMode = mode;
  7646. };
  7647. Engine.prototype.getAlphaMode = function () {
  7648. return this._alphaMode;
  7649. };
  7650. Engine.prototype.setAlphaTesting = function (enable) {
  7651. this._alphaTest = enable;
  7652. };
  7653. Engine.prototype.getAlphaTesting = function () {
  7654. return this._alphaTest;
  7655. };
  7656. // Textures
  7657. Engine.prototype.wipeCaches = function () {
  7658. this.resetTextureCache();
  7659. this._currentEffect = null;
  7660. this._stencilState.reset();
  7661. this._depthCullingState.reset();
  7662. this.setDepthFunctionToLessOrEqual();
  7663. this._alphaState.reset();
  7664. this._cachedVertexBuffers = null;
  7665. this._cachedIndexBuffer = null;
  7666. this._cachedEffectForVertexBuffers = null;
  7667. };
  7668. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  7669. var gl = this._gl;
  7670. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7671. var magFilter = gl.NEAREST;
  7672. var minFilter = gl.NEAREST;
  7673. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7674. magFilter = gl.LINEAR;
  7675. minFilter = gl.LINEAR;
  7676. }
  7677. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7678. magFilter = gl.LINEAR;
  7679. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7680. }
  7681. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  7682. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  7683. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7684. texture.samplingMode = samplingMode;
  7685. };
  7686. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  7687. var _this = this;
  7688. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7689. if (onLoad === void 0) { onLoad = null; }
  7690. if (onError === void 0) { onError = null; }
  7691. if (buffer === void 0) { buffer = null; }
  7692. var texture = this._gl.createTexture();
  7693. var extension;
  7694. var fromData = false;
  7695. if (url.substr(0, 5) === "data:") {
  7696. fromData = true;
  7697. }
  7698. if (!fromData)
  7699. extension = url.substr(url.length - 4, 4).toLowerCase();
  7700. else {
  7701. var oldUrl = url;
  7702. fromData = oldUrl.split(':');
  7703. url = oldUrl;
  7704. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  7705. }
  7706. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7707. var isTGA = (extension === ".tga");
  7708. scene._addPendingData(texture);
  7709. texture.url = url;
  7710. texture.noMipmap = noMipmap;
  7711. texture.references = 1;
  7712. texture.samplingMode = samplingMode;
  7713. texture.onLoadedCallbacks = [onLoad];
  7714. this._loadedTexturesCache.push(texture);
  7715. var onerror = function () {
  7716. scene._removePendingData(texture);
  7717. if (onError) {
  7718. onError();
  7719. }
  7720. };
  7721. var callback;
  7722. if (isTGA) {
  7723. callback = function (arrayBuffer) {
  7724. var data = new Uint8Array(arrayBuffer);
  7725. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  7726. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  7727. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  7728. }, samplingMode);
  7729. };
  7730. if (!(fromData instanceof Array))
  7731. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  7732. callback(arrayBuffer);
  7733. }, null, scene.database, true, onerror);
  7734. else
  7735. callback(buffer);
  7736. }
  7737. else if (isDDS) {
  7738. callback = function (data) {
  7739. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7740. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  7741. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  7742. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  7743. }, samplingMode);
  7744. };
  7745. if (!(fromData instanceof Array))
  7746. BABYLON.Tools.LoadFile(url, function (data) {
  7747. callback(data);
  7748. }, null, scene.database, true, onerror);
  7749. else
  7750. callback(buffer);
  7751. }
  7752. else {
  7753. var onload = function (img) {
  7754. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  7755. var isPot = (img.width === potWidth && img.height === potHeight);
  7756. if (!isPot) {
  7757. _this._prepareWorkingCanvas();
  7758. _this._workingCanvas.width = potWidth;
  7759. _this._workingCanvas.height = potHeight;
  7760. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7761. _this._workingContext.imageSmoothingEnabled = false;
  7762. _this._workingContext.mozImageSmoothingEnabled = false;
  7763. _this._workingContext.oImageSmoothingEnabled = false;
  7764. _this._workingContext.webkitImageSmoothingEnabled = false;
  7765. _this._workingContext.msImageSmoothingEnabled = false;
  7766. }
  7767. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  7768. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7769. _this._workingContext.imageSmoothingEnabled = true;
  7770. _this._workingContext.mozImageSmoothingEnabled = true;
  7771. _this._workingContext.oImageSmoothingEnabled = true;
  7772. _this._workingContext.webkitImageSmoothingEnabled = true;
  7773. _this._workingContext.msImageSmoothingEnabled = true;
  7774. }
  7775. }
  7776. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  7777. }, samplingMode);
  7778. };
  7779. if (!(fromData instanceof Array))
  7780. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7781. else
  7782. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  7783. }
  7784. return texture;
  7785. };
  7786. Engine.prototype._getInternalFormat = function (format) {
  7787. var internalFormat = this._gl.RGBA;
  7788. switch (format) {
  7789. case Engine.TEXTUREFORMAT_ALPHA:
  7790. internalFormat = this._gl.ALPHA;
  7791. break;
  7792. case Engine.TEXTUREFORMAT_LUMINANCE:
  7793. internalFormat = this._gl.LUMINANCE;
  7794. break;
  7795. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  7796. internalFormat = this._gl.LUMINANCE_ALPHA;
  7797. break;
  7798. case Engine.TEXTUREFORMAT_RGB:
  7799. internalFormat = this._gl.RGB;
  7800. break;
  7801. case Engine.TEXTUREFORMAT_RGBA:
  7802. internalFormat = this._gl.RGBA;
  7803. break;
  7804. }
  7805. return internalFormat;
  7806. };
  7807. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  7808. if (compression === void 0) { compression = null; }
  7809. var internalFormat = this._getInternalFormat(format);
  7810. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7811. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7812. if (texture._width % 4 !== 0) {
  7813. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  7814. }
  7815. if (compression) {
  7816. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  7817. }
  7818. else {
  7819. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  7820. }
  7821. if (texture.generateMipMaps) {
  7822. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7823. }
  7824. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7825. this.resetTextureCache();
  7826. texture.isReady = true;
  7827. };
  7828. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  7829. if (compression === void 0) { compression = null; }
  7830. var texture = this._gl.createTexture();
  7831. texture._baseWidth = width;
  7832. texture._baseHeight = height;
  7833. texture._width = width;
  7834. texture._height = height;
  7835. texture.references = 1;
  7836. this.updateRawTexture(texture, data, format, invertY, compression);
  7837. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7838. // Filters
  7839. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  7840. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7841. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7842. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7843. texture.samplingMode = samplingMode;
  7844. this._loadedTexturesCache.push(texture);
  7845. return texture;
  7846. };
  7847. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  7848. var texture = this._gl.createTexture();
  7849. texture._baseWidth = width;
  7850. texture._baseHeight = height;
  7851. if (generateMipMaps) {
  7852. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  7853. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  7854. }
  7855. this.resetTextureCache();
  7856. texture._width = width;
  7857. texture._height = height;
  7858. texture.isReady = false;
  7859. texture.generateMipMaps = generateMipMaps;
  7860. texture.references = 1;
  7861. texture.samplingMode = samplingMode;
  7862. this.updateTextureSamplingMode(samplingMode, texture);
  7863. this._loadedTexturesCache.push(texture);
  7864. return texture;
  7865. };
  7866. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  7867. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  7868. if (texture.isCube) {
  7869. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  7870. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7871. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7872. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  7873. }
  7874. else {
  7875. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7876. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7877. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7878. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7879. }
  7880. };
  7881. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  7882. if (premulAlpha === void 0) { premulAlpha = false; }
  7883. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7884. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  7885. if (premulAlpha) {
  7886. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  7887. }
  7888. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  7889. if (texture.generateMipMaps) {
  7890. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7891. }
  7892. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7893. this.resetTextureCache();
  7894. texture.isReady = true;
  7895. };
  7896. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  7897. if (texture._isDisabled) {
  7898. return;
  7899. }
  7900. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7901. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  7902. try {
  7903. // Testing video texture support
  7904. if (this._videoTextureSupported === undefined) {
  7905. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7906. if (this._gl.getError() !== 0) {
  7907. this._videoTextureSupported = false;
  7908. }
  7909. else {
  7910. this._videoTextureSupported = true;
  7911. }
  7912. }
  7913. // Copy video through the current working canvas if video texture is not supported
  7914. if (!this._videoTextureSupported) {
  7915. if (!texture._workingCanvas) {
  7916. texture._workingCanvas = document.createElement("canvas");
  7917. texture._workingContext = texture._workingCanvas.getContext("2d");
  7918. texture._workingCanvas.width = texture._width;
  7919. texture._workingCanvas.height = texture._height;
  7920. }
  7921. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  7922. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  7923. }
  7924. else {
  7925. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7926. }
  7927. if (texture.generateMipMaps) {
  7928. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7929. }
  7930. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7931. this.resetTextureCache();
  7932. texture.isReady = true;
  7933. }
  7934. catch (ex) {
  7935. // Something unexpected
  7936. // Let's disable the texture
  7937. texture._isDisabled = true;
  7938. }
  7939. };
  7940. Engine.prototype.createRenderTargetTexture = function (size, options) {
  7941. // old version had a "generateMipMaps" arg instead of options.
  7942. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  7943. // in the same way, generateDepthBuffer is defaulted to true
  7944. var generateMipMaps = false;
  7945. var generateDepthBuffer = true;
  7946. var generateStencilBuffer = false;
  7947. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7948. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7949. if (options !== undefined) {
  7950. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7951. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  7952. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  7953. type = options.type === undefined ? type : options.type;
  7954. if (options.samplingMode !== undefined) {
  7955. samplingMode = options.samplingMode;
  7956. }
  7957. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  7958. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  7959. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  7960. }
  7961. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  7962. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  7963. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  7964. }
  7965. }
  7966. var gl = this._gl;
  7967. var texture = gl.createTexture();
  7968. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7969. var width = size.width || size;
  7970. var height = size.height || size;
  7971. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7972. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  7973. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7974. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  7975. }
  7976. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7977. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7978. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7979. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7980. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  7981. var depthStencilBuffer;
  7982. // Create the depth/stencil buffer
  7983. if (generateStencilBuffer) {
  7984. depthStencilBuffer = gl.createRenderbuffer();
  7985. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  7986. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  7987. }
  7988. else if (generateDepthBuffer) {
  7989. depthStencilBuffer = gl.createRenderbuffer();
  7990. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  7991. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  7992. }
  7993. // Create the framebuffer
  7994. var framebuffer = gl.createFramebuffer();
  7995. this.bindUnboundFramebuffer(framebuffer);
  7996. // Manage attachments
  7997. if (generateStencilBuffer) {
  7998. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  7999. }
  8000. else if (generateDepthBuffer) {
  8001. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8002. }
  8003. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  8004. if (generateMipMaps) {
  8005. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8006. }
  8007. // Unbind
  8008. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8009. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8010. this.bindUnboundFramebuffer(null);
  8011. texture._framebuffer = framebuffer;
  8012. if (generateDepthBuffer) {
  8013. texture._depthBuffer = depthStencilBuffer;
  8014. }
  8015. texture._baseWidth = width;
  8016. texture._baseHeight = height;
  8017. texture._width = width;
  8018. texture._height = height;
  8019. texture.isReady = true;
  8020. texture.generateMipMaps = generateMipMaps;
  8021. texture.references = 1;
  8022. texture.samplingMode = samplingMode;
  8023. texture.type = type;
  8024. this.resetTextureCache();
  8025. this._loadedTexturesCache.push(texture);
  8026. return texture;
  8027. };
  8028. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  8029. var gl = this._gl;
  8030. var texture = gl.createTexture();
  8031. var generateMipMaps = true;
  8032. var generateDepthBuffer = true;
  8033. var generateStencilBuffer = false;
  8034. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8035. if (options !== undefined) {
  8036. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8037. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8038. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8039. if (options.samplingMode !== undefined) {
  8040. samplingMode = options.samplingMode;
  8041. }
  8042. }
  8043. texture.isCube = true;
  8044. texture.references = 1;
  8045. texture.generateMipMaps = generateMipMaps;
  8046. texture.references = 1;
  8047. texture.samplingMode = samplingMode;
  8048. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8049. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8050. for (var face = 0; face < 6; face++) {
  8051. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  8052. }
  8053. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  8054. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  8055. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8056. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8057. // Create the depth buffer
  8058. var depthStencilBuffer;
  8059. // Create the depth/stencil buffer
  8060. if (generateStencilBuffer) {
  8061. depthStencilBuffer = gl.createRenderbuffer();
  8062. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8063. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  8064. }
  8065. else if (generateDepthBuffer) {
  8066. depthStencilBuffer = gl.createRenderbuffer();
  8067. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8068. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  8069. }
  8070. // Create the framebuffer
  8071. var framebuffer = gl.createFramebuffer();
  8072. this.bindUnboundFramebuffer(framebuffer);
  8073. // Manage attachments
  8074. if (generateStencilBuffer) {
  8075. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8076. }
  8077. else if (generateDepthBuffer) {
  8078. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8079. }
  8080. // Mipmaps
  8081. if (texture.generateMipMaps) {
  8082. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8083. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8084. }
  8085. // Unbind
  8086. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8087. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8088. this.bindUnboundFramebuffer(null);
  8089. texture._framebuffer = framebuffer;
  8090. if (generateDepthBuffer) {
  8091. texture._depthBuffer = depthStencilBuffer;
  8092. }
  8093. texture._width = size;
  8094. texture._height = size;
  8095. texture.isReady = true;
  8096. this.resetTextureCache();
  8097. this._loadedTexturesCache.push(texture);
  8098. return texture;
  8099. };
  8100. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  8101. var _this = this;
  8102. var gl = this._gl;
  8103. var texture = gl.createTexture();
  8104. texture.isCube = true;
  8105. texture.url = rootUrl;
  8106. texture.references = 1;
  8107. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  8108. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8109. if (isDDS) {
  8110. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8111. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8112. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  8113. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8114. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8115. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  8116. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  8117. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8118. }
  8119. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8120. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8121. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8122. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8123. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8124. _this.resetTextureCache();
  8125. texture._width = info.width;
  8126. texture._height = info.height;
  8127. texture.isReady = true;
  8128. }, null, null, true);
  8129. }
  8130. else {
  8131. cascadeLoad(rootUrl, scene, function (imgs) {
  8132. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  8133. var height = width;
  8134. _this._prepareWorkingCanvas();
  8135. _this._workingCanvas.width = width;
  8136. _this._workingCanvas.height = height;
  8137. var faces = [
  8138. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8139. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8140. ];
  8141. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8142. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8143. for (var index = 0; index < faces.length; index++) {
  8144. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  8145. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  8146. }
  8147. if (!noMipmap) {
  8148. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8149. }
  8150. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8151. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8152. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8153. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8154. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8155. _this.resetTextureCache();
  8156. texture._width = width;
  8157. texture._height = height;
  8158. texture.isReady = true;
  8159. }, files);
  8160. }
  8161. this._loadedTexturesCache.push(texture);
  8162. return texture;
  8163. };
  8164. Engine.prototype.updateTextureSize = function (texture, width, height) {
  8165. texture._width = width;
  8166. texture._height = height;
  8167. texture._size = width * height;
  8168. texture._baseWidth = width;
  8169. texture._baseHeight = height;
  8170. };
  8171. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  8172. var _this = this;
  8173. var gl = this._gl;
  8174. var texture = gl.createTexture();
  8175. scene._addPendingData(texture);
  8176. texture.isCube = true;
  8177. texture.references = 1;
  8178. texture.url = url;
  8179. var internalFormat = this._getInternalFormat(format);
  8180. var textureType = gl.UNSIGNED_BYTE;
  8181. if (type === Engine.TEXTURETYPE_FLOAT) {
  8182. textureType = gl.FLOAT;
  8183. }
  8184. var width = size;
  8185. var height = width;
  8186. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8187. texture._width = width;
  8188. texture._height = height;
  8189. var onerror = function () {
  8190. scene._removePendingData(texture);
  8191. };
  8192. var internalCallback = function (data) {
  8193. var rgbeDataArrays = callback(data);
  8194. var facesIndex = [
  8195. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8196. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8197. ];
  8198. width = texture._width;
  8199. height = texture._height;
  8200. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8201. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8202. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8203. if (!noMipmap && isPot) {
  8204. if (mipmmapGenerator) {
  8205. var arrayTemp = [];
  8206. // Data are known to be in +X +Y +Z -X -Y -Z
  8207. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  8208. arrayTemp.push(rgbeDataArrays[0]); // +X
  8209. arrayTemp.push(rgbeDataArrays[3]); // -X
  8210. arrayTemp.push(rgbeDataArrays[1]); // +Y
  8211. arrayTemp.push(rgbeDataArrays[4]); // -Y
  8212. arrayTemp.push(rgbeDataArrays[2]); // +Z
  8213. arrayTemp.push(rgbeDataArrays[5]); // -Z
  8214. var mipData = mipmmapGenerator(arrayTemp);
  8215. for (var level = 0; level < mipData.length; level++) {
  8216. var mipSize = width >> level;
  8217. // mipData is order in +X -X +Y -Y +Z -Z
  8218. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  8219. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  8220. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  8221. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  8222. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  8223. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  8224. }
  8225. }
  8226. else {
  8227. // Data are known to be in +X +Y +Z -X -Y -Z
  8228. for (var index = 0; index < facesIndex.length; index++) {
  8229. var faceData = rgbeDataArrays[index];
  8230. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  8231. }
  8232. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8233. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  8234. // By following the webgl standard changes from Revision 7, 2014/11/24
  8235. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  8236. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  8237. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  8238. // Data are known to be in +X +Y +Z -X -Y -Z
  8239. for (var index = 0; index < facesIndex.length; index++) {
  8240. var faceData = rgbeDataArrays[index];
  8241. // Create a new RGBA Face.
  8242. var newFaceData = new Float32Array(width * height * 4);
  8243. for (var x = 0; x < width; x++) {
  8244. for (var y = 0; y < height; y++) {
  8245. var index_1 = (y * width + x) * 3;
  8246. var newIndex = (y * width + x) * 4;
  8247. // Map Old Value to new value.
  8248. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  8249. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  8250. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  8251. // Add fully opaque alpha channel.
  8252. newFaceData[newIndex + 3] = 1;
  8253. }
  8254. }
  8255. // Reupload the face.
  8256. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  8257. }
  8258. // Try to generate mipmap again.
  8259. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8260. }
  8261. }
  8262. }
  8263. else {
  8264. noMipmap = true;
  8265. }
  8266. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  8267. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8268. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8269. }
  8270. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  8271. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8272. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8273. }
  8274. else {
  8275. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8276. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8277. }
  8278. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8279. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8280. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8281. texture.isReady = true;
  8282. _this.resetTextureCache();
  8283. scene._removePendingData(texture);
  8284. };
  8285. BABYLON.Tools.LoadFile(url, function (data) {
  8286. internalCallback(data);
  8287. }, onerror, scene.database, true);
  8288. return texture;
  8289. };
  8290. ;
  8291. Engine.prototype._releaseTexture = function (texture) {
  8292. var gl = this._gl;
  8293. if (texture._framebuffer) {
  8294. gl.deleteFramebuffer(texture._framebuffer);
  8295. }
  8296. if (texture._depthBuffer) {
  8297. gl.deleteRenderbuffer(texture._depthBuffer);
  8298. }
  8299. gl.deleteTexture(texture);
  8300. // Unbind channels
  8301. this.unbindAllTextures();
  8302. var index = this._loadedTexturesCache.indexOf(texture);
  8303. if (index !== -1) {
  8304. this._loadedTexturesCache.splice(index, 1);
  8305. }
  8306. };
  8307. Engine.prototype.setProgram = function (program) {
  8308. if (this._currentProgram !== program) {
  8309. this._gl.useProgram(program);
  8310. this._currentProgram = program;
  8311. }
  8312. };
  8313. Engine.prototype.bindSamplers = function (effect) {
  8314. this.setProgram(effect.getProgram());
  8315. var samplers = effect.getSamplers();
  8316. for (var index = 0; index < samplers.length; index++) {
  8317. var uniform = effect.getUniform(samplers[index]);
  8318. this._gl.uniform1i(uniform, index);
  8319. }
  8320. this._currentEffect = null;
  8321. };
  8322. Engine.prototype.activateTexture = function (texture) {
  8323. if (this._activeTexture !== texture) {
  8324. this._gl.activeTexture(texture);
  8325. this._activeTexture = texture;
  8326. }
  8327. };
  8328. Engine.prototype._bindTextureDirectly = function (target, texture) {
  8329. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  8330. this._gl.bindTexture(target, texture);
  8331. this._activeTexturesCache[this._activeTexture] = texture;
  8332. }
  8333. };
  8334. Engine.prototype._bindTexture = function (channel, texture) {
  8335. if (channel < 0) {
  8336. return;
  8337. }
  8338. this.activateTexture(this._gl["TEXTURE" + channel]);
  8339. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8340. };
  8341. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  8342. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  8343. };
  8344. Engine.prototype.unbindAllTextures = function () {
  8345. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  8346. this.activateTexture(this._gl["TEXTURE" + channel]);
  8347. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8348. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8349. }
  8350. };
  8351. Engine.prototype.setTexture = function (channel, uniform, texture) {
  8352. if (channel < 0) {
  8353. return;
  8354. }
  8355. this._gl.uniform1i(uniform, channel);
  8356. this._setTexture(channel, texture);
  8357. };
  8358. Engine.prototype._setTexture = function (channel, texture) {
  8359. // Not ready?
  8360. if (!texture || !texture.isReady()) {
  8361. if (this._activeTexturesCache[channel] != null) {
  8362. this.activateTexture(this._gl["TEXTURE" + channel]);
  8363. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8364. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8365. }
  8366. return;
  8367. }
  8368. // Video
  8369. var alreadyActivated = false;
  8370. if (texture instanceof BABYLON.VideoTexture) {
  8371. this.activateTexture(this._gl["TEXTURE" + channel]);
  8372. alreadyActivated = true;
  8373. texture.update();
  8374. }
  8375. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  8376. texture.delayLoad();
  8377. return;
  8378. }
  8379. var internalTexture = texture.getInternalTexture();
  8380. if (this._activeTexturesCache[channel] === internalTexture) {
  8381. return;
  8382. }
  8383. if (!alreadyActivated) {
  8384. this.activateTexture(this._gl["TEXTURE" + channel]);
  8385. }
  8386. if (internalTexture.isCube) {
  8387. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  8388. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  8389. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  8390. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  8391. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  8392. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  8393. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  8394. }
  8395. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  8396. }
  8397. else {
  8398. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  8399. if (internalTexture._cachedWrapU !== texture.wrapU) {
  8400. internalTexture._cachedWrapU = texture.wrapU;
  8401. switch (texture.wrapU) {
  8402. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8403. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  8404. break;
  8405. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8406. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  8407. break;
  8408. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8409. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  8410. break;
  8411. }
  8412. }
  8413. if (internalTexture._cachedWrapV !== texture.wrapV) {
  8414. internalTexture._cachedWrapV = texture.wrapV;
  8415. switch (texture.wrapV) {
  8416. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8417. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  8418. break;
  8419. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8420. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  8421. break;
  8422. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8423. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  8424. break;
  8425. }
  8426. }
  8427. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  8428. }
  8429. };
  8430. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  8431. if (channel < 0) {
  8432. return;
  8433. }
  8434. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  8435. this._textureUnits = new Int32Array(textures.length);
  8436. }
  8437. for (var i = 0; i < textures.length; i++) {
  8438. this._textureUnits[i] = channel + i;
  8439. }
  8440. this._gl.uniform1iv(uniform, this._textureUnits);
  8441. for (var index = 0; index < textures.length; index++) {
  8442. this._setTexture(channel + index, textures[index]);
  8443. }
  8444. };
  8445. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  8446. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  8447. var value = texture.anisotropicFilteringLevel;
  8448. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8449. value = 1;
  8450. }
  8451. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  8452. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  8453. texture._cachedAnisotropicFilteringLevel = value;
  8454. }
  8455. };
  8456. Engine.prototype.readPixels = function (x, y, width, height) {
  8457. var data = new Uint8Array(height * width * 4);
  8458. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  8459. return data;
  8460. };
  8461. /**
  8462. * Add an externaly attached data from its key.
  8463. * This method call will fail and return false, if such key already exists.
  8464. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  8465. * @param key the unique key that identifies the data
  8466. * @param data the data object to associate to the key for this Engine instance
  8467. * @return true if no such key were already present and the data was added successfully, false otherwise
  8468. */
  8469. Engine.prototype.addExternalData = function (key, data) {
  8470. return this._externalData.add(key, data);
  8471. };
  8472. /**
  8473. * Get an externaly attached data from its key
  8474. * @param key the unique key that identifies the data
  8475. * @return the associated data, if present (can be null), or undefined if not present
  8476. */
  8477. Engine.prototype.getExternalData = function (key) {
  8478. return this._externalData.get(key);
  8479. };
  8480. /**
  8481. * Get an externaly attached data from its key, create it using a factory if it's not already present
  8482. * @param key the unique key that identifies the data
  8483. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  8484. * @return the associated data, can be null if the factory returned null.
  8485. */
  8486. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  8487. return this._externalData.getOrAddWithFactory(key, factory);
  8488. };
  8489. /**
  8490. * Remove an externaly attached data from the Engine instance
  8491. * @param key the unique key that identifies the data
  8492. * @return true if the data was successfully removed, false if it doesn't exist
  8493. */
  8494. Engine.prototype.removeExternalData = function (key) {
  8495. return this._externalData.remove(key);
  8496. };
  8497. Engine.prototype.releaseInternalTexture = function (texture) {
  8498. if (!texture) {
  8499. return;
  8500. }
  8501. texture.references--;
  8502. // Final reference ?
  8503. if (texture.references === 0) {
  8504. var texturesCache = this.getLoadedTexturesCache();
  8505. var index = texturesCache.indexOf(texture);
  8506. if (index > -1) {
  8507. texturesCache.splice(index, 1);
  8508. }
  8509. this._releaseTexture(texture);
  8510. }
  8511. };
  8512. // Dispose
  8513. Engine.prototype.dispose = function () {
  8514. this.hideLoadingUI();
  8515. this.stopRenderLoop();
  8516. // Release scenes
  8517. while (this.scenes.length) {
  8518. this.scenes[0].dispose();
  8519. }
  8520. // Release audio engine
  8521. Engine.audioEngine.dispose();
  8522. // Release effects
  8523. for (var name in this._compiledEffects) {
  8524. this._gl.deleteProgram(this._compiledEffects[name]._program);
  8525. }
  8526. // Unbind
  8527. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  8528. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  8529. continue;
  8530. }
  8531. this._gl.disableVertexAttribArray(i);
  8532. }
  8533. this._gl = null;
  8534. //WebVR
  8535. this.disableVR();
  8536. // Events
  8537. window.removeEventListener("blur", this._onBlur);
  8538. window.removeEventListener("focus", this._onFocus);
  8539. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  8540. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  8541. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  8542. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  8543. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  8544. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  8545. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  8546. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  8547. };
  8548. // Loading screen
  8549. Engine.prototype.displayLoadingUI = function () {
  8550. this._loadingScreen.displayLoadingUI();
  8551. };
  8552. Engine.prototype.hideLoadingUI = function () {
  8553. this._loadingScreen.hideLoadingUI();
  8554. };
  8555. Object.defineProperty(Engine.prototype, "loadingScreen", {
  8556. get: function () {
  8557. return this._loadingScreen;
  8558. },
  8559. set: function (loadingScreen) {
  8560. this._loadingScreen = loadingScreen;
  8561. },
  8562. enumerable: true,
  8563. configurable: true
  8564. });
  8565. Object.defineProperty(Engine.prototype, "loadingUIText", {
  8566. set: function (text) {
  8567. this._loadingScreen.loadingUIText = text;
  8568. },
  8569. enumerable: true,
  8570. configurable: true
  8571. });
  8572. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  8573. set: function (color) {
  8574. this._loadingScreen.loadingUIBackgroundColor = color;
  8575. },
  8576. enumerable: true,
  8577. configurable: true
  8578. });
  8579. Engine.prototype.attachContextLostEvent = function (callback) {
  8580. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  8581. };
  8582. Engine.prototype.attachContextRestoredEvent = function (callback) {
  8583. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  8584. };
  8585. // FPS
  8586. Engine.prototype.getFps = function () {
  8587. return this.fps;
  8588. };
  8589. Engine.prototype.getDeltaTime = function () {
  8590. return this.deltaTime;
  8591. };
  8592. Engine.prototype._measureFps = function () {
  8593. this.previousFramesDuration.push(BABYLON.Tools.Now);
  8594. var length = this.previousFramesDuration.length;
  8595. if (length >= 2) {
  8596. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  8597. }
  8598. if (length >= this.fpsRange) {
  8599. if (length > this.fpsRange) {
  8600. this.previousFramesDuration.splice(0, 1);
  8601. length = this.previousFramesDuration.length;
  8602. }
  8603. var sum = 0;
  8604. for (var id = 0; id < length - 1; id++) {
  8605. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  8606. }
  8607. this.fps = 1000.0 / (sum / (length - 1));
  8608. }
  8609. };
  8610. Engine.prototype._canRenderToFloatTexture = function () {
  8611. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  8612. };
  8613. Engine.prototype._canRenderToHalfFloatTexture = function () {
  8614. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  8615. };
  8616. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  8617. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  8618. var tempcanvas = document.createElement("canvas");
  8619. tempcanvas.height = 16;
  8620. tempcanvas.width = 16;
  8621. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  8622. // extension.
  8623. var ext = gl.getExtension(extension);
  8624. if (!ext) {
  8625. return false;
  8626. }
  8627. // setup GLSL program
  8628. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  8629. 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 }";
  8630. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  8631. gl.useProgram(program);
  8632. // look up where the vertex data needs to go.
  8633. var positionLocation = gl.getAttribLocation(program, "a_position");
  8634. var colorLoc = gl.getUniformLocation(program, "u_color");
  8635. // provide texture coordinates for the rectangle.
  8636. var positionBuffer = gl.createBuffer();
  8637. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  8638. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  8639. -1.0, -1.0,
  8640. 1.0, -1.0,
  8641. -1.0, 1.0,
  8642. -1.0, 1.0,
  8643. 1.0, -1.0,
  8644. 1.0, 1.0]), gl.STATIC_DRAW);
  8645. gl.enableVertexAttribArray(positionLocation);
  8646. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  8647. var whiteTex = gl.createTexture();
  8648. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8649. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  8650. var tex = gl.createTexture();
  8651. gl.bindTexture(gl.TEXTURE_2D, tex);
  8652. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  8653. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8654. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8655. var fb = gl.createFramebuffer();
  8656. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  8657. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  8658. var cleanup = function () {
  8659. gl.deleteProgram(program);
  8660. gl.disableVertexAttribArray(positionLocation);
  8661. gl.deleteBuffer(positionBuffer);
  8662. gl.deleteFramebuffer(fb);
  8663. gl.deleteTexture(whiteTex);
  8664. gl.deleteTexture(tex);
  8665. };
  8666. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  8667. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  8668. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  8669. cleanup();
  8670. return false;
  8671. }
  8672. // Draw the rectangle.
  8673. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8674. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  8675. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8676. gl.bindTexture(gl.TEXTURE_2D, tex);
  8677. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  8678. gl.clearColor(1, 0, 0, 1);
  8679. gl.clear(gl.COLOR_BUFFER_BIT);
  8680. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  8681. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8682. var pixel = new Uint8Array(4);
  8683. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  8684. if (pixel[0] !== 0 ||
  8685. pixel[1] < 248 ||
  8686. pixel[2] < 248 ||
  8687. pixel[3] < 254) {
  8688. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  8689. cleanup();
  8690. return false;
  8691. }
  8692. // Succesfully rendered to "format" texture.
  8693. cleanup();
  8694. return true;
  8695. };
  8696. // Statics
  8697. Engine.isSupported = function () {
  8698. try {
  8699. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  8700. if (navigator.isCocoonJS) {
  8701. return true;
  8702. }
  8703. var tempcanvas = document.createElement("canvas");
  8704. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  8705. return gl != null && !!window.WebGLRenderingContext;
  8706. }
  8707. catch (e) {
  8708. return false;
  8709. }
  8710. };
  8711. // Const statics
  8712. Engine._ALPHA_DISABLE = 0;
  8713. Engine._ALPHA_ADD = 1;
  8714. Engine._ALPHA_COMBINE = 2;
  8715. Engine._ALPHA_SUBTRACT = 3;
  8716. Engine._ALPHA_MULTIPLY = 4;
  8717. Engine._ALPHA_MAXIMIZED = 5;
  8718. Engine._ALPHA_ONEONE = 6;
  8719. Engine._DELAYLOADSTATE_NONE = 0;
  8720. Engine._DELAYLOADSTATE_LOADED = 1;
  8721. Engine._DELAYLOADSTATE_LOADING = 2;
  8722. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  8723. Engine._TEXTUREFORMAT_ALPHA = 0;
  8724. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  8725. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  8726. Engine._TEXTUREFORMAT_RGB = 4;
  8727. Engine._TEXTUREFORMAT_RGBA = 5;
  8728. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  8729. Engine._TEXTURETYPE_FLOAT = 1;
  8730. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  8731. // Updatable statics so stick with vars here
  8732. Engine.CollisionsEpsilon = 0.001;
  8733. Engine.CodeRepository = "src/";
  8734. Engine.ShadersRepository = "src/Shaders/";
  8735. return Engine;
  8736. })();
  8737. BABYLON.Engine = Engine;
  8738. })(BABYLON || (BABYLON = {}));
  8739. var BABYLON;
  8740. (function (BABYLON) {
  8741. /**
  8742. * Node is the basic class for all scene objects (Mesh, Light Camera).
  8743. */
  8744. var Node = (function () {
  8745. /**
  8746. * @constructor
  8747. * @param {string} name - the name and id to be given to this node
  8748. * @param {BABYLON.Scene} the scene this node will be added to
  8749. */
  8750. function Node(name, scene) {
  8751. this.state = "";
  8752. this.animations = new Array();
  8753. this._ranges = {};
  8754. this._childrenFlag = -1;
  8755. this._isEnabled = true;
  8756. this._isReady = true;
  8757. this._currentRenderId = -1;
  8758. this._parentRenderId = -1;
  8759. this.name = name;
  8760. this.id = name;
  8761. this._scene = scene;
  8762. this._initCache();
  8763. }
  8764. Object.defineProperty(Node.prototype, "parent", {
  8765. get: function () {
  8766. return this._parentNode;
  8767. },
  8768. set: function (parent) {
  8769. if (this._parentNode === parent) {
  8770. return;
  8771. }
  8772. if (this._parentNode) {
  8773. var index = this._parentNode._children.indexOf(this);
  8774. if (index !== -1) {
  8775. this._parentNode._children.splice(index, 1);
  8776. }
  8777. }
  8778. this._parentNode = parent;
  8779. if (this._parentNode) {
  8780. if (!this._parentNode._children) {
  8781. this._parentNode._children = new Array();
  8782. }
  8783. this._parentNode._children.push(this);
  8784. }
  8785. },
  8786. enumerable: true,
  8787. configurable: true
  8788. });
  8789. Node.prototype.getScene = function () {
  8790. return this._scene;
  8791. };
  8792. Node.prototype.getEngine = function () {
  8793. return this._scene.getEngine();
  8794. };
  8795. // override it in derived class
  8796. Node.prototype.getWorldMatrix = function () {
  8797. return BABYLON.Matrix.Identity();
  8798. };
  8799. // override it in derived class if you add new variables to the cache
  8800. // and call the parent class method
  8801. Node.prototype._initCache = function () {
  8802. this._cache = {};
  8803. this._cache.parent = undefined;
  8804. };
  8805. Node.prototype.updateCache = function (force) {
  8806. if (!force && this.isSynchronized())
  8807. return;
  8808. this._cache.parent = this.parent;
  8809. this._updateCache();
  8810. };
  8811. // override it in derived class if you add new variables to the cache
  8812. // and call the parent class method if !ignoreParentClass
  8813. Node.prototype._updateCache = function (ignoreParentClass) {
  8814. };
  8815. // override it in derived class if you add new variables to the cache
  8816. Node.prototype._isSynchronized = function () {
  8817. return true;
  8818. };
  8819. Node.prototype._markSyncedWithParent = function () {
  8820. this._parentRenderId = this.parent._currentRenderId;
  8821. };
  8822. Node.prototype.isSynchronizedWithParent = function () {
  8823. if (!this.parent) {
  8824. return true;
  8825. }
  8826. if (this._parentRenderId !== this.parent._currentRenderId) {
  8827. return false;
  8828. }
  8829. return this.parent.isSynchronized();
  8830. };
  8831. Node.prototype.isSynchronized = function (updateCache) {
  8832. var check = this.hasNewParent();
  8833. check = check || !this.isSynchronizedWithParent();
  8834. check = check || !this._isSynchronized();
  8835. if (updateCache)
  8836. this.updateCache(true);
  8837. return !check;
  8838. };
  8839. Node.prototype.hasNewParent = function (update) {
  8840. if (this._cache.parent === this.parent)
  8841. return false;
  8842. if (update)
  8843. this._cache.parent = this.parent;
  8844. return true;
  8845. };
  8846. /**
  8847. * Is this node ready to be used/rendered
  8848. * @return {boolean} is it ready
  8849. */
  8850. Node.prototype.isReady = function () {
  8851. return this._isReady;
  8852. };
  8853. /**
  8854. * Is this node enabled.
  8855. * If the node has a parent and is enabled, the parent will be inspected as well.
  8856. * @return {boolean} whether this node (and its parent) is enabled.
  8857. * @see setEnabled
  8858. */
  8859. Node.prototype.isEnabled = function () {
  8860. if (!this._isEnabled) {
  8861. return false;
  8862. }
  8863. if (this.parent) {
  8864. return this.parent.isEnabled();
  8865. }
  8866. return true;
  8867. };
  8868. /**
  8869. * Set the enabled state of this node.
  8870. * @param {boolean} value - the new enabled state
  8871. * @see isEnabled
  8872. */
  8873. Node.prototype.setEnabled = function (value) {
  8874. this._isEnabled = value;
  8875. };
  8876. /**
  8877. * Is this node a descendant of the given node.
  8878. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  8879. * @param {BABYLON.Node} ancestor - The parent node to inspect
  8880. * @see parent
  8881. */
  8882. Node.prototype.isDescendantOf = function (ancestor) {
  8883. if (this.parent) {
  8884. if (this.parent === ancestor) {
  8885. return true;
  8886. }
  8887. return this.parent.isDescendantOf(ancestor);
  8888. }
  8889. return false;
  8890. };
  8891. /**
  8892. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  8893. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  8894. * @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.
  8895. * @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.
  8896. */
  8897. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  8898. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  8899. if (!this._children) {
  8900. return;
  8901. }
  8902. for (var index = 0; index < this._children.length; index++) {
  8903. var item = this._children[index];
  8904. if (!predicate || predicate(item)) {
  8905. results.push(item);
  8906. }
  8907. if (!directDescendantsOnly) {
  8908. item._getDescendants(results, false, predicate);
  8909. }
  8910. }
  8911. };
  8912. /**
  8913. * Will return all nodes that have this node as ascendant.
  8914. * @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.
  8915. * @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.
  8916. * @return {BABYLON.Node[]} all children nodes of all types.
  8917. */
  8918. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  8919. var results = [];
  8920. this._getDescendants(results, directDescendantsOnly, predicate);
  8921. return results;
  8922. };
  8923. /**
  8924. * @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.
  8925. * @Deprecated, legacy support.
  8926. * use getDecendants instead.
  8927. */
  8928. Node.prototype.getChildren = function (predicate) {
  8929. return this.getDescendants(true, predicate);
  8930. };
  8931. /**
  8932. * Get all child-meshes of this node.
  8933. */
  8934. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  8935. var results = [];
  8936. this._getDescendants(results, directDecendantsOnly, function (node) {
  8937. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  8938. });
  8939. return results;
  8940. };
  8941. Node.prototype._setReady = function (state) {
  8942. if (state === this._isReady) {
  8943. return;
  8944. }
  8945. if (!state) {
  8946. this._isReady = false;
  8947. return;
  8948. }
  8949. this._isReady = true;
  8950. if (this.onReady) {
  8951. this.onReady(this);
  8952. }
  8953. };
  8954. Node.prototype.getAnimationByName = function (name) {
  8955. for (var i = 0; i < this.animations.length; i++) {
  8956. var animation = this.animations[i];
  8957. if (animation.name === name) {
  8958. return animation;
  8959. }
  8960. }
  8961. return null;
  8962. };
  8963. Node.prototype.createAnimationRange = function (name, from, to) {
  8964. // check name not already in use
  8965. if (!this._ranges[name]) {
  8966. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  8967. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8968. if (this.animations[i]) {
  8969. this.animations[i].createRange(name, from, to);
  8970. }
  8971. }
  8972. }
  8973. };
  8974. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  8975. if (deleteFrames === void 0) { deleteFrames = true; }
  8976. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8977. if (this.animations[i]) {
  8978. this.animations[i].deleteRange(name, deleteFrames);
  8979. }
  8980. }
  8981. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  8982. };
  8983. Node.prototype.getAnimationRange = function (name) {
  8984. return this._ranges[name];
  8985. };
  8986. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  8987. var range = this.getAnimationRange(name);
  8988. if (!range) {
  8989. return null;
  8990. }
  8991. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  8992. };
  8993. Node.prototype.serializeAnimationRanges = function () {
  8994. var serializationRanges = [];
  8995. for (var name in this._ranges) {
  8996. var range = {};
  8997. range.name = name;
  8998. range.from = this._ranges[name].from;
  8999. range.to = this._ranges[name].to;
  9000. serializationRanges.push(range);
  9001. }
  9002. return serializationRanges;
  9003. };
  9004. Node.prototype.dispose = function () {
  9005. this.parent = null;
  9006. };
  9007. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  9008. if (parsedNode.ranges) {
  9009. for (var index = 0; index < parsedNode.ranges.length; index++) {
  9010. var data = parsedNode.ranges[index];
  9011. node.createAnimationRange(data.name, data.from, data.to);
  9012. }
  9013. }
  9014. };
  9015. __decorate([
  9016. BABYLON.serialize()
  9017. ], Node.prototype, "name", void 0);
  9018. __decorate([
  9019. BABYLON.serialize()
  9020. ], Node.prototype, "id", void 0);
  9021. __decorate([
  9022. BABYLON.serialize()
  9023. ], Node.prototype, "uniqueId", void 0);
  9024. __decorate([
  9025. BABYLON.serialize()
  9026. ], Node.prototype, "state", void 0);
  9027. return Node;
  9028. })();
  9029. BABYLON.Node = Node;
  9030. })(BABYLON || (BABYLON = {}));
  9031. var BABYLON;
  9032. (function (BABYLON) {
  9033. var FilesInput = (function () {
  9034. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  9035. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  9036. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  9037. this._engine = p_engine;
  9038. this._canvas = p_canvas;
  9039. this._currentScene = p_scene;
  9040. this._sceneLoadedCallback = p_sceneLoadedCallback;
  9041. this._progressCallback = p_progressCallback;
  9042. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  9043. this._textureLoadingCallback = p_textureLoadingCallback;
  9044. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  9045. }
  9046. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  9047. var _this = this;
  9048. if (p_elementToMonitor) {
  9049. this._elementToMonitor = p_elementToMonitor;
  9050. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  9051. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  9052. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  9053. }
  9054. };
  9055. FilesInput.prototype.renderFunction = function () {
  9056. if (this._additionnalRenderLoopLogicCallback) {
  9057. this._additionnalRenderLoopLogicCallback();
  9058. }
  9059. if (this._currentScene) {
  9060. if (this._textureLoadingCallback) {
  9061. var remaining = this._currentScene.getWaitingItemsCount();
  9062. if (remaining > 0) {
  9063. this._textureLoadingCallback(remaining);
  9064. }
  9065. }
  9066. this._currentScene.render();
  9067. }
  9068. };
  9069. FilesInput.prototype.drag = function (e) {
  9070. e.stopPropagation();
  9071. e.preventDefault();
  9072. };
  9073. FilesInput.prototype.drop = function (eventDrop) {
  9074. eventDrop.stopPropagation();
  9075. eventDrop.preventDefault();
  9076. this.loadFiles(eventDrop);
  9077. };
  9078. FilesInput.prototype.loadFiles = function (event) {
  9079. if (this._startingProcessingFilesCallback)
  9080. this._startingProcessingFilesCallback();
  9081. // Handling data transfer via drag'n'drop
  9082. if (event && event.dataTransfer && event.dataTransfer.files) {
  9083. this._filesToLoad = event.dataTransfer.files;
  9084. }
  9085. // Handling files from input files
  9086. if (event && event.target && event.target.files) {
  9087. this._filesToLoad = event.target.files;
  9088. }
  9089. if (this._filesToLoad && this._filesToLoad.length > 0) {
  9090. for (var i = 0; i < this._filesToLoad.length; i++) {
  9091. switch (this._filesToLoad[i].type) {
  9092. case "image/jpeg":
  9093. case "image/png":
  9094. case "image/bmp":
  9095. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9096. break;
  9097. case "image/targa":
  9098. case "image/vnd.ms-dds":
  9099. case "audio/wav":
  9100. case "audio/x-wav":
  9101. case "audio/mp3":
  9102. case "audio/mpeg":
  9103. case "audio/mpeg3":
  9104. case "audio/x-mpeg-3":
  9105. case "audio/ogg":
  9106. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9107. break;
  9108. default:
  9109. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  9110. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9111. }
  9112. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  9113. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  9114. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  9115. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  9116. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  9117. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  9118. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  9119. this._sceneFileToLoad = this._filesToLoad[i];
  9120. }
  9121. break;
  9122. }
  9123. }
  9124. this.reload();
  9125. }
  9126. };
  9127. FilesInput.prototype.reload = function () {
  9128. var _this = this;
  9129. var that = this;
  9130. // If a ".babylon" file has been provided
  9131. if (this._sceneFileToLoad) {
  9132. if (this._currentScene) {
  9133. if (BABYLON.Tools.errorsCount > 0) {
  9134. BABYLON.Tools.ClearLogCache();
  9135. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  9136. }
  9137. this._engine.stopRenderLoop();
  9138. this._currentScene.dispose();
  9139. }
  9140. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  9141. that._currentScene = newScene;
  9142. // Wait for textures and shaders to be ready
  9143. that._currentScene.executeWhenReady(function () {
  9144. // Attach camera to canvas inputs
  9145. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  9146. that._currentScene.createDefaultCameraOrLight();
  9147. }
  9148. that._currentScene.activeCamera.attachControl(that._canvas);
  9149. if (that._sceneLoadedCallback) {
  9150. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  9151. }
  9152. that._engine.runRenderLoop(function () { that.renderFunction(); });
  9153. });
  9154. }, function (progress) {
  9155. if (_this._progressCallback) {
  9156. _this._progressCallback(progress);
  9157. }
  9158. });
  9159. }
  9160. else {
  9161. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  9162. }
  9163. };
  9164. FilesInput.FilesTextures = new Array();
  9165. FilesInput.FilesToLoad = new Array();
  9166. return FilesInput;
  9167. })();
  9168. BABYLON.FilesInput = FilesInput;
  9169. })(BABYLON || (BABYLON = {}));
  9170. var BABYLON;
  9171. (function (BABYLON) {
  9172. var IntersectionInfo = (function () {
  9173. function IntersectionInfo(bu, bv, distance) {
  9174. this.bu = bu;
  9175. this.bv = bv;
  9176. this.distance = distance;
  9177. this.faceId = 0;
  9178. this.subMeshId = 0;
  9179. }
  9180. return IntersectionInfo;
  9181. })();
  9182. BABYLON.IntersectionInfo = IntersectionInfo;
  9183. var PickingInfo = (function () {
  9184. function PickingInfo() {
  9185. this.hit = false;
  9186. this.distance = 0;
  9187. this.pickedPoint = null;
  9188. this.pickedMesh = null;
  9189. this.bu = 0;
  9190. this.bv = 0;
  9191. this.faceId = -1;
  9192. this.subMeshId = 0;
  9193. this.pickedSprite = null;
  9194. }
  9195. // Methods
  9196. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  9197. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  9198. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  9199. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9200. return null;
  9201. }
  9202. var indices = this.pickedMesh.getIndices();
  9203. var result;
  9204. if (useVerticesNormals) {
  9205. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9206. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  9207. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  9208. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  9209. normal0 = normal0.scale(this.bu);
  9210. normal1 = normal1.scale(this.bv);
  9211. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  9212. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  9213. }
  9214. else {
  9215. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9216. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  9217. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  9218. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  9219. var p1p2 = vertex1.subtract(vertex2);
  9220. var p3p2 = vertex3.subtract(vertex2);
  9221. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  9222. }
  9223. if (useWorldCoordinates) {
  9224. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  9225. }
  9226. return BABYLON.Vector3.Normalize(result);
  9227. };
  9228. PickingInfo.prototype.getTextureCoordinates = function () {
  9229. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9230. return null;
  9231. }
  9232. var indices = this.pickedMesh.getIndices();
  9233. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9234. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  9235. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  9236. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  9237. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  9238. uv1 = uv1.scale(this.bu);
  9239. uv2 = uv2.scale(this.bv);
  9240. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  9241. };
  9242. return PickingInfo;
  9243. })();
  9244. BABYLON.PickingInfo = PickingInfo;
  9245. })(BABYLON || (BABYLON = {}));
  9246. var BABYLON;
  9247. (function (BABYLON) {
  9248. var BoundingSphere = (function () {
  9249. function BoundingSphere(minimum, maximum) {
  9250. this.minimum = minimum;
  9251. this.maximum = maximum;
  9252. this._tempRadiusVector = BABYLON.Vector3.Zero();
  9253. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  9254. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  9255. this.radius = distance * 0.5;
  9256. this.centerWorld = BABYLON.Vector3.Zero();
  9257. this._update(BABYLON.Matrix.Identity());
  9258. }
  9259. // Methods
  9260. BoundingSphere.prototype._update = function (world) {
  9261. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  9262. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  9263. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  9264. };
  9265. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  9266. for (var i = 0; i < 6; i++) {
  9267. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  9268. return false;
  9269. }
  9270. return true;
  9271. };
  9272. BoundingSphere.prototype.intersectsPoint = function (point) {
  9273. var x = this.centerWorld.x - point.x;
  9274. var y = this.centerWorld.y - point.y;
  9275. var z = this.centerWorld.z - point.z;
  9276. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9277. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  9278. return false;
  9279. return true;
  9280. };
  9281. // Statics
  9282. BoundingSphere.Intersects = function (sphere0, sphere1) {
  9283. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  9284. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  9285. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  9286. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9287. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  9288. return false;
  9289. return true;
  9290. };
  9291. return BoundingSphere;
  9292. })();
  9293. BABYLON.BoundingSphere = BoundingSphere;
  9294. })(BABYLON || (BABYLON = {}));
  9295. var BABYLON;
  9296. (function (BABYLON) {
  9297. var BoundingBox = (function () {
  9298. function BoundingBox(minimum, maximum) {
  9299. this.minimum = minimum;
  9300. this.maximum = maximum;
  9301. this.vectors = new Array();
  9302. this.vectorsWorld = new Array();
  9303. // Bounding vectors
  9304. this.vectors.push(this.minimum.clone());
  9305. this.vectors.push(this.maximum.clone());
  9306. this.vectors.push(this.minimum.clone());
  9307. this.vectors[2].x = this.maximum.x;
  9308. this.vectors.push(this.minimum.clone());
  9309. this.vectors[3].y = this.maximum.y;
  9310. this.vectors.push(this.minimum.clone());
  9311. this.vectors[4].z = this.maximum.z;
  9312. this.vectors.push(this.maximum.clone());
  9313. this.vectors[5].z = this.minimum.z;
  9314. this.vectors.push(this.maximum.clone());
  9315. this.vectors[6].x = this.minimum.x;
  9316. this.vectors.push(this.maximum.clone());
  9317. this.vectors[7].y = this.minimum.y;
  9318. // OBB
  9319. this.center = this.maximum.add(this.minimum).scale(0.5);
  9320. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  9321. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  9322. // World
  9323. for (var index = 0; index < this.vectors.length; index++) {
  9324. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  9325. }
  9326. this.minimumWorld = BABYLON.Vector3.Zero();
  9327. this.maximumWorld = BABYLON.Vector3.Zero();
  9328. this._update(BABYLON.Matrix.Identity());
  9329. }
  9330. // Methods
  9331. BoundingBox.prototype.getWorldMatrix = function () {
  9332. return this._worldMatrix;
  9333. };
  9334. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  9335. this._worldMatrix.copyFrom(matrix);
  9336. return this;
  9337. };
  9338. BoundingBox.prototype._update = function (world) {
  9339. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  9340. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  9341. for (var index = 0; index < this.vectors.length; index++) {
  9342. var v = this.vectorsWorld[index];
  9343. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  9344. if (v.x < this.minimumWorld.x)
  9345. this.minimumWorld.x = v.x;
  9346. if (v.y < this.minimumWorld.y)
  9347. this.minimumWorld.y = v.y;
  9348. if (v.z < this.minimumWorld.z)
  9349. this.minimumWorld.z = v.z;
  9350. if (v.x > this.maximumWorld.x)
  9351. this.maximumWorld.x = v.x;
  9352. if (v.y > this.maximumWorld.y)
  9353. this.maximumWorld.y = v.y;
  9354. if (v.z > this.maximumWorld.z)
  9355. this.maximumWorld.z = v.z;
  9356. }
  9357. // OBB
  9358. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  9359. this.center.scaleInPlace(0.5);
  9360. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  9361. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  9362. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  9363. this._worldMatrix = world;
  9364. };
  9365. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  9366. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  9367. };
  9368. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9369. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  9370. };
  9371. BoundingBox.prototype.intersectsPoint = function (point) {
  9372. var delta = -BABYLON.Epsilon;
  9373. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  9374. return false;
  9375. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  9376. return false;
  9377. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  9378. return false;
  9379. return true;
  9380. };
  9381. BoundingBox.prototype.intersectsSphere = function (sphere) {
  9382. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  9383. };
  9384. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  9385. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  9386. return false;
  9387. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  9388. return false;
  9389. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  9390. return false;
  9391. return true;
  9392. };
  9393. // Statics
  9394. BoundingBox.Intersects = function (box0, box1) {
  9395. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  9396. return false;
  9397. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  9398. return false;
  9399. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  9400. return false;
  9401. return true;
  9402. };
  9403. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  9404. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  9405. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  9406. return (num <= (sphereRadius * sphereRadius));
  9407. };
  9408. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  9409. for (var p = 0; p < 6; p++) {
  9410. for (var i = 0; i < 8; i++) {
  9411. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9412. return false;
  9413. }
  9414. }
  9415. }
  9416. return true;
  9417. };
  9418. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  9419. for (var p = 0; p < 6; p++) {
  9420. var inCount = 8;
  9421. for (var i = 0; i < 8; i++) {
  9422. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9423. --inCount;
  9424. }
  9425. else {
  9426. break;
  9427. }
  9428. }
  9429. if (inCount === 0)
  9430. return false;
  9431. }
  9432. return true;
  9433. };
  9434. return BoundingBox;
  9435. })();
  9436. BABYLON.BoundingBox = BoundingBox;
  9437. })(BABYLON || (BABYLON = {}));
  9438. var BABYLON;
  9439. (function (BABYLON) {
  9440. var computeBoxExtents = function (axis, box) {
  9441. var p = BABYLON.Vector3.Dot(box.center, axis);
  9442. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  9443. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  9444. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  9445. var r = r0 + r1 + r2;
  9446. return {
  9447. min: p - r,
  9448. max: p + r
  9449. };
  9450. };
  9451. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  9452. var axisOverlap = function (axis, box0, box1) {
  9453. var result0 = computeBoxExtents(axis, box0);
  9454. var result1 = computeBoxExtents(axis, box1);
  9455. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  9456. };
  9457. var BoundingInfo = (function () {
  9458. function BoundingInfo(minimum, maximum) {
  9459. this.minimum = minimum;
  9460. this.maximum = maximum;
  9461. this._isLocked = false;
  9462. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  9463. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  9464. }
  9465. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  9466. get: function () {
  9467. return this._isLocked;
  9468. },
  9469. set: function (value) {
  9470. this._isLocked = value;
  9471. },
  9472. enumerable: true,
  9473. configurable: true
  9474. });
  9475. // Methods
  9476. BoundingInfo.prototype.update = function (world) {
  9477. if (this._isLocked) {
  9478. return;
  9479. }
  9480. this.boundingBox._update(world);
  9481. this.boundingSphere._update(world);
  9482. };
  9483. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  9484. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  9485. return false;
  9486. return this.boundingBox.isInFrustum(frustumPlanes);
  9487. };
  9488. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9489. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  9490. };
  9491. BoundingInfo.prototype._checkCollision = function (collider) {
  9492. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  9493. };
  9494. BoundingInfo.prototype.intersectsPoint = function (point) {
  9495. if (!this.boundingSphere.centerWorld) {
  9496. return false;
  9497. }
  9498. if (!this.boundingSphere.intersectsPoint(point)) {
  9499. return false;
  9500. }
  9501. if (!this.boundingBox.intersectsPoint(point)) {
  9502. return false;
  9503. }
  9504. return true;
  9505. };
  9506. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  9507. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  9508. return false;
  9509. }
  9510. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  9511. return false;
  9512. }
  9513. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  9514. return false;
  9515. }
  9516. if (!precise) {
  9517. return true;
  9518. }
  9519. var box0 = this.boundingBox;
  9520. var box1 = boundingInfo.boundingBox;
  9521. if (!axisOverlap(box0.directions[0], box0, box1))
  9522. return false;
  9523. if (!axisOverlap(box0.directions[1], box0, box1))
  9524. return false;
  9525. if (!axisOverlap(box0.directions[2], box0, box1))
  9526. return false;
  9527. if (!axisOverlap(box1.directions[0], box0, box1))
  9528. return false;
  9529. if (!axisOverlap(box1.directions[1], box0, box1))
  9530. return false;
  9531. if (!axisOverlap(box1.directions[2], box0, box1))
  9532. return false;
  9533. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  9534. return false;
  9535. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  9536. return false;
  9537. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  9538. return false;
  9539. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  9540. return false;
  9541. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  9542. return false;
  9543. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  9544. return false;
  9545. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  9546. return false;
  9547. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  9548. return false;
  9549. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  9550. return false;
  9551. return true;
  9552. };
  9553. return BoundingInfo;
  9554. })();
  9555. BABYLON.BoundingInfo = BoundingInfo;
  9556. })(BABYLON || (BABYLON = {}));
  9557. var BABYLON;
  9558. (function (BABYLON) {
  9559. var Ray = (function () {
  9560. function Ray(origin, direction, length) {
  9561. if (length === void 0) { length = Number.MAX_VALUE; }
  9562. this.origin = origin;
  9563. this.direction = direction;
  9564. this.length = length;
  9565. }
  9566. // Methods
  9567. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  9568. var d = 0.0;
  9569. var maxValue = Number.MAX_VALUE;
  9570. var inv;
  9571. var min;
  9572. var max;
  9573. var temp;
  9574. if (Math.abs(this.direction.x) < 0.0000001) {
  9575. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  9576. return false;
  9577. }
  9578. }
  9579. else {
  9580. inv = 1.0 / this.direction.x;
  9581. min = (minimum.x - this.origin.x) * inv;
  9582. max = (maximum.x - this.origin.x) * inv;
  9583. if (max === -Infinity) {
  9584. max = Infinity;
  9585. }
  9586. if (min > max) {
  9587. temp = min;
  9588. min = max;
  9589. max = temp;
  9590. }
  9591. d = Math.max(min, d);
  9592. maxValue = Math.min(max, maxValue);
  9593. if (d > maxValue) {
  9594. return false;
  9595. }
  9596. }
  9597. if (Math.abs(this.direction.y) < 0.0000001) {
  9598. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  9599. return false;
  9600. }
  9601. }
  9602. else {
  9603. inv = 1.0 / this.direction.y;
  9604. min = (minimum.y - this.origin.y) * inv;
  9605. max = (maximum.y - this.origin.y) * inv;
  9606. if (max === -Infinity) {
  9607. max = Infinity;
  9608. }
  9609. if (min > max) {
  9610. temp = min;
  9611. min = max;
  9612. max = temp;
  9613. }
  9614. d = Math.max(min, d);
  9615. maxValue = Math.min(max, maxValue);
  9616. if (d > maxValue) {
  9617. return false;
  9618. }
  9619. }
  9620. if (Math.abs(this.direction.z) < 0.0000001) {
  9621. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  9622. return false;
  9623. }
  9624. }
  9625. else {
  9626. inv = 1.0 / this.direction.z;
  9627. min = (minimum.z - this.origin.z) * inv;
  9628. max = (maximum.z - this.origin.z) * inv;
  9629. if (max === -Infinity) {
  9630. max = Infinity;
  9631. }
  9632. if (min > max) {
  9633. temp = min;
  9634. min = max;
  9635. max = temp;
  9636. }
  9637. d = Math.max(min, d);
  9638. maxValue = Math.min(max, maxValue);
  9639. if (d > maxValue) {
  9640. return false;
  9641. }
  9642. }
  9643. return true;
  9644. };
  9645. Ray.prototype.intersectsBox = function (box) {
  9646. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  9647. };
  9648. Ray.prototype.intersectsSphere = function (sphere) {
  9649. var x = sphere.center.x - this.origin.x;
  9650. var y = sphere.center.y - this.origin.y;
  9651. var z = sphere.center.z - this.origin.z;
  9652. var pyth = (x * x) + (y * y) + (z * z);
  9653. var rr = sphere.radius * sphere.radius;
  9654. if (pyth <= rr) {
  9655. return true;
  9656. }
  9657. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  9658. if (dot < 0.0) {
  9659. return false;
  9660. }
  9661. var temp = pyth - (dot * dot);
  9662. return temp <= rr;
  9663. };
  9664. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  9665. if (!this._edge1) {
  9666. this._edge1 = BABYLON.Vector3.Zero();
  9667. this._edge2 = BABYLON.Vector3.Zero();
  9668. this._pvec = BABYLON.Vector3.Zero();
  9669. this._tvec = BABYLON.Vector3.Zero();
  9670. this._qvec = BABYLON.Vector3.Zero();
  9671. }
  9672. vertex1.subtractToRef(vertex0, this._edge1);
  9673. vertex2.subtractToRef(vertex0, this._edge2);
  9674. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  9675. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  9676. if (det === 0) {
  9677. return null;
  9678. }
  9679. var invdet = 1 / det;
  9680. this.origin.subtractToRef(vertex0, this._tvec);
  9681. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  9682. if (bu < 0 || bu > 1.0) {
  9683. return null;
  9684. }
  9685. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  9686. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  9687. if (bv < 0 || bu + bv > 1.0) {
  9688. return null;
  9689. }
  9690. //check if the distance is longer than the predefined length.
  9691. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  9692. if (distance > this.length) {
  9693. return null;
  9694. }
  9695. return new BABYLON.IntersectionInfo(bu, bv, distance);
  9696. };
  9697. Ray.prototype.intersectsPlane = function (plane) {
  9698. var distance;
  9699. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  9700. if (Math.abs(result1) < 9.99999997475243E-07) {
  9701. return null;
  9702. }
  9703. else {
  9704. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  9705. distance = (-plane.d - result2) / result1;
  9706. if (distance < 0.0) {
  9707. if (distance < -9.99999997475243E-07) {
  9708. return null;
  9709. }
  9710. else {
  9711. return 0;
  9712. }
  9713. }
  9714. return distance;
  9715. }
  9716. };
  9717. /**
  9718. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  9719. * @param sega the first point of the segment to test the intersection against
  9720. * @param segb the second point of the segment to test the intersection against
  9721. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  9722. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  9723. */
  9724. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  9725. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  9726. var u = segb.subtract(sega);
  9727. var v = rsegb.subtract(this.origin);
  9728. var w = sega.subtract(this.origin);
  9729. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  9730. var b = BABYLON.Vector3.Dot(u, v);
  9731. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  9732. var d = BABYLON.Vector3.Dot(u, w);
  9733. var e = BABYLON.Vector3.Dot(v, w);
  9734. var D = a * c - b * b; // always >= 0
  9735. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  9736. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  9737. // compute the line parameters of the two closest points
  9738. if (D < Ray.smallnum) {
  9739. sN = 0.0; // force using point P0 on segment S1
  9740. sD = 1.0; // to prevent possible division by 0.0 later
  9741. tN = e;
  9742. tD = c;
  9743. }
  9744. else {
  9745. sN = (b * e - c * d);
  9746. tN = (a * e - b * d);
  9747. if (sN < 0.0) {
  9748. sN = 0.0;
  9749. tN = e;
  9750. tD = c;
  9751. }
  9752. else if (sN > sD) {
  9753. sN = sD;
  9754. tN = e + b;
  9755. tD = c;
  9756. }
  9757. }
  9758. if (tN < 0.0) {
  9759. tN = 0.0;
  9760. // recompute sc for this edge
  9761. if (-d < 0.0) {
  9762. sN = 0.0;
  9763. }
  9764. else if (-d > a)
  9765. sN = sD;
  9766. else {
  9767. sN = -d;
  9768. sD = a;
  9769. }
  9770. }
  9771. else if (tN > tD) {
  9772. tN = tD;
  9773. // recompute sc for this edge
  9774. if ((-d + b) < 0.0) {
  9775. sN = 0;
  9776. }
  9777. else if ((-d + b) > a) {
  9778. sN = sD;
  9779. }
  9780. else {
  9781. sN = (-d + b);
  9782. sD = a;
  9783. }
  9784. }
  9785. // finally do the division to get sc and tc
  9786. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  9787. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  9788. // get the difference of the two closest points
  9789. var qtc = v.multiplyByFloats(tc, tc, tc);
  9790. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  9791. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  9792. if (isIntersected) {
  9793. return qtc.length();
  9794. }
  9795. return -1;
  9796. };
  9797. // Statics
  9798. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  9799. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  9800. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  9801. var direction = end.subtract(start);
  9802. direction.normalize();
  9803. return new Ray(start, direction);
  9804. };
  9805. /**
  9806. * 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
  9807. * transformed to the given world matrix.
  9808. * @param origin The origin point
  9809. * @param end The end point
  9810. * @param world a matrix to transform the ray to. Default is the identity matrix.
  9811. */
  9812. Ray.CreateNewFromTo = function (origin, end, world) {
  9813. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  9814. var direction = end.subtract(origin);
  9815. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  9816. direction.normalize();
  9817. return Ray.Transform(new Ray(origin, direction, length), world);
  9818. };
  9819. Ray.Transform = function (ray, matrix) {
  9820. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  9821. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  9822. newDirection.normalize();
  9823. return new Ray(newOrigin, newDirection, ray.length);
  9824. };
  9825. Ray.smallnum = 0.00000001;
  9826. Ray.rayl = 10e8;
  9827. return Ray;
  9828. })();
  9829. BABYLON.Ray = Ray;
  9830. })(BABYLON || (BABYLON = {}));
  9831. var BABYLON;
  9832. (function (BABYLON) {
  9833. var AbstractMesh = (function (_super) {
  9834. __extends(AbstractMesh, _super);
  9835. // Constructor
  9836. function AbstractMesh(name, scene) {
  9837. var _this = this;
  9838. _super.call(this, name, scene);
  9839. // Events
  9840. /**
  9841. * An event triggered when the mesh is disposed.
  9842. * @type {BABYLON.Observable}
  9843. */
  9844. this.onDisposeObservable = new BABYLON.Observable();
  9845. /**
  9846. * An event triggered when this mesh collides with another one
  9847. * @type {BABYLON.Observable}
  9848. */
  9849. this.onCollideObservable = new BABYLON.Observable();
  9850. /**
  9851. * An event triggered when the collision's position changes
  9852. * @type {BABYLON.Observable}
  9853. */
  9854. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  9855. /**
  9856. * An event triggered after the world matrix is updated
  9857. * @type {BABYLON.Observable}
  9858. */
  9859. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  9860. // Properties
  9861. this.definedFacingForward = true; // orientation for POV movement & rotation
  9862. this.position = new BABYLON.Vector3(0, 0, 0);
  9863. this._rotation = new BABYLON.Vector3(0, 0, 0);
  9864. this._scaling = new BABYLON.Vector3(1, 1, 1);
  9865. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9866. this.visibility = 1.0;
  9867. this.alphaIndex = Number.MAX_VALUE;
  9868. this.infiniteDistance = false;
  9869. this.isVisible = true;
  9870. this.isPickable = true;
  9871. this.showBoundingBox = false;
  9872. this.showSubMeshesBoundingBox = false;
  9873. this.isBlocker = false;
  9874. this.renderingGroupId = 0;
  9875. this.receiveShadows = false;
  9876. this.renderOutline = false;
  9877. this.outlineColor = BABYLON.Color3.Red();
  9878. this.outlineWidth = 0.02;
  9879. this.renderOverlay = false;
  9880. this.overlayColor = BABYLON.Color3.Red();
  9881. this.overlayAlpha = 0.5;
  9882. this.hasVertexAlpha = false;
  9883. this.useVertexColors = true;
  9884. this.applyFog = true;
  9885. this.computeBonesUsingShaders = true;
  9886. this.scalingDeterminant = 1;
  9887. this.numBoneInfluencers = 4;
  9888. this.useOctreeForRenderingSelection = true;
  9889. this.useOctreeForPicking = true;
  9890. this.useOctreeForCollisions = true;
  9891. this.layerMask = 0x0FFFFFFF;
  9892. this.alwaysSelectAsActiveMesh = false;
  9893. // Collisions
  9894. this._checkCollisions = false;
  9895. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9896. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9897. this._collider = new BABYLON.Collider();
  9898. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9899. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9900. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9901. // Edges
  9902. this.edgesWidth = 1;
  9903. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  9904. // Cache
  9905. this._localWorld = BABYLON.Matrix.Zero();
  9906. this._worldMatrix = BABYLON.Matrix.Zero();
  9907. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9908. this._absolutePosition = BABYLON.Vector3.Zero();
  9909. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9910. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9911. this._isDirty = false;
  9912. this._pivotMatrix = BABYLON.Matrix.Identity();
  9913. this._isDisposed = false;
  9914. this._renderId = 0;
  9915. this._intersectionsInProgress = new Array();
  9916. this._isWorldMatrixFrozen = false;
  9917. this._unIndexed = false;
  9918. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  9919. if (collidedMesh === void 0) { collidedMesh = null; }
  9920. //TODO move this to the collision coordinator!
  9921. if (_this.getScene().workerCollisions)
  9922. newPosition.multiplyInPlace(_this._collider.radius);
  9923. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  9924. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9925. _this.position.addInPlace(_this._diffPositionForCollisions);
  9926. }
  9927. if (collidedMesh) {
  9928. _this.onCollideObservable.notifyObservers(collidedMesh);
  9929. }
  9930. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  9931. };
  9932. scene.addMesh(this);
  9933. }
  9934. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9935. get: function () {
  9936. return AbstractMesh._BILLBOARDMODE_NONE;
  9937. },
  9938. enumerable: true,
  9939. configurable: true
  9940. });
  9941. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9942. get: function () {
  9943. return AbstractMesh._BILLBOARDMODE_X;
  9944. },
  9945. enumerable: true,
  9946. configurable: true
  9947. });
  9948. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9949. get: function () {
  9950. return AbstractMesh._BILLBOARDMODE_Y;
  9951. },
  9952. enumerable: true,
  9953. configurable: true
  9954. });
  9955. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9956. get: function () {
  9957. return AbstractMesh._BILLBOARDMODE_Z;
  9958. },
  9959. enumerable: true,
  9960. configurable: true
  9961. });
  9962. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9963. get: function () {
  9964. return AbstractMesh._BILLBOARDMODE_ALL;
  9965. },
  9966. enumerable: true,
  9967. configurable: true
  9968. });
  9969. Object.defineProperty(AbstractMesh.prototype, "onDispose", {
  9970. set: function (callback) {
  9971. if (this._onDisposeObserver) {
  9972. this.onDisposeObservable.remove(this._onDisposeObserver);
  9973. }
  9974. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9975. },
  9976. enumerable: true,
  9977. configurable: true
  9978. });
  9979. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  9980. set: function (callback) {
  9981. if (this._onCollideObserver) {
  9982. this.onCollideObservable.remove(this._onCollideObserver);
  9983. }
  9984. this._onCollideObserver = this.onCollideObservable.add(callback);
  9985. },
  9986. enumerable: true,
  9987. configurable: true
  9988. });
  9989. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  9990. set: function (callback) {
  9991. if (this._onCollisionPositionChangeObserver) {
  9992. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  9993. }
  9994. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  9995. },
  9996. enumerable: true,
  9997. configurable: true
  9998. });
  9999. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  10000. get: function () {
  10001. return this._skeleton;
  10002. },
  10003. set: function (value) {
  10004. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  10005. this._skeleton._unregisterMeshWithPoseMatrix(this);
  10006. }
  10007. if (value && value.needInitialSkinMatrix) {
  10008. value._registerMeshWithPoseMatrix(this);
  10009. }
  10010. this._skeleton = value;
  10011. if (!this._skeleton) {
  10012. this._bonesTransformMatrices = null;
  10013. }
  10014. },
  10015. enumerable: true,
  10016. configurable: true
  10017. });
  10018. /**
  10019. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10020. */
  10021. AbstractMesh.prototype.toString = function (fullDetails) {
  10022. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  10023. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  10024. if (this._skeleton) {
  10025. ret += ", skeleton: " + this._skeleton.name;
  10026. }
  10027. if (fullDetails) {
  10028. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  10029. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  10030. }
  10031. return ret;
  10032. };
  10033. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  10034. /**
  10035. * Getting the rotation object.
  10036. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  10037. */
  10038. get: function () {
  10039. return this._rotation;
  10040. },
  10041. set: function (newRotation) {
  10042. this._rotation = newRotation;
  10043. },
  10044. enumerable: true,
  10045. configurable: true
  10046. });
  10047. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  10048. get: function () {
  10049. return this._scaling;
  10050. },
  10051. set: function (newScaling) {
  10052. this._scaling = newScaling;
  10053. if (this.physicsImpostor) {
  10054. this.physicsImpostor.forceUpdate();
  10055. }
  10056. },
  10057. enumerable: true,
  10058. configurable: true
  10059. });
  10060. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  10061. get: function () {
  10062. return this._rotationQuaternion;
  10063. },
  10064. set: function (quaternion) {
  10065. this._rotationQuaternion = quaternion;
  10066. //reset the rotation vector.
  10067. if (quaternion && this.rotation.length()) {
  10068. this.rotation.copyFromFloats(0, 0, 0);
  10069. }
  10070. },
  10071. enumerable: true,
  10072. configurable: true
  10073. });
  10074. // Methods
  10075. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  10076. this._poseMatrix.copyFrom(matrix);
  10077. };
  10078. AbstractMesh.prototype.getPoseMatrix = function () {
  10079. return this._poseMatrix;
  10080. };
  10081. AbstractMesh.prototype.disableEdgesRendering = function () {
  10082. if (this._edgesRenderer !== undefined) {
  10083. this._edgesRenderer.dispose();
  10084. this._edgesRenderer = undefined;
  10085. }
  10086. };
  10087. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  10088. if (epsilon === void 0) { epsilon = 0.95; }
  10089. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  10090. this.disableEdgesRendering();
  10091. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  10092. };
  10093. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10094. get: function () {
  10095. return false;
  10096. },
  10097. enumerable: true,
  10098. configurable: true
  10099. });
  10100. AbstractMesh.prototype.getLOD = function (camera) {
  10101. return this;
  10102. };
  10103. AbstractMesh.prototype.getTotalVertices = function () {
  10104. return 0;
  10105. };
  10106. AbstractMesh.prototype.getIndices = function () {
  10107. return null;
  10108. };
  10109. AbstractMesh.prototype.getVerticesData = function (kind) {
  10110. return null;
  10111. };
  10112. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10113. return false;
  10114. };
  10115. AbstractMesh.prototype.getBoundingInfo = function () {
  10116. if (this._masterMesh) {
  10117. return this._masterMesh.getBoundingInfo();
  10118. }
  10119. if (!this._boundingInfo) {
  10120. this._updateBoundingInfo();
  10121. }
  10122. return this._boundingInfo;
  10123. };
  10124. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  10125. this._boundingInfo = boundingInfo;
  10126. };
  10127. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10128. get: function () {
  10129. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10130. },
  10131. enumerable: true,
  10132. configurable: true
  10133. });
  10134. AbstractMesh.prototype._preActivate = function () {
  10135. };
  10136. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  10137. };
  10138. AbstractMesh.prototype._activate = function (renderId) {
  10139. this._renderId = renderId;
  10140. };
  10141. AbstractMesh.prototype.getWorldMatrix = function () {
  10142. if (this._masterMesh) {
  10143. return this._masterMesh.getWorldMatrix();
  10144. }
  10145. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10146. this.computeWorldMatrix();
  10147. }
  10148. return this._worldMatrix;
  10149. };
  10150. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10151. get: function () {
  10152. return this._worldMatrix;
  10153. },
  10154. enumerable: true,
  10155. configurable: true
  10156. });
  10157. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10158. get: function () {
  10159. return this._absolutePosition;
  10160. },
  10161. enumerable: true,
  10162. configurable: true
  10163. });
  10164. AbstractMesh.prototype.freezeWorldMatrix = function () {
  10165. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  10166. this.computeWorldMatrix(true);
  10167. this._isWorldMatrixFrozen = true;
  10168. };
  10169. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  10170. this._isWorldMatrixFrozen = false;
  10171. this.computeWorldMatrix(true);
  10172. };
  10173. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  10174. get: function () {
  10175. return this._isWorldMatrixFrozen;
  10176. },
  10177. enumerable: true,
  10178. configurable: true
  10179. });
  10180. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10181. axis.normalize();
  10182. if (!this.rotationQuaternion) {
  10183. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10184. this.rotation = BABYLON.Vector3.Zero();
  10185. }
  10186. var rotationQuaternion;
  10187. if (!space || space === BABYLON.Space.LOCAL) {
  10188. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10189. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  10190. }
  10191. else {
  10192. if (this.parent) {
  10193. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10194. invertParentWorldMatrix.invert();
  10195. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10196. }
  10197. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10198. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  10199. }
  10200. };
  10201. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10202. var displacementVector = axis.scale(distance);
  10203. if (!space || space === BABYLON.Space.LOCAL) {
  10204. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10205. this.setPositionWithLocalVector(tempV3);
  10206. }
  10207. else {
  10208. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10209. }
  10210. };
  10211. AbstractMesh.prototype.getAbsolutePosition = function () {
  10212. this.computeWorldMatrix();
  10213. return this._absolutePosition;
  10214. };
  10215. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10216. if (!absolutePosition) {
  10217. return;
  10218. }
  10219. var absolutePositionX;
  10220. var absolutePositionY;
  10221. var absolutePositionZ;
  10222. if (absolutePosition.x === undefined) {
  10223. if (arguments.length < 3) {
  10224. return;
  10225. }
  10226. absolutePositionX = arguments[0];
  10227. absolutePositionY = arguments[1];
  10228. absolutePositionZ = arguments[2];
  10229. }
  10230. else {
  10231. absolutePositionX = absolutePosition.x;
  10232. absolutePositionY = absolutePosition.y;
  10233. absolutePositionZ = absolutePosition.z;
  10234. }
  10235. if (this.parent) {
  10236. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10237. invertParentWorldMatrix.invert();
  10238. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10239. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10240. }
  10241. else {
  10242. this.position.x = absolutePositionX;
  10243. this.position.y = absolutePositionY;
  10244. this.position.z = absolutePositionZ;
  10245. }
  10246. };
  10247. // ================================== Point of View Movement =================================
  10248. /**
  10249. * Perform relative position change from the point of view of behind the front of the mesh.
  10250. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10251. * Supports definition of mesh facing forward or backward.
  10252. * @param {number} amountRight
  10253. * @param {number} amountUp
  10254. * @param {number} amountForward
  10255. */
  10256. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10257. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10258. };
  10259. /**
  10260. * Calculate relative position change from the point of view of behind the front of the mesh.
  10261. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10262. * Supports definition of mesh facing forward or backward.
  10263. * @param {number} amountRight
  10264. * @param {number} amountUp
  10265. * @param {number} amountForward
  10266. */
  10267. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10268. var rotMatrix = new BABYLON.Matrix();
  10269. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10270. rotQuaternion.toRotationMatrix(rotMatrix);
  10271. var translationDelta = BABYLON.Vector3.Zero();
  10272. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10273. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10274. return translationDelta;
  10275. };
  10276. // ================================== Point of View Rotation =================================
  10277. /**
  10278. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10279. * Supports definition of mesh facing forward or backward.
  10280. * @param {number} flipBack
  10281. * @param {number} twirlClockwise
  10282. * @param {number} tiltRight
  10283. */
  10284. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10285. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10286. };
  10287. /**
  10288. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10289. * Supports definition of mesh facing forward or backward.
  10290. * @param {number} flipBack
  10291. * @param {number} twirlClockwise
  10292. * @param {number} tiltRight
  10293. */
  10294. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10295. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10296. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10297. };
  10298. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10299. this._pivotMatrix = matrix;
  10300. this._cache.pivotMatrixUpdated = true;
  10301. };
  10302. AbstractMesh.prototype.getPivotMatrix = function () {
  10303. return this._pivotMatrix;
  10304. };
  10305. AbstractMesh.prototype._isSynchronized = function () {
  10306. if (this._isDirty) {
  10307. return false;
  10308. }
  10309. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10310. return false;
  10311. if (this._cache.pivotMatrixUpdated) {
  10312. return false;
  10313. }
  10314. if (this.infiniteDistance) {
  10315. return false;
  10316. }
  10317. if (!this._cache.position.equals(this.position))
  10318. return false;
  10319. if (this.rotationQuaternion) {
  10320. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10321. return false;
  10322. }
  10323. if (!this._cache.rotation.equals(this.rotation))
  10324. return false;
  10325. if (!this._cache.scaling.equals(this.scaling))
  10326. return false;
  10327. return true;
  10328. };
  10329. AbstractMesh.prototype._initCache = function () {
  10330. _super.prototype._initCache.call(this);
  10331. this._cache.localMatrixUpdated = false;
  10332. this._cache.position = BABYLON.Vector3.Zero();
  10333. this._cache.scaling = BABYLON.Vector3.Zero();
  10334. this._cache.rotation = BABYLON.Vector3.Zero();
  10335. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10336. this._cache.billboardMode = -1;
  10337. };
  10338. AbstractMesh.prototype.markAsDirty = function (property) {
  10339. if (property === "rotation") {
  10340. this.rotationQuaternion = null;
  10341. }
  10342. this._currentRenderId = Number.MAX_VALUE;
  10343. this._isDirty = true;
  10344. };
  10345. AbstractMesh.prototype._updateBoundingInfo = function () {
  10346. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10347. this._boundingInfo.update(this.worldMatrixFromCache);
  10348. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10349. };
  10350. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10351. if (!this.subMeshes) {
  10352. return;
  10353. }
  10354. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10355. var subMesh = this.subMeshes[subIndex];
  10356. if (!subMesh.IsGlobal) {
  10357. subMesh.updateBoundingInfo(matrix);
  10358. }
  10359. }
  10360. };
  10361. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10362. if (this._isWorldMatrixFrozen) {
  10363. return this._worldMatrix;
  10364. }
  10365. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10366. this._currentRenderId = this.getScene().getRenderId();
  10367. return this._worldMatrix;
  10368. }
  10369. this._cache.position.copyFrom(this.position);
  10370. this._cache.scaling.copyFrom(this.scaling);
  10371. this._cache.pivotMatrixUpdated = false;
  10372. this._cache.billboardMode = this.billboardMode;
  10373. this._currentRenderId = this.getScene().getRenderId();
  10374. this._isDirty = false;
  10375. // Scaling
  10376. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  10377. // Rotation
  10378. //rotate, if quaternion is set and rotation was used
  10379. if (this.rotationQuaternion) {
  10380. var len = this.rotation.length();
  10381. if (len) {
  10382. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  10383. this.rotation.copyFromFloats(0, 0, 0);
  10384. }
  10385. }
  10386. if (this.rotationQuaternion) {
  10387. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  10388. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10389. }
  10390. else {
  10391. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  10392. this._cache.rotation.copyFrom(this.rotation);
  10393. }
  10394. // Translation
  10395. if (this.infiniteDistance && !this.parent) {
  10396. var camera = this.getScene().activeCamera;
  10397. if (camera) {
  10398. var cameraWorldMatrix = camera.getWorldMatrix();
  10399. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10400. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  10401. }
  10402. }
  10403. else {
  10404. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  10405. }
  10406. // Composing transformations
  10407. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  10408. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  10409. // Billboarding
  10410. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10411. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  10412. var localPosition = BABYLON.Tmp.Vector3[0];
  10413. if (this.parent && this.parent.getWorldMatrix) {
  10414. this._markSyncedWithParent();
  10415. var parentMatrix;
  10416. if (this._meshToBoneReferal) {
  10417. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10418. parentMatrix = BABYLON.Tmp.Matrix[6];
  10419. }
  10420. else {
  10421. parentMatrix = this.parent.getWorldMatrix();
  10422. }
  10423. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  10424. localPosition = BABYLON.Tmp.Vector3[1];
  10425. }
  10426. var zero = this.getScene().activeCamera.globalPosition.clone();
  10427. if (this.parent && this.parent.position) {
  10428. localPosition.addInPlace(this.parent.position);
  10429. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  10430. }
  10431. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  10432. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10433. zero.x = localPosition.x + BABYLON.Epsilon;
  10434. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10435. zero.y = localPosition.y + BABYLON.Epsilon;
  10436. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10437. zero.z = localPosition.z + BABYLON.Epsilon;
  10438. }
  10439. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  10440. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  10441. BABYLON.Tmp.Matrix[3].invert();
  10442. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  10443. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  10444. }
  10445. // Local world
  10446. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  10447. // Parent
  10448. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10449. this._markSyncedWithParent();
  10450. if (this._meshToBoneReferal) {
  10451. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10452. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  10453. }
  10454. else {
  10455. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10456. }
  10457. }
  10458. else {
  10459. this._worldMatrix.copyFrom(this._localWorld);
  10460. }
  10461. // Bounding info
  10462. this._updateBoundingInfo();
  10463. // Absolute position
  10464. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10465. // Callbacks
  10466. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  10467. if (!this._poseMatrix) {
  10468. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  10469. }
  10470. return this._worldMatrix;
  10471. };
  10472. /**
  10473. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10474. * @param func: callback function to add
  10475. */
  10476. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10477. this.onAfterWorldMatrixUpdateObservable.add(func);
  10478. };
  10479. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10480. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  10481. };
  10482. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10483. this.computeWorldMatrix();
  10484. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10485. };
  10486. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10487. this.computeWorldMatrix();
  10488. var invLocalWorldMatrix = this._localWorld.clone();
  10489. invLocalWorldMatrix.invert();
  10490. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10491. };
  10492. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10493. this.computeWorldMatrix(true);
  10494. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10495. };
  10496. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  10497. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10498. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10499. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10500. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10501. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10502. /// <returns>Mesh oriented towards targetMesh</returns>
  10503. if (yawCor === void 0) { yawCor = 0; }
  10504. if (pitchCor === void 0) { pitchCor = 0; }
  10505. if (rollCor === void 0) { rollCor = 0; }
  10506. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  10507. var dv = AbstractMesh._lookAtVectorCache;
  10508. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  10509. targetPoint.subtractToRef(pos, dv);
  10510. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10511. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10512. var pitch = Math.atan2(dv.y, len);
  10513. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  10514. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  10515. };
  10516. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  10517. this._meshToBoneReferal = affectedMesh;
  10518. this.parent = bone;
  10519. if (bone.getWorldMatrix().determinant() < 0) {
  10520. this.scalingDeterminant *= -1;
  10521. }
  10522. };
  10523. AbstractMesh.prototype.detachFromBone = function () {
  10524. if (this.parent.getWorldMatrix().determinant() < 0) {
  10525. this.scalingDeterminant *= -1;
  10526. }
  10527. this._meshToBoneReferal = null;
  10528. this.parent = null;
  10529. };
  10530. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10531. return this._boundingInfo.isInFrustum(frustumPlanes);
  10532. };
  10533. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10534. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  10535. ;
  10536. };
  10537. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10538. if (!this._boundingInfo || !mesh._boundingInfo) {
  10539. return false;
  10540. }
  10541. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10542. };
  10543. AbstractMesh.prototype.intersectsPoint = function (point) {
  10544. if (!this._boundingInfo) {
  10545. return false;
  10546. }
  10547. return this._boundingInfo.intersectsPoint(point);
  10548. };
  10549. // Physics
  10550. /**
  10551. * @Deprecated. Use new PhysicsImpostor instead.
  10552. * */
  10553. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10554. //legacy support
  10555. if (impostor.impostor) {
  10556. options = impostor;
  10557. impostor = impostor.impostor;
  10558. }
  10559. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  10560. return this.physicsImpostor.physicsBody;
  10561. };
  10562. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10563. return this.physicsImpostor;
  10564. };
  10565. /**
  10566. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  10567. */
  10568. AbstractMesh.prototype.getPhysicsMass = function () {
  10569. return this.physicsImpostor.getParam("mass");
  10570. };
  10571. /**
  10572. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  10573. */
  10574. AbstractMesh.prototype.getPhysicsFriction = function () {
  10575. return this.physicsImpostor.getParam("friction");
  10576. };
  10577. /**
  10578. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  10579. */
  10580. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10581. return this.physicsImpostor.getParam("restitution");
  10582. };
  10583. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10584. if (!camera) {
  10585. camera = this.getScene().activeCamera;
  10586. }
  10587. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10588. };
  10589. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10590. if (!camera) {
  10591. camera = this.getScene().activeCamera;
  10592. }
  10593. return this.absolutePosition.subtract(camera.position).length();
  10594. };
  10595. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10596. if (!this.physicsImpostor) {
  10597. return;
  10598. }
  10599. this.physicsImpostor.applyImpulse(force, contactPoint);
  10600. };
  10601. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10602. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  10603. return;
  10604. }
  10605. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  10606. mainPivot: pivot1,
  10607. connectedPivot: pivot2,
  10608. nativeParams: options
  10609. });
  10610. };
  10611. /**
  10612. * @Deprecated
  10613. */
  10614. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10615. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  10616. this.updatePhysicsBody();
  10617. };
  10618. /**
  10619. * @Deprecated
  10620. * Calling this function is not needed anymore.
  10621. * The physics engine takes care of transofmration automatically.
  10622. */
  10623. AbstractMesh.prototype.updatePhysicsBody = function () {
  10624. //Unneeded
  10625. };
  10626. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  10627. // Collisions
  10628. get: function () {
  10629. return this._checkCollisions;
  10630. },
  10631. set: function (collisionEnabled) {
  10632. this._checkCollisions = collisionEnabled;
  10633. if (this.getScene().workerCollisions) {
  10634. this.getScene().collisionCoordinator.onMeshUpdated(this);
  10635. }
  10636. },
  10637. enumerable: true,
  10638. configurable: true
  10639. });
  10640. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10641. var globalPosition = this.getAbsolutePosition();
  10642. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10643. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10644. this._collider.radius = this.ellipsoid;
  10645. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  10646. };
  10647. // Submeshes octree
  10648. /**
  10649. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10650. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10651. */
  10652. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10653. if (maxCapacity === void 0) { maxCapacity = 64; }
  10654. if (maxDepth === void 0) { maxDepth = 2; }
  10655. if (!this._submeshesOctree) {
  10656. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10657. }
  10658. this.computeWorldMatrix(true);
  10659. // Update octree
  10660. var bbox = this.getBoundingInfo().boundingBox;
  10661. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10662. return this._submeshesOctree;
  10663. };
  10664. // Collisions
  10665. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10666. this._generatePointsArray();
  10667. // Transformation
  10668. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10669. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10670. subMesh._lastColliderWorldVertices = [];
  10671. subMesh._trianglePlanes = [];
  10672. var start = subMesh.verticesStart;
  10673. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10674. for (var i = start; i < end; i++) {
  10675. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10676. }
  10677. }
  10678. // Collide
  10679. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  10680. if (collider.collisionFound) {
  10681. collider.collidedMesh = this;
  10682. }
  10683. };
  10684. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10685. var subMeshes;
  10686. var len;
  10687. // Octrees
  10688. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10689. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10690. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10691. len = intersections.length;
  10692. subMeshes = intersections.data;
  10693. }
  10694. else {
  10695. subMeshes = this.subMeshes;
  10696. len = subMeshes.length;
  10697. }
  10698. for (var index = 0; index < len; index++) {
  10699. var subMesh = subMeshes[index];
  10700. // Bounding test
  10701. if (len > 1 && !subMesh._checkCollision(collider))
  10702. continue;
  10703. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10704. }
  10705. };
  10706. AbstractMesh.prototype._checkCollision = function (collider) {
  10707. // Bounding box test
  10708. if (!this._boundingInfo._checkCollision(collider))
  10709. return;
  10710. // Transformation matrix
  10711. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10712. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10713. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10714. };
  10715. // Picking
  10716. AbstractMesh.prototype._generatePointsArray = function () {
  10717. return false;
  10718. };
  10719. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10720. var pickingInfo = new BABYLON.PickingInfo();
  10721. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10722. return pickingInfo;
  10723. }
  10724. if (!this._generatePointsArray()) {
  10725. return pickingInfo;
  10726. }
  10727. var intersectInfo = null;
  10728. // Octrees
  10729. var subMeshes;
  10730. var len;
  10731. if (this._submeshesOctree && this.useOctreeForPicking) {
  10732. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10733. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10734. len = intersections.length;
  10735. subMeshes = intersections.data;
  10736. }
  10737. else {
  10738. subMeshes = this.subMeshes;
  10739. len = subMeshes.length;
  10740. }
  10741. for (var index = 0; index < len; index++) {
  10742. var subMesh = subMeshes[index];
  10743. // Bounding test
  10744. if (len > 1 && !subMesh.canIntersects(ray))
  10745. continue;
  10746. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10747. if (currentIntersectInfo) {
  10748. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10749. intersectInfo = currentIntersectInfo;
  10750. intersectInfo.subMeshId = index;
  10751. if (fastCheck) {
  10752. break;
  10753. }
  10754. }
  10755. }
  10756. }
  10757. if (intersectInfo) {
  10758. // Get picked point
  10759. var world = this.getWorldMatrix();
  10760. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10761. var direction = ray.direction.clone();
  10762. direction = direction.scale(intersectInfo.distance);
  10763. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10764. var pickedPoint = worldOrigin.add(worldDirection);
  10765. // Return result
  10766. pickingInfo.hit = true;
  10767. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10768. pickingInfo.pickedPoint = pickedPoint;
  10769. pickingInfo.pickedMesh = this;
  10770. pickingInfo.bu = intersectInfo.bu;
  10771. pickingInfo.bv = intersectInfo.bv;
  10772. pickingInfo.faceId = intersectInfo.faceId;
  10773. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10774. return pickingInfo;
  10775. }
  10776. return pickingInfo;
  10777. };
  10778. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10779. return null;
  10780. };
  10781. AbstractMesh.prototype.releaseSubMeshes = function () {
  10782. if (this.subMeshes) {
  10783. while (this.subMeshes.length) {
  10784. this.subMeshes[0].dispose();
  10785. }
  10786. }
  10787. else {
  10788. this.subMeshes = new Array();
  10789. }
  10790. };
  10791. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10792. var _this = this;
  10793. var index;
  10794. // Action manager
  10795. if (this.actionManager) {
  10796. this.actionManager.dispose();
  10797. this.actionManager = null;
  10798. }
  10799. // Skeleton
  10800. this.skeleton = null;
  10801. // Animations
  10802. this.getScene().stopAnimation(this);
  10803. // Physics
  10804. if (this.physicsImpostor) {
  10805. this.physicsImpostor.dispose();
  10806. }
  10807. // Intersections in progress
  10808. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10809. var other = this._intersectionsInProgress[index];
  10810. var pos = other._intersectionsInProgress.indexOf(this);
  10811. other._intersectionsInProgress.splice(pos, 1);
  10812. }
  10813. this._intersectionsInProgress = [];
  10814. // Lights
  10815. var lights = this.getScene().lights;
  10816. lights.forEach(function (light) {
  10817. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  10818. if (meshIndex !== -1) {
  10819. light.includedOnlyMeshes.splice(meshIndex, 1);
  10820. }
  10821. meshIndex = light.excludedMeshes.indexOf(_this);
  10822. if (meshIndex !== -1) {
  10823. light.excludedMeshes.splice(meshIndex, 1);
  10824. }
  10825. // Shadow generators
  10826. var generator = light.getShadowGenerator();
  10827. if (generator) {
  10828. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  10829. if (meshIndex !== -1) {
  10830. generator.getShadowMap().renderList.splice(meshIndex, 1);
  10831. }
  10832. }
  10833. });
  10834. // Edges
  10835. if (this._edgesRenderer) {
  10836. this._edgesRenderer.dispose();
  10837. this._edgesRenderer = null;
  10838. }
  10839. // SubMeshes
  10840. this.releaseSubMeshes();
  10841. // Remove from scene
  10842. this.getScene().removeMesh(this);
  10843. if (!doNotRecurse) {
  10844. // Particles
  10845. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10846. if (this.getScene().particleSystems[index].emitter === this) {
  10847. this.getScene().particleSystems[index].dispose();
  10848. index--;
  10849. }
  10850. }
  10851. // Children
  10852. var objects = this.getDescendants(true);
  10853. for (index = 0; index < objects.length; index++) {
  10854. objects[index].dispose();
  10855. }
  10856. }
  10857. else {
  10858. var childMeshes = this.getChildMeshes(true);
  10859. for (index = 0; index < childMeshes.length; index++) {
  10860. var child = childMeshes[index];
  10861. child.parent = null;
  10862. child.computeWorldMatrix(true);
  10863. }
  10864. }
  10865. _super.prototype.dispose.call(this);
  10866. this.onAfterWorldMatrixUpdateObservable.clear();
  10867. this.onCollideObservable.clear();
  10868. this.onCollisionPositionChangeObservable.clear();
  10869. this._isDisposed = true;
  10870. // Callback
  10871. this.onDisposeObservable.notifyObservers(this);
  10872. this.onDisposeObservable.clear();
  10873. };
  10874. // Statics
  10875. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10876. AbstractMesh._BILLBOARDMODE_X = 1;
  10877. AbstractMesh._BILLBOARDMODE_Y = 2;
  10878. AbstractMesh._BILLBOARDMODE_Z = 4;
  10879. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10880. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  10881. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  10882. return AbstractMesh;
  10883. })(BABYLON.Node);
  10884. BABYLON.AbstractMesh = AbstractMesh;
  10885. })(BABYLON || (BABYLON = {}));
  10886. var BABYLON;
  10887. (function (BABYLON) {
  10888. var Light = (function (_super) {
  10889. __extends(Light, _super);
  10890. function Light(name, scene) {
  10891. _super.call(this, name, scene);
  10892. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  10893. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  10894. this.intensity = 1.0;
  10895. this.range = Number.MAX_VALUE;
  10896. this.includeOnlyWithLayerMask = 0;
  10897. this.includedOnlyMeshes = new Array();
  10898. this.excludedMeshes = new Array();
  10899. this.excludeWithLayerMask = 0;
  10900. this.lightmapMode = 0;
  10901. // PBR Properties.
  10902. this.radius = 0.00001;
  10903. this._excludedMeshesIds = new Array();
  10904. this._includedOnlyMeshesIds = new Array();
  10905. scene.addLight(this);
  10906. }
  10907. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  10908. /**
  10909. * If every light affecting the material is in this lightmapMode,
  10910. * material.lightmapTexture adds or multiplies
  10911. * (depends on material.useLightmapAsShadowmap)
  10912. * after every other light calculations.
  10913. */
  10914. get: function () {
  10915. return Light._LIGHTMAP_DEFAULT;
  10916. },
  10917. enumerable: true,
  10918. configurable: true
  10919. });
  10920. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  10921. /**
  10922. * material.lightmapTexture as only diffuse lighting from this light
  10923. * adds pnly specular lighting from this light
  10924. * adds dynamic shadows
  10925. */
  10926. get: function () {
  10927. return Light._LIGHTMAP_SPECULAR;
  10928. },
  10929. enumerable: true,
  10930. configurable: true
  10931. });
  10932. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  10933. /**
  10934. * material.lightmapTexture as only lighting
  10935. * no light calculation from this light
  10936. * only adds dynamic shadows from this light
  10937. */
  10938. get: function () {
  10939. return Light._LIGHTMAP_SHADOWSONLY;
  10940. },
  10941. enumerable: true,
  10942. configurable: true
  10943. });
  10944. /**
  10945. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10946. */
  10947. Light.prototype.toString = function (fullDetails) {
  10948. var ret = "Name: " + this.name;
  10949. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  10950. if (this.animations) {
  10951. for (var i = 0; i < this.animations.length; i++) {
  10952. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  10953. }
  10954. }
  10955. if (fullDetails) {
  10956. }
  10957. return ret;
  10958. };
  10959. Light.prototype.getShadowGenerator = function () {
  10960. return this._shadowGenerator;
  10961. };
  10962. Light.prototype.getAbsolutePosition = function () {
  10963. return BABYLON.Vector3.Zero();
  10964. };
  10965. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  10966. };
  10967. Light.prototype._getWorldMatrix = function () {
  10968. return BABYLON.Matrix.Identity();
  10969. };
  10970. Light.prototype.canAffectMesh = function (mesh) {
  10971. if (!mesh) {
  10972. return true;
  10973. }
  10974. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  10975. return false;
  10976. }
  10977. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  10978. return false;
  10979. }
  10980. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  10981. return false;
  10982. }
  10983. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  10984. return false;
  10985. }
  10986. return true;
  10987. };
  10988. Light.prototype.getWorldMatrix = function () {
  10989. this._currentRenderId = this.getScene().getRenderId();
  10990. var worldMatrix = this._getWorldMatrix();
  10991. if (this.parent && this.parent.getWorldMatrix) {
  10992. if (!this._parentedWorldMatrix) {
  10993. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  10994. }
  10995. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  10996. this._markSyncedWithParent();
  10997. return this._parentedWorldMatrix;
  10998. }
  10999. return worldMatrix;
  11000. };
  11001. Light.prototype.dispose = function () {
  11002. if (this._shadowGenerator) {
  11003. this._shadowGenerator.dispose();
  11004. this._shadowGenerator = null;
  11005. }
  11006. // Animations
  11007. this.getScene().stopAnimation(this);
  11008. // Remove from scene
  11009. this.getScene().removeLight(this);
  11010. _super.prototype.dispose.call(this);
  11011. };
  11012. Light.prototype.getTypeID = function () {
  11013. return 0;
  11014. };
  11015. Light.prototype.clone = function (name) {
  11016. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  11017. };
  11018. Light.prototype.serialize = function () {
  11019. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11020. // Type
  11021. serializationObject.type = this.getTypeID();
  11022. // Parent
  11023. if (this.parent) {
  11024. serializationObject.parentId = this.parent.id;
  11025. }
  11026. // Inclusion / exclusions
  11027. if (this.excludedMeshes.length > 0) {
  11028. serializationObject.excludedMeshesIds = [];
  11029. this.excludedMeshes.forEach(function (mesh) {
  11030. serializationObject.excludedMeshesIds.push(mesh.id);
  11031. });
  11032. }
  11033. if (this.includedOnlyMeshes.length > 0) {
  11034. serializationObject.includedOnlyMeshesIds = [];
  11035. this.includedOnlyMeshes.forEach(function (mesh) {
  11036. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  11037. });
  11038. }
  11039. // Animations
  11040. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11041. serializationObject.ranges = this.serializeAnimationRanges();
  11042. return serializationObject;
  11043. };
  11044. Light.GetConstructorFromName = function (type, name, scene) {
  11045. switch (type) {
  11046. case 0:
  11047. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  11048. case 1:
  11049. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  11050. case 2:
  11051. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  11052. case 3:
  11053. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  11054. }
  11055. };
  11056. Light.Parse = function (parsedLight, scene) {
  11057. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  11058. // Inclusion / exclusions
  11059. if (parsedLight.excludedMeshesIds) {
  11060. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  11061. }
  11062. if (parsedLight.includedOnlyMeshesIds) {
  11063. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  11064. }
  11065. // Parent
  11066. if (parsedLight.parentId) {
  11067. light._waitingParentId = parsedLight.parentId;
  11068. }
  11069. // Animations
  11070. if (parsedLight.animations) {
  11071. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  11072. var parsedAnimation = parsedLight.animations[animationIndex];
  11073. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11074. }
  11075. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  11076. }
  11077. if (parsedLight.autoAnimate) {
  11078. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  11079. }
  11080. return light;
  11081. };
  11082. //lightmapMode Consts
  11083. Light._LIGHTMAP_DEFAULT = 0;
  11084. Light._LIGHTMAP_SPECULAR = 1;
  11085. Light._LIGHTMAP_SHADOWSONLY = 2;
  11086. __decorate([
  11087. BABYLON.serializeAsColor3()
  11088. ], Light.prototype, "diffuse", void 0);
  11089. __decorate([
  11090. BABYLON.serializeAsColor3()
  11091. ], Light.prototype, "specular", void 0);
  11092. __decorate([
  11093. BABYLON.serialize()
  11094. ], Light.prototype, "intensity", void 0);
  11095. __decorate([
  11096. BABYLON.serialize()
  11097. ], Light.prototype, "range", void 0);
  11098. __decorate([
  11099. BABYLON.serialize()
  11100. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  11101. __decorate([
  11102. BABYLON.serialize()
  11103. ], Light.prototype, "excludeWithLayerMask", void 0);
  11104. __decorate([
  11105. BABYLON.serialize()
  11106. ], Light.prototype, "lightmapMode", void 0);
  11107. __decorate([
  11108. BABYLON.serialize()
  11109. ], Light.prototype, "radius", void 0);
  11110. return Light;
  11111. })(BABYLON.Node);
  11112. BABYLON.Light = Light;
  11113. })(BABYLON || (BABYLON = {}));
  11114. var BABYLON;
  11115. (function (BABYLON) {
  11116. var PointLight = (function (_super) {
  11117. __extends(PointLight, _super);
  11118. function PointLight(name, position, scene) {
  11119. _super.call(this, name, scene);
  11120. this.position = position;
  11121. }
  11122. PointLight.prototype.getAbsolutePosition = function () {
  11123. return this.transformedPosition ? this.transformedPosition : this.position;
  11124. };
  11125. PointLight.prototype.computeTransformedPosition = function () {
  11126. if (this.parent && this.parent.getWorldMatrix) {
  11127. if (!this.transformedPosition) {
  11128. this.transformedPosition = BABYLON.Vector3.Zero();
  11129. }
  11130. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11131. return true;
  11132. }
  11133. return false;
  11134. };
  11135. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  11136. if (this.parent && this.parent.getWorldMatrix) {
  11137. this.computeTransformedPosition();
  11138. if (this.getScene().useRightHandedSystem) {
  11139. effect.setFloat4(positionUniformName, -this.transformedPosition.x, -this.transformedPosition.y, -this.transformedPosition.z, 0);
  11140. }
  11141. else {
  11142. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  11143. }
  11144. return;
  11145. }
  11146. if (this.getScene().useRightHandedSystem) {
  11147. effect.setFloat4(positionUniformName, -this.position.x, -this.position.y, -this.position.z, 0);
  11148. }
  11149. else {
  11150. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  11151. }
  11152. };
  11153. PointLight.prototype.needCube = function () {
  11154. return true;
  11155. };
  11156. PointLight.prototype.supportsVSM = function () {
  11157. return false;
  11158. };
  11159. PointLight.prototype.needRefreshPerFrame = function () {
  11160. return false;
  11161. };
  11162. PointLight.prototype.getShadowDirection = function (faceIndex) {
  11163. switch (faceIndex) {
  11164. case 0:
  11165. return new BABYLON.Vector3(1, 0, 0);
  11166. case 1:
  11167. return new BABYLON.Vector3(-1, 0, 0);
  11168. case 2:
  11169. return new BABYLON.Vector3(0, -1, 0);
  11170. case 3:
  11171. return new BABYLON.Vector3(0, 1, 0);
  11172. case 4:
  11173. return new BABYLON.Vector3(0, 0, 1);
  11174. case 5:
  11175. return new BABYLON.Vector3(0, 0, -1);
  11176. }
  11177. return BABYLON.Vector3.Zero();
  11178. };
  11179. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11180. var activeCamera = this.getScene().activeCamera;
  11181. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11182. };
  11183. PointLight.prototype._getWorldMatrix = function () {
  11184. if (!this._worldMatrix) {
  11185. this._worldMatrix = BABYLON.Matrix.Identity();
  11186. }
  11187. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11188. return this._worldMatrix;
  11189. };
  11190. PointLight.prototype.getTypeID = function () {
  11191. return 0;
  11192. };
  11193. __decorate([
  11194. BABYLON.serializeAsVector3()
  11195. ], PointLight.prototype, "position", void 0);
  11196. return PointLight;
  11197. })(BABYLON.Light);
  11198. BABYLON.PointLight = PointLight;
  11199. })(BABYLON || (BABYLON = {}));
  11200. var BABYLON;
  11201. (function (BABYLON) {
  11202. var SpotLight = (function (_super) {
  11203. __extends(SpotLight, _super);
  11204. function SpotLight(name, position, direction, angle, exponent, scene) {
  11205. _super.call(this, name, scene);
  11206. this.position = position;
  11207. this.direction = direction;
  11208. this.angle = angle;
  11209. this.exponent = exponent;
  11210. }
  11211. SpotLight.prototype.getAbsolutePosition = function () {
  11212. return this.transformedPosition ? this.transformedPosition : this.position;
  11213. };
  11214. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11215. var activeCamera = this.getScene().activeCamera;
  11216. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11217. };
  11218. SpotLight.prototype.needCube = function () {
  11219. return false;
  11220. };
  11221. SpotLight.prototype.supportsVSM = function () {
  11222. return true;
  11223. };
  11224. SpotLight.prototype.needRefreshPerFrame = function () {
  11225. return false;
  11226. };
  11227. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  11228. return this.direction;
  11229. };
  11230. SpotLight.prototype.setDirectionToTarget = function (target) {
  11231. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11232. return this.direction;
  11233. };
  11234. SpotLight.prototype.computeTransformedPosition = function () {
  11235. if (this.parent && this.parent.getWorldMatrix) {
  11236. if (!this.transformedPosition) {
  11237. this.transformedPosition = BABYLON.Vector3.Zero();
  11238. }
  11239. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11240. return true;
  11241. }
  11242. return false;
  11243. };
  11244. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  11245. var normalizeDirection;
  11246. if (this.parent && this.parent.getWorldMatrix) {
  11247. if (!this._transformedDirection) {
  11248. this._transformedDirection = BABYLON.Vector3.Zero();
  11249. }
  11250. this.computeTransformedPosition();
  11251. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11252. if (this.getScene().useRightHandedSystem) {
  11253. effect.setFloat4(positionUniformName, -this.transformedPosition.x, -this.transformedPosition.y, -this.transformedPosition.z, this.exponent);
  11254. }
  11255. else {
  11256. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  11257. }
  11258. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  11259. }
  11260. else {
  11261. if (this.getScene().useRightHandedSystem) {
  11262. effect.setFloat4(positionUniformName, -this.position.x, -this.position.y, -this.position.z, this.exponent);
  11263. }
  11264. else {
  11265. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  11266. }
  11267. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11268. }
  11269. if (this.getScene().useRightHandedSystem) {
  11270. effect.setFloat4(directionUniformName, -normalizeDirection.x, -normalizeDirection.y, -normalizeDirection.z, Math.cos(this.angle * 0.5));
  11271. }
  11272. else {
  11273. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  11274. }
  11275. };
  11276. SpotLight.prototype._getWorldMatrix = function () {
  11277. if (!this._worldMatrix) {
  11278. this._worldMatrix = BABYLON.Matrix.Identity();
  11279. }
  11280. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11281. return this._worldMatrix;
  11282. };
  11283. SpotLight.prototype.getTypeID = function () {
  11284. return 2;
  11285. };
  11286. __decorate([
  11287. BABYLON.serializeAsVector3()
  11288. ], SpotLight.prototype, "position", void 0);
  11289. __decorate([
  11290. BABYLON.serializeAsVector3()
  11291. ], SpotLight.prototype, "direction", void 0);
  11292. __decorate([
  11293. BABYLON.serialize()
  11294. ], SpotLight.prototype, "angle", void 0);
  11295. __decorate([
  11296. BABYLON.serialize()
  11297. ], SpotLight.prototype, "exponent", void 0);
  11298. return SpotLight;
  11299. })(BABYLON.Light);
  11300. BABYLON.SpotLight = SpotLight;
  11301. })(BABYLON || (BABYLON = {}));
  11302. var BABYLON;
  11303. (function (BABYLON) {
  11304. var HemisphericLight = (function (_super) {
  11305. __extends(HemisphericLight, _super);
  11306. function HemisphericLight(name, direction, scene) {
  11307. _super.call(this, name, scene);
  11308. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  11309. this.direction = direction;
  11310. }
  11311. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  11312. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  11313. return this.direction;
  11314. };
  11315. HemisphericLight.prototype.getShadowGenerator = function () {
  11316. return null;
  11317. };
  11318. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  11319. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11320. if (this.getScene().useRightHandedSystem) {
  11321. effect.setFloat4(directionUniformName, -normalizeDirection.x, -normalizeDirection.y, -normalizeDirection.z, 0);
  11322. }
  11323. else {
  11324. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  11325. }
  11326. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  11327. };
  11328. HemisphericLight.prototype._getWorldMatrix = function () {
  11329. if (!this._worldMatrix) {
  11330. this._worldMatrix = BABYLON.Matrix.Identity();
  11331. }
  11332. return this._worldMatrix;
  11333. };
  11334. HemisphericLight.prototype.getTypeID = function () {
  11335. return 3;
  11336. };
  11337. __decorate([
  11338. BABYLON.serializeAsColor3()
  11339. ], HemisphericLight.prototype, "groundColor", void 0);
  11340. __decorate([
  11341. BABYLON.serializeAsVector3()
  11342. ], HemisphericLight.prototype, "direction", void 0);
  11343. return HemisphericLight;
  11344. })(BABYLON.Light);
  11345. BABYLON.HemisphericLight = HemisphericLight;
  11346. })(BABYLON || (BABYLON = {}));
  11347. var BABYLON;
  11348. (function (BABYLON) {
  11349. var DirectionalLight = (function (_super) {
  11350. __extends(DirectionalLight, _super);
  11351. function DirectionalLight(name, direction, scene) {
  11352. _super.call(this, name, scene);
  11353. this.shadowOrthoScale = 0.5;
  11354. this.autoUpdateExtends = true;
  11355. // Cache
  11356. this._orthoLeft = Number.MAX_VALUE;
  11357. this._orthoRight = Number.MIN_VALUE;
  11358. this._orthoTop = Number.MIN_VALUE;
  11359. this._orthoBottom = Number.MAX_VALUE;
  11360. this.position = direction.scale(-1);
  11361. this.direction = direction;
  11362. }
  11363. DirectionalLight.prototype.getAbsolutePosition = function () {
  11364. return this.transformedPosition ? this.transformedPosition : this.position;
  11365. };
  11366. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  11367. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11368. return this.direction;
  11369. };
  11370. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11371. var activeCamera = this.getScene().activeCamera;
  11372. // Check extends
  11373. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  11374. var tempVector3 = BABYLON.Vector3.Zero();
  11375. this._orthoLeft = Number.MAX_VALUE;
  11376. this._orthoRight = Number.MIN_VALUE;
  11377. this._orthoTop = Number.MIN_VALUE;
  11378. this._orthoBottom = Number.MAX_VALUE;
  11379. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  11380. var mesh = renderList[meshIndex];
  11381. if (!mesh) {
  11382. continue;
  11383. }
  11384. var boundingInfo = mesh.getBoundingInfo();
  11385. if (!boundingInfo) {
  11386. continue;
  11387. }
  11388. var boundingBox = boundingInfo.boundingBox;
  11389. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  11390. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  11391. if (tempVector3.x < this._orthoLeft)
  11392. this._orthoLeft = tempVector3.x;
  11393. if (tempVector3.y < this._orthoBottom)
  11394. this._orthoBottom = tempVector3.y;
  11395. if (tempVector3.x > this._orthoRight)
  11396. this._orthoRight = tempVector3.x;
  11397. if (tempVector3.y > this._orthoTop)
  11398. this._orthoTop = tempVector3.y;
  11399. }
  11400. }
  11401. }
  11402. var xOffset = this._orthoRight - this._orthoLeft;
  11403. var yOffset = this._orthoTop - this._orthoBottom;
  11404. 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);
  11405. };
  11406. DirectionalLight.prototype.supportsVSM = function () {
  11407. return true;
  11408. };
  11409. DirectionalLight.prototype.needRefreshPerFrame = function () {
  11410. return true;
  11411. };
  11412. DirectionalLight.prototype.needCube = function () {
  11413. return false;
  11414. };
  11415. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  11416. return this.direction;
  11417. };
  11418. DirectionalLight.prototype.computeTransformedPosition = function () {
  11419. if (this.parent && this.parent.getWorldMatrix) {
  11420. if (!this.transformedPosition) {
  11421. this.transformedPosition = BABYLON.Vector3.Zero();
  11422. }
  11423. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11424. return true;
  11425. }
  11426. return false;
  11427. };
  11428. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  11429. if (this.parent && this.parent.getWorldMatrix) {
  11430. if (!this._transformedDirection) {
  11431. this._transformedDirection = BABYLON.Vector3.Zero();
  11432. }
  11433. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11434. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  11435. return;
  11436. }
  11437. if (this.getScene().useRightHandedSystem) {
  11438. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, -1);
  11439. }
  11440. else {
  11441. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  11442. }
  11443. };
  11444. DirectionalLight.prototype._getWorldMatrix = function () {
  11445. if (!this._worldMatrix) {
  11446. this._worldMatrix = BABYLON.Matrix.Identity();
  11447. }
  11448. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11449. return this._worldMatrix;
  11450. };
  11451. DirectionalLight.prototype.getTypeID = function () {
  11452. return 1;
  11453. };
  11454. __decorate([
  11455. BABYLON.serializeAsVector3()
  11456. ], DirectionalLight.prototype, "position", void 0);
  11457. __decorate([
  11458. BABYLON.serializeAsVector3()
  11459. ], DirectionalLight.prototype, "direction", void 0);
  11460. __decorate([
  11461. BABYLON.serialize()
  11462. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  11463. __decorate([
  11464. BABYLON.serialize()
  11465. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  11466. return DirectionalLight;
  11467. })(BABYLON.Light);
  11468. BABYLON.DirectionalLight = DirectionalLight;
  11469. })(BABYLON || (BABYLON = {}));
  11470. var BABYLON;
  11471. (function (BABYLON) {
  11472. var ShadowGenerator = (function () {
  11473. function ShadowGenerator(mapSize, light) {
  11474. var _this = this;
  11475. // Members
  11476. this._filter = ShadowGenerator.FILTER_NONE;
  11477. this.blurScale = 2;
  11478. this._blurBoxOffset = 0;
  11479. this._bias = 0.00005;
  11480. this._lightDirection = BABYLON.Vector3.Zero();
  11481. this.forceBackFacesOnly = false;
  11482. this._darkness = 0;
  11483. this._transparencyShadow = false;
  11484. this._viewMatrix = BABYLON.Matrix.Zero();
  11485. this._projectionMatrix = BABYLON.Matrix.Zero();
  11486. this._transformMatrix = BABYLON.Matrix.Zero();
  11487. this._worldViewProjection = BABYLON.Matrix.Zero();
  11488. this._currentFaceIndex = 0;
  11489. this._currentFaceIndexCache = 0;
  11490. this._useFullFloat = true;
  11491. this._light = light;
  11492. this._scene = light.getScene();
  11493. this._mapSize = mapSize;
  11494. light._shadowGenerator = this;
  11495. // Texture type fallback from float to int if not supported.
  11496. var textureType;
  11497. var caps = this._scene.getEngine().getCaps();
  11498. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  11499. this._useFullFloat = true;
  11500. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  11501. }
  11502. else {
  11503. this._useFullFloat = false;
  11504. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  11505. }
  11506. // Render target
  11507. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  11508. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11509. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11510. this._shadowMap.anisotropicFilteringLevel = 1;
  11511. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11512. this._shadowMap.renderParticles = false;
  11513. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  11514. _this._currentFaceIndex = faceIndex;
  11515. });
  11516. this._shadowMap.onAfterUnbindObservable.add(function () {
  11517. if (!_this.useBlurVarianceShadowMap) {
  11518. return;
  11519. }
  11520. if (!_this._shadowMap2) {
  11521. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  11522. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11523. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11524. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  11525. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  11526. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  11527. effect.setTexture("textureSampler", _this._shadowMap);
  11528. });
  11529. _this.blurBoxOffset = 1;
  11530. }
  11531. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  11532. });
  11533. // Custom render function
  11534. var renderSubMesh = function (subMesh) {
  11535. var mesh = subMesh.getRenderingMesh();
  11536. var scene = _this._scene;
  11537. var engine = scene.getEngine();
  11538. // Culling
  11539. engine.setState(subMesh.getMaterial().backFaceCulling);
  11540. // Managing instances
  11541. var batch = mesh._getInstancesRenderList(subMesh._id);
  11542. if (batch.mustReturn) {
  11543. return;
  11544. }
  11545. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11546. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  11547. engine.enableEffect(_this._effect);
  11548. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  11549. var material = subMesh.getMaterial();
  11550. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  11551. _this._effect.setVector3("lightPosition", _this.getLight().position);
  11552. if (_this.getLight().needCube()) {
  11553. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  11554. }
  11555. // Alpha test
  11556. if (material && material.needAlphaTesting()) {
  11557. var alphaTexture = material.getAlphaTestTexture();
  11558. _this._effect.setTexture("diffuseSampler", alphaTexture);
  11559. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  11560. }
  11561. // Bones
  11562. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11563. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  11564. }
  11565. if (_this.forceBackFacesOnly) {
  11566. engine.setState(true, 0, false, true);
  11567. }
  11568. // Draw
  11569. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  11570. if (_this.forceBackFacesOnly) {
  11571. engine.setState(true, 0, false, false);
  11572. }
  11573. }
  11574. else {
  11575. // Need to reset refresh rate of the shadowMap
  11576. _this._shadowMap.resetRefreshCounter();
  11577. }
  11578. };
  11579. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  11580. var index;
  11581. for (index = 0; index < opaqueSubMeshes.length; index++) {
  11582. renderSubMesh(opaqueSubMeshes.data[index]);
  11583. }
  11584. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  11585. renderSubMesh(alphaTestSubMeshes.data[index]);
  11586. }
  11587. if (_this._transparencyShadow) {
  11588. for (index = 0; index < transparentSubMeshes.length; index++) {
  11589. renderSubMesh(transparentSubMeshes.data[index]);
  11590. }
  11591. }
  11592. };
  11593. this._shadowMap.onClearObservable.add(function (engine) {
  11594. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  11595. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  11596. }
  11597. else {
  11598. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  11599. }
  11600. });
  11601. }
  11602. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  11603. // Static
  11604. get: function () {
  11605. return ShadowGenerator._FILTER_NONE;
  11606. },
  11607. enumerable: true,
  11608. configurable: true
  11609. });
  11610. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  11611. get: function () {
  11612. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  11613. },
  11614. enumerable: true,
  11615. configurable: true
  11616. });
  11617. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  11618. get: function () {
  11619. return ShadowGenerator._FILTER_POISSONSAMPLING;
  11620. },
  11621. enumerable: true,
  11622. configurable: true
  11623. });
  11624. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  11625. get: function () {
  11626. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  11627. },
  11628. enumerable: true,
  11629. configurable: true
  11630. });
  11631. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  11632. get: function () {
  11633. return this._bias;
  11634. },
  11635. set: function (bias) {
  11636. this._bias = bias;
  11637. },
  11638. enumerable: true,
  11639. configurable: true
  11640. });
  11641. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  11642. get: function () {
  11643. return this._blurBoxOffset;
  11644. },
  11645. set: function (value) {
  11646. var _this = this;
  11647. if (this._blurBoxOffset === value) {
  11648. return;
  11649. }
  11650. this._blurBoxOffset = value;
  11651. if (this._boxBlurPostprocess) {
  11652. this._boxBlurPostprocess.dispose();
  11653. }
  11654. 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);
  11655. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  11656. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  11657. });
  11658. },
  11659. enumerable: true,
  11660. configurable: true
  11661. });
  11662. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  11663. get: function () {
  11664. return this._filter;
  11665. },
  11666. set: function (value) {
  11667. if (this._filter === value) {
  11668. return;
  11669. }
  11670. this._filter = value;
  11671. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  11672. this._shadowMap.anisotropicFilteringLevel = 16;
  11673. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  11674. }
  11675. else {
  11676. this._shadowMap.anisotropicFilteringLevel = 1;
  11677. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11678. }
  11679. },
  11680. enumerable: true,
  11681. configurable: true
  11682. });
  11683. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  11684. get: function () {
  11685. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  11686. },
  11687. set: function (value) {
  11688. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11689. },
  11690. enumerable: true,
  11691. configurable: true
  11692. });
  11693. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  11694. get: function () {
  11695. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  11696. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  11697. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  11698. },
  11699. set: function (value) {
  11700. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  11701. },
  11702. enumerable: true,
  11703. configurable: true
  11704. });
  11705. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  11706. get: function () {
  11707. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  11708. },
  11709. set: function (value) {
  11710. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11711. },
  11712. enumerable: true,
  11713. configurable: true
  11714. });
  11715. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  11716. var defines = [];
  11717. if (this._useFullFloat) {
  11718. defines.push("#define FULLFLOAT");
  11719. }
  11720. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  11721. defines.push("#define VSM");
  11722. }
  11723. if (this.getLight().needCube()) {
  11724. defines.push("#define CUBEMAP");
  11725. }
  11726. var attribs = [BABYLON.VertexBuffer.PositionKind];
  11727. var mesh = subMesh.getMesh();
  11728. var material = subMesh.getMaterial();
  11729. // Alpha test
  11730. if (material && material.needAlphaTesting()) {
  11731. defines.push("#define ALPHATEST");
  11732. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11733. attribs.push(BABYLON.VertexBuffer.UVKind);
  11734. defines.push("#define UV1");
  11735. }
  11736. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  11737. var alphaTexture = material.getAlphaTestTexture();
  11738. if (alphaTexture.coordinatesIndex === 1) {
  11739. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  11740. defines.push("#define UV2");
  11741. }
  11742. }
  11743. }
  11744. // Bones
  11745. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11746. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  11747. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  11748. if (mesh.numBoneInfluencers > 4) {
  11749. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  11750. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  11751. }
  11752. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  11753. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  11754. }
  11755. else {
  11756. defines.push("#define NUM_BONE_INFLUENCERS 0");
  11757. }
  11758. // Instances
  11759. if (useInstances) {
  11760. defines.push("#define INSTANCES");
  11761. attribs.push("world0");
  11762. attribs.push("world1");
  11763. attribs.push("world2");
  11764. attribs.push("world3");
  11765. }
  11766. // Get correct effect
  11767. var join = defines.join("\n");
  11768. if (this._cachedDefines !== join) {
  11769. this._cachedDefines = join;
  11770. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  11771. }
  11772. return this._effect.isReady();
  11773. };
  11774. ShadowGenerator.prototype.getShadowMap = function () {
  11775. return this._shadowMap;
  11776. };
  11777. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  11778. if (this._shadowMap2) {
  11779. return this._shadowMap2;
  11780. }
  11781. return this._shadowMap;
  11782. };
  11783. ShadowGenerator.prototype.getLight = function () {
  11784. return this._light;
  11785. };
  11786. // Methods
  11787. ShadowGenerator.prototype.getTransformMatrix = function () {
  11788. var scene = this._scene;
  11789. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  11790. return this._transformMatrix;
  11791. }
  11792. this._currentRenderID = scene.getRenderId();
  11793. this._currentFaceIndexCache = this._currentFaceIndex;
  11794. var lightPosition = this._light.position;
  11795. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  11796. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  11797. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  11798. }
  11799. if (this._light.computeTransformedPosition()) {
  11800. lightPosition = this._light.transformedPosition;
  11801. }
  11802. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  11803. this._cachedPosition = lightPosition.clone();
  11804. this._cachedDirection = this._lightDirection.clone();
  11805. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  11806. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  11807. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  11808. }
  11809. return this._transformMatrix;
  11810. };
  11811. ShadowGenerator.prototype.getDarkness = function () {
  11812. return this._darkness;
  11813. };
  11814. ShadowGenerator.prototype.setDarkness = function (darkness) {
  11815. if (darkness >= 1.0)
  11816. this._darkness = 1.0;
  11817. else if (darkness <= 0.0)
  11818. this._darkness = 0.0;
  11819. else
  11820. this._darkness = darkness;
  11821. };
  11822. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  11823. this._transparencyShadow = hasShadow;
  11824. };
  11825. ShadowGenerator.prototype._packHalf = function (depth) {
  11826. var scale = depth * 255.0;
  11827. var fract = scale - Math.floor(scale);
  11828. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  11829. };
  11830. ShadowGenerator.prototype.dispose = function () {
  11831. this._shadowMap.dispose();
  11832. if (this._shadowMap2) {
  11833. this._shadowMap2.dispose();
  11834. }
  11835. if (this._downSamplePostprocess) {
  11836. this._downSamplePostprocess.dispose();
  11837. }
  11838. if (this._boxBlurPostprocess) {
  11839. this._boxBlurPostprocess.dispose();
  11840. }
  11841. };
  11842. ShadowGenerator.prototype.serialize = function () {
  11843. var serializationObject = {};
  11844. serializationObject.lightId = this._light.id;
  11845. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  11846. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  11847. serializationObject.usePoissonSampling = this.usePoissonSampling;
  11848. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  11849. serializationObject.renderList = [];
  11850. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  11851. var mesh = this.getShadowMap().renderList[meshIndex];
  11852. serializationObject.renderList.push(mesh.id);
  11853. }
  11854. return serializationObject;
  11855. };
  11856. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  11857. //casting to point light, as light is missing the position attr and typescript complains.
  11858. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  11859. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  11860. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  11861. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  11862. meshes.forEach(function (mesh) {
  11863. shadowGenerator.getShadowMap().renderList.push(mesh);
  11864. });
  11865. }
  11866. if (parsedShadowGenerator.usePoissonSampling) {
  11867. shadowGenerator.usePoissonSampling = true;
  11868. }
  11869. else if (parsedShadowGenerator.useVarianceShadowMap) {
  11870. shadowGenerator.useVarianceShadowMap = true;
  11871. }
  11872. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  11873. shadowGenerator.useBlurVarianceShadowMap = true;
  11874. if (parsedShadowGenerator.blurScale) {
  11875. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  11876. }
  11877. if (parsedShadowGenerator.blurBoxOffset) {
  11878. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  11879. }
  11880. }
  11881. if (parsedShadowGenerator.bias !== undefined) {
  11882. shadowGenerator.bias = parsedShadowGenerator.bias;
  11883. }
  11884. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  11885. return shadowGenerator;
  11886. };
  11887. ShadowGenerator._FILTER_NONE = 0;
  11888. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  11889. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  11890. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  11891. return ShadowGenerator;
  11892. })();
  11893. BABYLON.ShadowGenerator = ShadowGenerator;
  11894. })(BABYLON || (BABYLON = {}));
  11895. var BABYLON;
  11896. (function (BABYLON) {
  11897. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  11898. if (boxMin.x > sphereCenter.x + sphereRadius)
  11899. return false;
  11900. if (sphereCenter.x - sphereRadius > boxMax.x)
  11901. return false;
  11902. if (boxMin.y > sphereCenter.y + sphereRadius)
  11903. return false;
  11904. if (sphereCenter.y - sphereRadius > boxMax.y)
  11905. return false;
  11906. if (boxMin.z > sphereCenter.z + sphereRadius)
  11907. return false;
  11908. if (sphereCenter.z - sphereRadius > boxMax.z)
  11909. return false;
  11910. return true;
  11911. };
  11912. var getLowestRoot = (function () {
  11913. var result = { root: 0, found: false };
  11914. return function (a, b, c, maxR) {
  11915. result.root = 0;
  11916. result.found = false;
  11917. var determinant = b * b - 4.0 * a * c;
  11918. if (determinant < 0)
  11919. return result;
  11920. var sqrtD = Math.sqrt(determinant);
  11921. var r1 = (-b - sqrtD) / (2.0 * a);
  11922. var r2 = (-b + sqrtD) / (2.0 * a);
  11923. if (r1 > r2) {
  11924. var temp = r2;
  11925. r2 = r1;
  11926. r1 = temp;
  11927. }
  11928. if (r1 > 0 && r1 < maxR) {
  11929. result.root = r1;
  11930. result.found = true;
  11931. return result;
  11932. }
  11933. if (r2 > 0 && r2 < maxR) {
  11934. result.root = r2;
  11935. result.found = true;
  11936. return result;
  11937. }
  11938. return result;
  11939. };
  11940. })();
  11941. var Collider = (function () {
  11942. function Collider() {
  11943. this.radius = new BABYLON.Vector3(1, 1, 1);
  11944. this.retry = 0;
  11945. this.basePointWorld = BABYLON.Vector3.Zero();
  11946. this.velocityWorld = BABYLON.Vector3.Zero();
  11947. this.normalizedVelocity = BABYLON.Vector3.Zero();
  11948. this._collisionPoint = BABYLON.Vector3.Zero();
  11949. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  11950. this._tempVector = BABYLON.Vector3.Zero();
  11951. this._tempVector2 = BABYLON.Vector3.Zero();
  11952. this._tempVector3 = BABYLON.Vector3.Zero();
  11953. this._tempVector4 = BABYLON.Vector3.Zero();
  11954. this._edge = BABYLON.Vector3.Zero();
  11955. this._baseToVertex = BABYLON.Vector3.Zero();
  11956. this._destinationPoint = BABYLON.Vector3.Zero();
  11957. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  11958. this._displacementVector = BABYLON.Vector3.Zero();
  11959. }
  11960. // Methods
  11961. Collider.prototype._initialize = function (source, dir, e) {
  11962. this.velocity = dir;
  11963. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  11964. this.basePoint = source;
  11965. source.multiplyToRef(this.radius, this.basePointWorld);
  11966. dir.multiplyToRef(this.radius, this.velocityWorld);
  11967. this.velocityWorldLength = this.velocityWorld.length();
  11968. this.epsilon = e;
  11969. this.collisionFound = false;
  11970. };
  11971. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  11972. pa.subtractToRef(point, this._tempVector);
  11973. pb.subtractToRef(point, this._tempVector2);
  11974. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  11975. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11976. if (d < 0)
  11977. return false;
  11978. pc.subtractToRef(point, this._tempVector3);
  11979. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  11980. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11981. if (d < 0)
  11982. return false;
  11983. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  11984. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11985. return d >= 0;
  11986. };
  11987. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  11988. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  11989. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  11990. if (distance > this.velocityWorldLength + max + sphereRadius) {
  11991. return false;
  11992. }
  11993. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  11994. return false;
  11995. return true;
  11996. };
  11997. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  11998. var t0;
  11999. var embeddedInPlane = false;
  12000. //defensive programming, actually not needed.
  12001. if (!trianglePlaneArray) {
  12002. trianglePlaneArray = [];
  12003. }
  12004. if (!trianglePlaneArray[faceIndex]) {
  12005. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  12006. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  12007. }
  12008. var trianglePlane = trianglePlaneArray[faceIndex];
  12009. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  12010. return;
  12011. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  12012. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  12013. if (normalDotVelocity == 0) {
  12014. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  12015. return;
  12016. embeddedInPlane = true;
  12017. t0 = 0;
  12018. }
  12019. else {
  12020. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12021. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12022. if (t0 > t1) {
  12023. var temp = t1;
  12024. t1 = t0;
  12025. t0 = temp;
  12026. }
  12027. if (t0 > 1.0 || t1 < 0.0)
  12028. return;
  12029. if (t0 < 0)
  12030. t0 = 0;
  12031. if (t0 > 1.0)
  12032. t0 = 1.0;
  12033. }
  12034. this._collisionPoint.copyFromFloats(0, 0, 0);
  12035. var found = false;
  12036. var t = 1.0;
  12037. if (!embeddedInPlane) {
  12038. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  12039. this.velocity.scaleToRef(t0, this._tempVector);
  12040. this._planeIntersectionPoint.addInPlace(this._tempVector);
  12041. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  12042. found = true;
  12043. t = t0;
  12044. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  12045. }
  12046. }
  12047. if (!found) {
  12048. var velocitySquaredLength = this.velocity.lengthSquared();
  12049. var a = velocitySquaredLength;
  12050. this.basePoint.subtractToRef(p1, this._tempVector);
  12051. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12052. var c = this._tempVector.lengthSquared() - 1.0;
  12053. var lowestRoot = getLowestRoot(a, b, c, t);
  12054. if (lowestRoot.found) {
  12055. t = lowestRoot.root;
  12056. found = true;
  12057. this._collisionPoint.copyFrom(p1);
  12058. }
  12059. this.basePoint.subtractToRef(p2, this._tempVector);
  12060. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12061. c = this._tempVector.lengthSquared() - 1.0;
  12062. lowestRoot = getLowestRoot(a, b, c, t);
  12063. if (lowestRoot.found) {
  12064. t = lowestRoot.root;
  12065. found = true;
  12066. this._collisionPoint.copyFrom(p2);
  12067. }
  12068. this.basePoint.subtractToRef(p3, this._tempVector);
  12069. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12070. c = this._tempVector.lengthSquared() - 1.0;
  12071. lowestRoot = getLowestRoot(a, b, c, t);
  12072. if (lowestRoot.found) {
  12073. t = lowestRoot.root;
  12074. found = true;
  12075. this._collisionPoint.copyFrom(p3);
  12076. }
  12077. p2.subtractToRef(p1, this._edge);
  12078. p1.subtractToRef(this.basePoint, this._baseToVertex);
  12079. var edgeSquaredLength = this._edge.lengthSquared();
  12080. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12081. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12082. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12083. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12084. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12085. lowestRoot = getLowestRoot(a, b, c, t);
  12086. if (lowestRoot.found) {
  12087. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12088. if (f >= 0.0 && f <= 1.0) {
  12089. t = lowestRoot.root;
  12090. found = true;
  12091. this._edge.scaleInPlace(f);
  12092. p1.addToRef(this._edge, this._collisionPoint);
  12093. }
  12094. }
  12095. p3.subtractToRef(p2, this._edge);
  12096. p2.subtractToRef(this.basePoint, this._baseToVertex);
  12097. edgeSquaredLength = this._edge.lengthSquared();
  12098. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12099. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12100. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12101. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12102. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12103. lowestRoot = getLowestRoot(a, b, c, t);
  12104. if (lowestRoot.found) {
  12105. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12106. if (f >= 0.0 && f <= 1.0) {
  12107. t = lowestRoot.root;
  12108. found = true;
  12109. this._edge.scaleInPlace(f);
  12110. p2.addToRef(this._edge, this._collisionPoint);
  12111. }
  12112. }
  12113. p1.subtractToRef(p3, this._edge);
  12114. p3.subtractToRef(this.basePoint, this._baseToVertex);
  12115. edgeSquaredLength = this._edge.lengthSquared();
  12116. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12117. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12118. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12119. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12120. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12121. lowestRoot = getLowestRoot(a, b, c, t);
  12122. if (lowestRoot.found) {
  12123. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12124. if (f >= 0.0 && f <= 1.0) {
  12125. t = lowestRoot.root;
  12126. found = true;
  12127. this._edge.scaleInPlace(f);
  12128. p3.addToRef(this._edge, this._collisionPoint);
  12129. }
  12130. }
  12131. }
  12132. if (found) {
  12133. var distToCollision = t * this.velocity.length();
  12134. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  12135. if (!this.intersectionPoint) {
  12136. this.intersectionPoint = this._collisionPoint.clone();
  12137. }
  12138. else {
  12139. this.intersectionPoint.copyFrom(this._collisionPoint);
  12140. }
  12141. this.nearestDistance = distToCollision;
  12142. this.collisionFound = true;
  12143. }
  12144. }
  12145. };
  12146. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  12147. for (var i = indexStart; i < indexEnd; i += 3) {
  12148. var p1 = pts[indices[i] - decal];
  12149. var p2 = pts[indices[i + 1] - decal];
  12150. var p3 = pts[indices[i + 2] - decal];
  12151. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  12152. }
  12153. };
  12154. Collider.prototype._getResponse = function (pos, vel) {
  12155. pos.addToRef(vel, this._destinationPoint);
  12156. vel.scaleInPlace((this.nearestDistance / vel.length()));
  12157. this.basePoint.addToRef(vel, pos);
  12158. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  12159. this._slidePlaneNormal.normalize();
  12160. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  12161. pos.addInPlace(this._displacementVector);
  12162. this.intersectionPoint.addInPlace(this._displacementVector);
  12163. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  12164. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  12165. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  12166. };
  12167. return Collider;
  12168. })();
  12169. BABYLON.Collider = Collider;
  12170. })(BABYLON || (BABYLON = {}));
  12171. var BABYLON;
  12172. (function (BABYLON) {
  12173. //WebWorker code will be inserted to this variable.
  12174. BABYLON.CollisionWorker = "";
  12175. (function (WorkerTaskType) {
  12176. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  12177. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  12178. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  12179. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  12180. var WorkerTaskType = BABYLON.WorkerTaskType;
  12181. (function (WorkerReplyType) {
  12182. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  12183. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  12184. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  12185. var WorkerReplyType = BABYLON.WorkerReplyType;
  12186. var CollisionCoordinatorWorker = (function () {
  12187. function CollisionCoordinatorWorker() {
  12188. var _this = this;
  12189. this._scaledPosition = BABYLON.Vector3.Zero();
  12190. this._scaledVelocity = BABYLON.Vector3.Zero();
  12191. this.onMeshUpdated = function (mesh) {
  12192. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  12193. };
  12194. this.onGeometryUpdated = function (geometry) {
  12195. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  12196. };
  12197. this._afterRender = function () {
  12198. if (!_this._init)
  12199. return;
  12200. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  12201. return;
  12202. }
  12203. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  12204. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  12205. if (_this._runningUpdated > 4) {
  12206. return;
  12207. }
  12208. ++_this._runningUpdated;
  12209. var payload = {
  12210. updatedMeshes: _this._addUpdateMeshesList,
  12211. updatedGeometries: _this._addUpdateGeometriesList,
  12212. removedGeometries: _this._toRemoveGeometryArray,
  12213. removedMeshes: _this._toRemoveMeshesArray
  12214. };
  12215. var message = {
  12216. payload: payload,
  12217. taskType: WorkerTaskType.UPDATE
  12218. };
  12219. var serializable = [];
  12220. for (var id in payload.updatedGeometries) {
  12221. if (payload.updatedGeometries.hasOwnProperty(id)) {
  12222. //prepare transferables
  12223. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  12224. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  12225. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  12226. }
  12227. }
  12228. _this._worker.postMessage(message, serializable);
  12229. _this._addUpdateMeshesList = {};
  12230. _this._addUpdateGeometriesList = {};
  12231. _this._toRemoveGeometryArray = [];
  12232. _this._toRemoveMeshesArray = [];
  12233. };
  12234. this._onMessageFromWorker = function (e) {
  12235. var returnData = e.data;
  12236. if (returnData.error != WorkerReplyType.SUCCESS) {
  12237. //TODO what errors can be returned from the worker?
  12238. BABYLON.Tools.Warn("error returned from worker!");
  12239. return;
  12240. }
  12241. switch (returnData.taskType) {
  12242. case WorkerTaskType.INIT:
  12243. _this._init = true;
  12244. //Update the worked with ALL of the scene's current state
  12245. _this._scene.meshes.forEach(function (mesh) {
  12246. _this.onMeshAdded(mesh);
  12247. });
  12248. _this._scene.getGeometries().forEach(function (geometry) {
  12249. _this.onGeometryAdded(geometry);
  12250. });
  12251. break;
  12252. case WorkerTaskType.UPDATE:
  12253. _this._runningUpdated--;
  12254. break;
  12255. case WorkerTaskType.COLLIDE:
  12256. _this._runningCollisionTask = false;
  12257. var returnPayload = returnData.payload;
  12258. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  12259. return;
  12260. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  12261. //cleanup
  12262. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  12263. break;
  12264. }
  12265. };
  12266. this._collisionsCallbackArray = [];
  12267. this._init = false;
  12268. this._runningUpdated = 0;
  12269. this._runningCollisionTask = false;
  12270. this._addUpdateMeshesList = {};
  12271. this._addUpdateGeometriesList = {};
  12272. this._toRemoveGeometryArray = [];
  12273. this._toRemoveMeshesArray = [];
  12274. }
  12275. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12276. if (!this._init)
  12277. return;
  12278. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  12279. return;
  12280. position.divideToRef(collider.radius, this._scaledPosition);
  12281. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12282. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  12283. var payload = {
  12284. collider: {
  12285. position: this._scaledPosition.asArray(),
  12286. velocity: this._scaledVelocity.asArray(),
  12287. radius: collider.radius.asArray()
  12288. },
  12289. collisionId: collisionIndex,
  12290. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  12291. maximumRetry: maximumRetry
  12292. };
  12293. var message = {
  12294. payload: payload,
  12295. taskType: WorkerTaskType.COLLIDE
  12296. };
  12297. this._worker.postMessage(message);
  12298. };
  12299. CollisionCoordinatorWorker.prototype.init = function (scene) {
  12300. this._scene = scene;
  12301. this._scene.registerAfterRender(this._afterRender);
  12302. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  12303. this._worker = new Worker(workerUrl);
  12304. this._worker.onmessage = this._onMessageFromWorker;
  12305. var message = {
  12306. payload: {},
  12307. taskType: WorkerTaskType.INIT
  12308. };
  12309. this._worker.postMessage(message);
  12310. };
  12311. CollisionCoordinatorWorker.prototype.destroy = function () {
  12312. this._scene.unregisterAfterRender(this._afterRender);
  12313. this._worker.terminate();
  12314. };
  12315. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  12316. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  12317. this.onMeshUpdated(mesh);
  12318. };
  12319. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  12320. this._toRemoveMeshesArray.push(mesh.uniqueId);
  12321. };
  12322. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  12323. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  12324. geometry.onGeometryUpdated = this.onGeometryUpdated;
  12325. this.onGeometryUpdated(geometry);
  12326. };
  12327. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  12328. this._toRemoveGeometryArray.push(geometry.id);
  12329. };
  12330. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  12331. var submeshes = [];
  12332. if (mesh.subMeshes) {
  12333. submeshes = mesh.subMeshes.map(function (sm, idx) {
  12334. return {
  12335. position: idx,
  12336. verticesStart: sm.verticesStart,
  12337. verticesCount: sm.verticesCount,
  12338. indexStart: sm.indexStart,
  12339. indexCount: sm.indexCount,
  12340. hasMaterial: !!sm.getMaterial(),
  12341. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12342. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  12343. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12344. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  12345. };
  12346. });
  12347. }
  12348. var geometryId = null;
  12349. if (mesh instanceof BABYLON.Mesh) {
  12350. geometryId = mesh.geometry ? mesh.geometry.id : null;
  12351. }
  12352. else if (mesh instanceof BABYLON.InstancedMesh) {
  12353. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  12354. }
  12355. return {
  12356. uniqueId: mesh.uniqueId,
  12357. id: mesh.id,
  12358. name: mesh.name,
  12359. geometryId: geometryId,
  12360. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12361. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  12362. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12363. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  12364. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  12365. subMeshes: submeshes,
  12366. checkCollisions: mesh.checkCollisions
  12367. };
  12368. };
  12369. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  12370. return {
  12371. id: geometry.id,
  12372. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  12373. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  12374. indices: new Int32Array(geometry.getIndices() || []),
  12375. };
  12376. };
  12377. return CollisionCoordinatorWorker;
  12378. })();
  12379. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  12380. var CollisionCoordinatorLegacy = (function () {
  12381. function CollisionCoordinatorLegacy() {
  12382. this._scaledPosition = BABYLON.Vector3.Zero();
  12383. this._scaledVelocity = BABYLON.Vector3.Zero();
  12384. this._finalPosition = BABYLON.Vector3.Zero();
  12385. }
  12386. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12387. position.divideToRef(collider.radius, this._scaledPosition);
  12388. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12389. collider.collidedMesh = null;
  12390. collider.retry = 0;
  12391. collider.initialVelocity = this._scaledVelocity;
  12392. collider.initialPosition = this._scaledPosition;
  12393. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  12394. this._finalPosition.multiplyInPlace(collider.radius);
  12395. //run the callback
  12396. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  12397. };
  12398. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  12399. this._scene = scene;
  12400. };
  12401. CollisionCoordinatorLegacy.prototype.destroy = function () {
  12402. //Legacy need no destruction method.
  12403. };
  12404. //No update in legacy mode
  12405. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  12406. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  12407. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  12408. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  12409. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  12410. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  12411. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  12412. if (excludedMesh === void 0) { excludedMesh = null; }
  12413. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  12414. if (collider.retry >= maximumRetry) {
  12415. finalPosition.copyFrom(position);
  12416. return;
  12417. }
  12418. collider._initialize(position, velocity, closeDistance);
  12419. // Check all meshes
  12420. for (var index = 0; index < this._scene.meshes.length; index++) {
  12421. var mesh = this._scene.meshes[index];
  12422. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  12423. mesh._checkCollision(collider);
  12424. }
  12425. }
  12426. if (!collider.collisionFound) {
  12427. position.addToRef(velocity, finalPosition);
  12428. return;
  12429. }
  12430. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  12431. collider._getResponse(position, velocity);
  12432. }
  12433. if (velocity.length() <= closeDistance) {
  12434. finalPosition.copyFrom(position);
  12435. return;
  12436. }
  12437. collider.retry++;
  12438. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  12439. };
  12440. return CollisionCoordinatorLegacy;
  12441. })();
  12442. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  12443. })(BABYLON || (BABYLON = {}));
  12444. var BABYLON;
  12445. (function (BABYLON) {
  12446. var Camera = (function (_super) {
  12447. __extends(Camera, _super);
  12448. function Camera(name, position, scene) {
  12449. _super.call(this, name, scene);
  12450. this.upVector = BABYLON.Vector3.Up();
  12451. this.orthoLeft = null;
  12452. this.orthoRight = null;
  12453. this.orthoBottom = null;
  12454. this.orthoTop = null;
  12455. this.fov = 0.8;
  12456. this.minZ = 1.0;
  12457. this.maxZ = 10000.0;
  12458. this.inertia = 0.9;
  12459. this.mode = Camera.PERSPECTIVE_CAMERA;
  12460. this.isIntermediate = false;
  12461. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  12462. this.layerMask = 0x0FFFFFFF;
  12463. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  12464. // Camera rig members
  12465. this.cameraRigMode = Camera.RIG_MODE_NONE;
  12466. this._rigCameras = new Array();
  12467. // Cache
  12468. this._computedViewMatrix = BABYLON.Matrix.Identity();
  12469. this._projectionMatrix = new BABYLON.Matrix();
  12470. this._postProcesses = new Array();
  12471. this._transformMatrix = BABYLON.Matrix.Zero();
  12472. this._activeMeshes = new BABYLON.SmartArray(256);
  12473. this._globalPosition = BABYLON.Vector3.Zero();
  12474. this._refreshFrustumPlanes = true;
  12475. scene.addCamera(this);
  12476. if (!scene.activeCamera) {
  12477. scene.activeCamera = this;
  12478. }
  12479. this.position = position;
  12480. }
  12481. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  12482. get: function () {
  12483. return Camera._PERSPECTIVE_CAMERA;
  12484. },
  12485. enumerable: true,
  12486. configurable: true
  12487. });
  12488. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  12489. get: function () {
  12490. return Camera._ORTHOGRAPHIC_CAMERA;
  12491. },
  12492. enumerable: true,
  12493. configurable: true
  12494. });
  12495. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  12496. get: function () {
  12497. return Camera._FOVMODE_VERTICAL_FIXED;
  12498. },
  12499. enumerable: true,
  12500. configurable: true
  12501. });
  12502. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  12503. get: function () {
  12504. return Camera._FOVMODE_HORIZONTAL_FIXED;
  12505. },
  12506. enumerable: true,
  12507. configurable: true
  12508. });
  12509. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  12510. get: function () {
  12511. return Camera._RIG_MODE_NONE;
  12512. },
  12513. enumerable: true,
  12514. configurable: true
  12515. });
  12516. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  12517. get: function () {
  12518. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  12519. },
  12520. enumerable: true,
  12521. configurable: true
  12522. });
  12523. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  12524. get: function () {
  12525. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  12526. },
  12527. enumerable: true,
  12528. configurable: true
  12529. });
  12530. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  12531. get: function () {
  12532. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12533. },
  12534. enumerable: true,
  12535. configurable: true
  12536. });
  12537. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  12538. get: function () {
  12539. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  12540. },
  12541. enumerable: true,
  12542. configurable: true
  12543. });
  12544. Object.defineProperty(Camera, "RIG_MODE_VR", {
  12545. get: function () {
  12546. return Camera._RIG_MODE_VR;
  12547. },
  12548. enumerable: true,
  12549. configurable: true
  12550. });
  12551. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  12552. get: function () {
  12553. return Camera._RIG_MODE_WEBVR;
  12554. },
  12555. enumerable: true,
  12556. configurable: true
  12557. });
  12558. /**
  12559. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12560. */
  12561. Camera.prototype.toString = function (fullDetails) {
  12562. var ret = "Name: " + this.name;
  12563. ret += ", type: " + this.getTypeName();
  12564. if (this.animations) {
  12565. for (var i = 0; i < this.animations.length; i++) {
  12566. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  12567. }
  12568. }
  12569. if (fullDetails) {
  12570. }
  12571. return ret;
  12572. };
  12573. Object.defineProperty(Camera.prototype, "globalPosition", {
  12574. get: function () {
  12575. return this._globalPosition;
  12576. },
  12577. enumerable: true,
  12578. configurable: true
  12579. });
  12580. Camera.prototype.getActiveMeshes = function () {
  12581. return this._activeMeshes;
  12582. };
  12583. Camera.prototype.isActiveMesh = function (mesh) {
  12584. return (this._activeMeshes.indexOf(mesh) !== -1);
  12585. };
  12586. //Cache
  12587. Camera.prototype._initCache = function () {
  12588. _super.prototype._initCache.call(this);
  12589. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12590. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12591. this._cache.mode = undefined;
  12592. this._cache.minZ = undefined;
  12593. this._cache.maxZ = undefined;
  12594. this._cache.fov = undefined;
  12595. this._cache.aspectRatio = undefined;
  12596. this._cache.orthoLeft = undefined;
  12597. this._cache.orthoRight = undefined;
  12598. this._cache.orthoBottom = undefined;
  12599. this._cache.orthoTop = undefined;
  12600. this._cache.renderWidth = undefined;
  12601. this._cache.renderHeight = undefined;
  12602. };
  12603. Camera.prototype._updateCache = function (ignoreParentClass) {
  12604. if (!ignoreParentClass) {
  12605. _super.prototype._updateCache.call(this);
  12606. }
  12607. var engine = this.getEngine();
  12608. this._cache.position.copyFrom(this.position);
  12609. this._cache.upVector.copyFrom(this.upVector);
  12610. this._cache.mode = this.mode;
  12611. this._cache.minZ = this.minZ;
  12612. this._cache.maxZ = this.maxZ;
  12613. this._cache.fov = this.fov;
  12614. this._cache.aspectRatio = engine.getAspectRatio(this);
  12615. this._cache.orthoLeft = this.orthoLeft;
  12616. this._cache.orthoRight = this.orthoRight;
  12617. this._cache.orthoBottom = this.orthoBottom;
  12618. this._cache.orthoTop = this.orthoTop;
  12619. this._cache.renderWidth = engine.getRenderWidth();
  12620. this._cache.renderHeight = engine.getRenderHeight();
  12621. };
  12622. Camera.prototype._updateFromScene = function () {
  12623. this.updateCache();
  12624. this.update();
  12625. };
  12626. // Synchronized
  12627. Camera.prototype._isSynchronized = function () {
  12628. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  12629. };
  12630. Camera.prototype._isSynchronizedViewMatrix = function () {
  12631. if (!_super.prototype._isSynchronized.call(this))
  12632. return false;
  12633. return this._cache.position.equals(this.position)
  12634. && this._cache.upVector.equals(this.upVector)
  12635. && this.isSynchronizedWithParent();
  12636. };
  12637. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  12638. var check = this._cache.mode === this.mode
  12639. && this._cache.minZ === this.minZ
  12640. && this._cache.maxZ === this.maxZ;
  12641. if (!check) {
  12642. return false;
  12643. }
  12644. var engine = this.getEngine();
  12645. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12646. check = this._cache.fov === this.fov
  12647. && this._cache.aspectRatio === engine.getAspectRatio(this);
  12648. }
  12649. else {
  12650. check = this._cache.orthoLeft === this.orthoLeft
  12651. && this._cache.orthoRight === this.orthoRight
  12652. && this._cache.orthoBottom === this.orthoBottom
  12653. && this._cache.orthoTop === this.orthoTop
  12654. && this._cache.renderWidth === engine.getRenderWidth()
  12655. && this._cache.renderHeight === engine.getRenderHeight();
  12656. }
  12657. return check;
  12658. };
  12659. // Controls
  12660. Camera.prototype.attachControl = function (element, noPreventDefault) {
  12661. };
  12662. Camera.prototype.detachControl = function (element) {
  12663. };
  12664. Camera.prototype.update = function () {
  12665. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12666. this._updateRigCameras();
  12667. }
  12668. this._checkInputs();
  12669. };
  12670. Camera.prototype._checkInputs = function () {
  12671. };
  12672. Camera.prototype._cascadePostProcessesToRigCams = function () {
  12673. // invalidate framebuffer
  12674. if (this._postProcesses.length > 0) {
  12675. this._postProcesses[0].markTextureDirty();
  12676. }
  12677. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  12678. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  12679. var cam = this._rigCameras[i];
  12680. var rigPostProcess = cam._rigPostProcess;
  12681. // for VR rig, there does not have to be a post process
  12682. if (rigPostProcess) {
  12683. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  12684. if (isPass) {
  12685. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  12686. cam.isIntermediate = this._postProcesses.length === 0;
  12687. }
  12688. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  12689. rigPostProcess.markTextureDirty();
  12690. }
  12691. else {
  12692. cam._postProcesses = this._postProcesses.slice(0);
  12693. }
  12694. }
  12695. };
  12696. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  12697. if (insertAt === void 0) { insertAt = null; }
  12698. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  12699. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  12700. return 0;
  12701. }
  12702. if (insertAt == null || insertAt < 0) {
  12703. this._postProcesses.push(postProcess);
  12704. }
  12705. else {
  12706. this._postProcesses.splice(insertAt, 0, postProcess);
  12707. }
  12708. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12709. return this._postProcesses.indexOf(postProcess);
  12710. };
  12711. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  12712. if (atIndices === void 0) { atIndices = null; }
  12713. var result = [];
  12714. var i;
  12715. var index;
  12716. if (!atIndices) {
  12717. var idx = this._postProcesses.indexOf(postProcess);
  12718. if (idx !== -1) {
  12719. this._postProcesses.splice(idx, 1);
  12720. }
  12721. }
  12722. else {
  12723. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  12724. // iterate descending, so can just splice as we go
  12725. for (i = atIndices.length - 1; i >= 0; i--) {
  12726. if (this._postProcesses[atIndices[i]] !== postProcess) {
  12727. result.push(i);
  12728. continue;
  12729. }
  12730. this._postProcesses.splice(index, 1);
  12731. }
  12732. }
  12733. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12734. return result;
  12735. };
  12736. Camera.prototype.getWorldMatrix = function () {
  12737. if (!this._worldMatrix) {
  12738. this._worldMatrix = BABYLON.Matrix.Identity();
  12739. }
  12740. var viewMatrix = this.getViewMatrix();
  12741. viewMatrix.invertToRef(this._worldMatrix);
  12742. return this._worldMatrix;
  12743. };
  12744. Camera.prototype._getViewMatrix = function () {
  12745. return BABYLON.Matrix.Identity();
  12746. };
  12747. Camera.prototype.getViewMatrix = function (force) {
  12748. this._computedViewMatrix = this._computeViewMatrix(force);
  12749. if (!force && this._isSynchronizedViewMatrix()) {
  12750. return this._computedViewMatrix;
  12751. }
  12752. this._refreshFrustumPlanes = true;
  12753. if (!this.parent || !this.parent.getWorldMatrix) {
  12754. this._globalPosition.copyFrom(this.position);
  12755. }
  12756. else {
  12757. if (!this._worldMatrix) {
  12758. this._worldMatrix = BABYLON.Matrix.Identity();
  12759. }
  12760. this._computedViewMatrix.invertToRef(this._worldMatrix);
  12761. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  12762. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  12763. this._computedViewMatrix.invert();
  12764. this._markSyncedWithParent();
  12765. }
  12766. this._currentRenderId = this.getScene().getRenderId();
  12767. return this._computedViewMatrix;
  12768. };
  12769. Camera.prototype._computeViewMatrix = function (force) {
  12770. if (!force && this._isSynchronizedViewMatrix()) {
  12771. return this._computedViewMatrix;
  12772. }
  12773. this._computedViewMatrix = this._getViewMatrix();
  12774. this._currentRenderId = this.getScene().getRenderId();
  12775. return this._computedViewMatrix;
  12776. };
  12777. Camera.prototype.getProjectionMatrix = function (force) {
  12778. if (!force && this._isSynchronizedProjectionMatrix()) {
  12779. return this._projectionMatrix;
  12780. }
  12781. this._refreshFrustumPlanes = true;
  12782. var engine = this.getEngine();
  12783. var scene = this.getScene();
  12784. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12785. if (this.minZ <= 0) {
  12786. this.minZ = 0.1;
  12787. }
  12788. if (scene.useRightHandedSystem) {
  12789. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  12790. }
  12791. else {
  12792. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  12793. }
  12794. return this._projectionMatrix;
  12795. }
  12796. var halfWidth = engine.getRenderWidth() / 2.0;
  12797. var halfHeight = engine.getRenderHeight() / 2.0;
  12798. if (scene.useRightHandedSystem) {
  12799. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  12800. }
  12801. else {
  12802. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  12803. }
  12804. return this._projectionMatrix;
  12805. };
  12806. Camera.prototype.getTranformationMatrix = function () {
  12807. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12808. return this._transformMatrix;
  12809. };
  12810. Camera.prototype.updateFrustumPlanes = function () {
  12811. if (!this._refreshFrustumPlanes) {
  12812. return;
  12813. }
  12814. this.getTranformationMatrix();
  12815. if (!this._frustumPlanes) {
  12816. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12817. }
  12818. else {
  12819. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12820. }
  12821. this._refreshFrustumPlanes = false;
  12822. };
  12823. Camera.prototype.isInFrustum = function (target) {
  12824. this.updateFrustumPlanes();
  12825. return target.isInFrustum(this._frustumPlanes);
  12826. };
  12827. Camera.prototype.isCompletelyInFrustum = function (target) {
  12828. this.updateFrustumPlanes();
  12829. return target.isCompletelyInFrustum(this._frustumPlanes);
  12830. };
  12831. Camera.prototype.dispose = function () {
  12832. // Animations
  12833. this.getScene().stopAnimation(this);
  12834. // Remove from scene
  12835. this.getScene().removeCamera(this);
  12836. while (this._rigCameras.length > 0) {
  12837. this._rigCameras.pop().dispose();
  12838. }
  12839. // Postprocesses
  12840. for (var i = 0; i < this._postProcesses.length; ++i) {
  12841. this._postProcesses[i].dispose(this);
  12842. }
  12843. _super.prototype.dispose.call(this);
  12844. };
  12845. // ---- Camera rigs section ----
  12846. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  12847. while (this._rigCameras.length > 0) {
  12848. this._rigCameras.pop().dispose();
  12849. }
  12850. this.cameraRigMode = mode;
  12851. this._cameraRigParams = {};
  12852. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  12853. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  12854. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  12855. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  12856. // create the rig cameras, unless none
  12857. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12858. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  12859. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  12860. }
  12861. switch (this.cameraRigMode) {
  12862. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12863. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12864. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  12865. break;
  12866. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12867. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12868. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12869. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12870. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12871. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  12872. break;
  12873. case Camera.RIG_MODE_VR:
  12874. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  12875. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  12876. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  12877. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12878. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  12879. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  12880. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  12881. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  12882. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  12883. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12884. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  12885. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  12886. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  12887. if (metrics.compensateDistortion) {
  12888. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  12889. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  12890. }
  12891. break;
  12892. case Camera.RIG_MODE_WEBVR:
  12893. if (rigParams.vrDisplay) {
  12894. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  12895. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  12896. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  12897. this._rigCameras[0].setCameraRigParameter("vrFieldOfView", leftEye.fieldOfView);
  12898. this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", BABYLON.Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
  12899. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12900. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  12901. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  12902. this._rigCameras[1].setCameraRigParameter("vrFieldOfView", rightEye.fieldOfView);
  12903. this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", BABYLON.Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
  12904. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12905. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  12906. }
  12907. break;
  12908. }
  12909. this._cascadePostProcessesToRigCams();
  12910. this.
  12911. update();
  12912. };
  12913. Camera.prototype._getVRProjectionMatrix = function () {
  12914. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  12915. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  12916. return this._projectionMatrix;
  12917. };
  12918. Camera.prototype._getWebVRProjectionMatrix = function () {
  12919. BABYLON.Matrix.PerspectiveFovWebVRToRef(this._cameraRigParams['vrFieldOfView'], this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  12920. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams['vrOffsetMatrix'], this._projectionMatrix);
  12921. return this._projectionMatrix;
  12922. };
  12923. Camera.prototype.setCameraRigParameter = function (name, value) {
  12924. if (!this._cameraRigParams) {
  12925. this._cameraRigParams = {};
  12926. }
  12927. this._cameraRigParams[name] = value;
  12928. //provisionnally:
  12929. if (name === "interaxialDistance") {
  12930. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  12931. }
  12932. };
  12933. /**
  12934. * needs to be overridden by children so sub has required properties to be copied
  12935. */
  12936. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  12937. return null;
  12938. };
  12939. /**
  12940. * May need to be overridden by children
  12941. */
  12942. Camera.prototype._updateRigCameras = function () {
  12943. for (var i = 0; i < this._rigCameras.length; i++) {
  12944. this._rigCameras[i].minZ = this.minZ;
  12945. this._rigCameras[i].maxZ = this.maxZ;
  12946. this._rigCameras[i].fov = this.fov;
  12947. }
  12948. // only update viewport when ANAGLYPH
  12949. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  12950. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  12951. }
  12952. };
  12953. Camera.prototype._setupInputs = function () {
  12954. };
  12955. Camera.prototype.serialize = function () {
  12956. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  12957. // Type
  12958. serializationObject.type = this.getTypeName();
  12959. // Parent
  12960. if (this.parent) {
  12961. serializationObject.parentId = this.parent.id;
  12962. }
  12963. if (this.inputs) {
  12964. this.inputs.serialize(serializationObject);
  12965. }
  12966. // Animations
  12967. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  12968. serializationObject.ranges = this.serializeAnimationRanges();
  12969. return serializationObject;
  12970. };
  12971. Camera.prototype.getTypeName = function () {
  12972. return "Camera";
  12973. };
  12974. Camera.prototype.clone = function (name) {
  12975. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  12976. };
  12977. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  12978. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  12979. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  12980. switch (type) {
  12981. case "ArcRotateCamera":
  12982. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  12983. case "DeviceOrientationCamera":
  12984. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  12985. case "FollowCamera":
  12986. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  12987. case "ArcFollowCamera":
  12988. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  12989. case "GamepadCamera":
  12990. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  12991. case "TouchCamera":
  12992. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  12993. case "VirtualJoysticksCamera":
  12994. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  12995. case "WebVRFreeCamera":
  12996. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  12997. case "VRDeviceOrientationFreeCamera":
  12998. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  12999. case "AnaglyphArcRotateCamera":
  13000. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13001. case "AnaglyphFreeCamera":
  13002. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13003. case "AnaglyphGamepadCamera":
  13004. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13005. case "AnaglyphUniversalCamera":
  13006. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13007. case "StereoscopicArcRotateCamera":
  13008. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13009. case "StereoscopicFreeCamera":
  13010. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13011. case "StereoscopicGamepadCamera":
  13012. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13013. case "StereoscopicUniversalCamera":
  13014. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13015. case "FreeCamera":
  13016. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13017. default:
  13018. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13019. }
  13020. };
  13021. Camera.Parse = function (parsedCamera, scene) {
  13022. var type = parsedCamera.type;
  13023. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  13024. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  13025. // Parent
  13026. if (parsedCamera.parentId) {
  13027. camera._waitingParentId = parsedCamera.parentId;
  13028. }
  13029. //If camera has an input manager, let it parse inputs settings
  13030. if (camera.inputs) {
  13031. camera.inputs.parse(parsedCamera);
  13032. camera._setupInputs();
  13033. }
  13034. // Target
  13035. if (parsedCamera.target) {
  13036. if (camera.setTarget) {
  13037. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  13038. }
  13039. }
  13040. // Apply 3d rig, when found
  13041. if (parsedCamera.cameraRigMode) {
  13042. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  13043. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  13044. }
  13045. // Animations
  13046. if (parsedCamera.animations) {
  13047. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  13048. var parsedAnimation = parsedCamera.animations[animationIndex];
  13049. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13050. }
  13051. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  13052. }
  13053. if (parsedCamera.autoAnimate) {
  13054. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  13055. }
  13056. return camera;
  13057. };
  13058. // Statics
  13059. Camera._PERSPECTIVE_CAMERA = 0;
  13060. Camera._ORTHOGRAPHIC_CAMERA = 1;
  13061. Camera._FOVMODE_VERTICAL_FIXED = 0;
  13062. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  13063. Camera._RIG_MODE_NONE = 0;
  13064. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  13065. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  13066. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  13067. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  13068. Camera._RIG_MODE_VR = 20;
  13069. Camera._RIG_MODE_WEBVR = 21;
  13070. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  13071. __decorate([
  13072. BABYLON.serializeAsVector3()
  13073. ], Camera.prototype, "position", void 0);
  13074. __decorate([
  13075. BABYLON.serializeAsVector3()
  13076. ], Camera.prototype, "upVector", void 0);
  13077. __decorate([
  13078. BABYLON.serialize()
  13079. ], Camera.prototype, "orthoLeft", void 0);
  13080. __decorate([
  13081. BABYLON.serialize()
  13082. ], Camera.prototype, "orthoRight", void 0);
  13083. __decorate([
  13084. BABYLON.serialize()
  13085. ], Camera.prototype, "orthoBottom", void 0);
  13086. __decorate([
  13087. BABYLON.serialize()
  13088. ], Camera.prototype, "orthoTop", void 0);
  13089. __decorate([
  13090. BABYLON.serialize()
  13091. ], Camera.prototype, "fov", void 0);
  13092. __decorate([
  13093. BABYLON.serialize()
  13094. ], Camera.prototype, "minZ", void 0);
  13095. __decorate([
  13096. BABYLON.serialize()
  13097. ], Camera.prototype, "maxZ", void 0);
  13098. __decorate([
  13099. BABYLON.serialize()
  13100. ], Camera.prototype, "inertia", void 0);
  13101. __decorate([
  13102. BABYLON.serialize()
  13103. ], Camera.prototype, "mode", void 0);
  13104. __decorate([
  13105. BABYLON.serialize()
  13106. ], Camera.prototype, "layerMask", void 0);
  13107. __decorate([
  13108. BABYLON.serialize()
  13109. ], Camera.prototype, "fovMode", void 0);
  13110. __decorate([
  13111. BABYLON.serialize()
  13112. ], Camera.prototype, "cameraRigMode", void 0);
  13113. __decorate([
  13114. BABYLON.serialize()
  13115. ], Camera.prototype, "interaxialDistance", void 0);
  13116. __decorate([
  13117. BABYLON.serialize()
  13118. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  13119. return Camera;
  13120. })(BABYLON.Node);
  13121. BABYLON.Camera = Camera;
  13122. })(BABYLON || (BABYLON = {}));
  13123. var BABYLON;
  13124. (function (BABYLON) {
  13125. BABYLON.CameraInputTypes = {};
  13126. var CameraInputsManager = (function () {
  13127. function CameraInputsManager(camera) {
  13128. this.attached = {};
  13129. this.camera = camera;
  13130. this.checkInputs = function () { };
  13131. }
  13132. CameraInputsManager.prototype.add = function (input) {
  13133. var type = input.getSimpleName();
  13134. if (this.attached[type]) {
  13135. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  13136. return;
  13137. }
  13138. this.attached[type] = input;
  13139. input.camera = this.camera;
  13140. //for checkInputs, we are dynamically creating a function
  13141. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  13142. if (input.checkInputs) {
  13143. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13144. }
  13145. if (this.attachedElement) {
  13146. input.attachControl(this.attachedElement);
  13147. }
  13148. };
  13149. CameraInputsManager.prototype.remove = function (inputToRemove) {
  13150. for (var cam in this.attached) {
  13151. var input = this.attached[cam];
  13152. if (input === inputToRemove) {
  13153. input.detachControl(this.attachedElement);
  13154. delete this.attached[cam];
  13155. this.rebuildInputCheck();
  13156. }
  13157. }
  13158. };
  13159. CameraInputsManager.prototype.removeByType = function (inputType) {
  13160. for (var cam in this.attached) {
  13161. var input = this.attached[cam];
  13162. if (input.getTypeName() === inputType) {
  13163. input.detachControl(this.attachedElement);
  13164. delete this.attached[cam];
  13165. this.rebuildInputCheck();
  13166. }
  13167. }
  13168. };
  13169. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  13170. var current = this.checkInputs;
  13171. return function () {
  13172. current();
  13173. fn();
  13174. };
  13175. };
  13176. CameraInputsManager.prototype.attachInput = function (input) {
  13177. input.attachControl(this.attachedElement, this.noPreventDefault);
  13178. };
  13179. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  13180. if (this.attachedElement) {
  13181. return;
  13182. }
  13183. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  13184. this.attachedElement = element;
  13185. this.noPreventDefault = noPreventDefault;
  13186. for (var cam in this.attached) {
  13187. var input = this.attached[cam];
  13188. this.attached[cam].attachControl(element, noPreventDefault);
  13189. }
  13190. };
  13191. CameraInputsManager.prototype.detachElement = function (element) {
  13192. if (this.attachedElement !== element) {
  13193. return;
  13194. }
  13195. for (var cam in this.attached) {
  13196. var input = this.attached[cam];
  13197. this.attached[cam].detachControl(element);
  13198. }
  13199. this.attachedElement = null;
  13200. };
  13201. CameraInputsManager.prototype.rebuildInputCheck = function () {
  13202. this.checkInputs = function () { };
  13203. for (var cam in this.attached) {
  13204. var input = this.attached[cam];
  13205. if (input.checkInputs) {
  13206. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13207. }
  13208. }
  13209. };
  13210. CameraInputsManager.prototype.clear = function () {
  13211. if (this.attachedElement) {
  13212. this.detachElement(this.attachedElement);
  13213. }
  13214. this.attached = {};
  13215. this.attachedElement = null;
  13216. this.checkInputs = function () { };
  13217. };
  13218. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  13219. var inputs = {};
  13220. for (var cam in this.attached) {
  13221. var input = this.attached[cam];
  13222. var res = BABYLON.SerializationHelper.Serialize(input);
  13223. inputs[input.getTypeName()] = res;
  13224. }
  13225. serializedCamera.inputsmgr = inputs;
  13226. };
  13227. CameraInputsManager.prototype.parse = function (parsedCamera) {
  13228. var parsedInputs = parsedCamera.inputsmgr;
  13229. if (parsedInputs) {
  13230. this.clear();
  13231. for (var n in parsedInputs) {
  13232. var construct = BABYLON.CameraInputTypes[n];
  13233. if (construct) {
  13234. var parsedinput = parsedInputs[n];
  13235. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  13236. this.add(input);
  13237. }
  13238. }
  13239. }
  13240. else {
  13241. //2016-03-08 this part is for managing backward compatibility
  13242. for (var n in this.attached) {
  13243. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  13244. if (construct) {
  13245. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  13246. this.remove(this.attached[n]);
  13247. this.add(input);
  13248. }
  13249. }
  13250. }
  13251. };
  13252. return CameraInputsManager;
  13253. })();
  13254. BABYLON.CameraInputsManager = CameraInputsManager;
  13255. })(BABYLON || (BABYLON = {}));
  13256. var BABYLON;
  13257. (function (BABYLON) {
  13258. var FreeCameraMouseInput = (function () {
  13259. function FreeCameraMouseInput(touchEnabled) {
  13260. if (touchEnabled === void 0) { touchEnabled = true; }
  13261. this.touchEnabled = touchEnabled;
  13262. this.angularSensibility = 2000.0;
  13263. }
  13264. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  13265. var _this = this;
  13266. if (!this._pointerInput) {
  13267. var camera = this.camera;
  13268. var engine = this.camera.getEngine();
  13269. this._pointerInput = function (p, s) {
  13270. var evt = p.event;
  13271. if (!_this.touchEnabled && evt.pointerType === "touch") {
  13272. return;
  13273. }
  13274. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13275. try {
  13276. evt.srcElement.setPointerCapture(evt.pointerId);
  13277. }
  13278. catch (e) {
  13279. }
  13280. _this.previousPosition = {
  13281. x: evt.clientX,
  13282. y: evt.clientY
  13283. };
  13284. if (!noPreventDefault) {
  13285. evt.preventDefault();
  13286. element.focus();
  13287. }
  13288. }
  13289. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13290. try {
  13291. evt.srcElement.releasePointerCapture(evt.pointerId);
  13292. }
  13293. catch (e) {
  13294. }
  13295. _this.previousPosition = null;
  13296. if (!noPreventDefault) {
  13297. evt.preventDefault();
  13298. }
  13299. }
  13300. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13301. if (!_this.previousPosition || engine.isPointerLock) {
  13302. return;
  13303. }
  13304. var offsetX = evt.clientX - _this.previousPosition.x;
  13305. var offsetY = evt.clientY - _this.previousPosition.y;
  13306. if (_this.camera.getScene().useRightHandedSystem) {
  13307. camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13308. }
  13309. else {
  13310. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13311. }
  13312. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13313. _this.previousPosition = {
  13314. x: evt.clientX,
  13315. y: evt.clientY
  13316. };
  13317. if (!noPreventDefault) {
  13318. evt.preventDefault();
  13319. }
  13320. }
  13321. };
  13322. }
  13323. this._onMouseMove = function (evt) {
  13324. if (!engine.isPointerLock) {
  13325. return;
  13326. }
  13327. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13328. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13329. if (_this.camera.getScene().useRightHandedSystem) {
  13330. camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13331. }
  13332. else {
  13333. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13334. }
  13335. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13336. _this.previousPosition = null;
  13337. if (!noPreventDefault) {
  13338. evt.preventDefault();
  13339. }
  13340. };
  13341. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13342. element.addEventListener("mousemove", this._onMouseMove, false);
  13343. };
  13344. FreeCameraMouseInput.prototype.detachControl = function (element) {
  13345. if (this._observer && element) {
  13346. this.camera.getScene().onPointerObservable.remove(this._observer);
  13347. element.removeEventListener("mousemove", this._onMouseMove);
  13348. this._observer = null;
  13349. this._onMouseMove = null;
  13350. this.previousPosition = null;
  13351. }
  13352. };
  13353. FreeCameraMouseInput.prototype.getTypeName = function () {
  13354. return "FreeCameraMouseInput";
  13355. };
  13356. FreeCameraMouseInput.prototype.getSimpleName = function () {
  13357. return "mouse";
  13358. };
  13359. __decorate([
  13360. BABYLON.serialize()
  13361. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  13362. return FreeCameraMouseInput;
  13363. })();
  13364. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  13365. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  13366. })(BABYLON || (BABYLON = {}));
  13367. var BABYLON;
  13368. (function (BABYLON) {
  13369. var FreeCameraKeyboardMoveInput = (function () {
  13370. function FreeCameraKeyboardMoveInput() {
  13371. this._keys = [];
  13372. this.keysUp = [38];
  13373. this.keysDown = [40];
  13374. this.keysLeft = [37];
  13375. this.keysRight = [39];
  13376. }
  13377. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13378. var _this = this;
  13379. if (!this._onKeyDown) {
  13380. element.tabIndex = 1;
  13381. this._onKeyDown = function (evt) {
  13382. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13383. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13384. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13385. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13386. var index = _this._keys.indexOf(evt.keyCode);
  13387. if (index === -1) {
  13388. _this._keys.push(evt.keyCode);
  13389. }
  13390. if (!noPreventDefault) {
  13391. evt.preventDefault();
  13392. }
  13393. }
  13394. };
  13395. this._onKeyUp = function (evt) {
  13396. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13397. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13398. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13399. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13400. var index = _this._keys.indexOf(evt.keyCode);
  13401. if (index >= 0) {
  13402. _this._keys.splice(index, 1);
  13403. }
  13404. if (!noPreventDefault) {
  13405. evt.preventDefault();
  13406. }
  13407. }
  13408. };
  13409. element.addEventListener("keydown", this._onKeyDown, false);
  13410. element.addEventListener("keyup", this._onKeyUp, false);
  13411. BABYLON.Tools.RegisterTopRootEvents([
  13412. { name: "blur", handler: this._onLostFocus }
  13413. ]);
  13414. }
  13415. };
  13416. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13417. if (this._onKeyDown) {
  13418. element.removeEventListener("keydown", this._onKeyDown);
  13419. element.removeEventListener("keyup", this._onKeyUp);
  13420. BABYLON.Tools.UnregisterTopRootEvents([
  13421. { name: "blur", handler: this._onLostFocus }
  13422. ]);
  13423. this._keys = [];
  13424. this._onKeyDown = null;
  13425. this._onKeyUp = null;
  13426. }
  13427. };
  13428. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13429. if (this._onKeyDown) {
  13430. var camera = this.camera;
  13431. // Keyboard
  13432. for (var index = 0; index < this._keys.length; index++) {
  13433. var keyCode = this._keys[index];
  13434. var speed = camera._computeLocalCameraSpeed();
  13435. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13436. camera._localDirection.copyFromFloats(-speed, 0, 0);
  13437. }
  13438. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13439. camera._localDirection.copyFromFloats(0, 0, speed);
  13440. }
  13441. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13442. camera._localDirection.copyFromFloats(speed, 0, 0);
  13443. }
  13444. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13445. camera._localDirection.copyFromFloats(0, 0, -speed);
  13446. }
  13447. if (camera.getScene().useRightHandedSystem) {
  13448. camera._localDirection.z *= -1;
  13449. }
  13450. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  13451. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  13452. camera.cameraDirection.addInPlace(camera._transformedDirection);
  13453. }
  13454. }
  13455. };
  13456. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13457. return "FreeCameraKeyboardMoveInput";
  13458. };
  13459. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  13460. this._keys = [];
  13461. };
  13462. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13463. return "keyboard";
  13464. };
  13465. __decorate([
  13466. BABYLON.serialize()
  13467. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13468. __decorate([
  13469. BABYLON.serialize()
  13470. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13471. __decorate([
  13472. BABYLON.serialize()
  13473. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13474. __decorate([
  13475. BABYLON.serialize()
  13476. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13477. return FreeCameraKeyboardMoveInput;
  13478. })();
  13479. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  13480. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  13481. })(BABYLON || (BABYLON = {}));
  13482. var BABYLON;
  13483. (function (BABYLON) {
  13484. var FreeCameraTouchInput = (function () {
  13485. function FreeCameraTouchInput() {
  13486. this._offsetX = null;
  13487. this._offsetY = null;
  13488. this._pointerCount = 0;
  13489. this._pointerPressed = [];
  13490. this.touchAngularSensibility = 200000.0;
  13491. this.touchMoveSensibility = 250.0;
  13492. }
  13493. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  13494. var _this = this;
  13495. var previousPosition;
  13496. if (this._pointerInput === undefined) {
  13497. this._onLostFocus = function (evt) {
  13498. _this._offsetX = null;
  13499. _this._offsetY = null;
  13500. };
  13501. this._pointerInput = function (p, s) {
  13502. var evt = p.event;
  13503. if (evt.pointerType === "mouse") {
  13504. return;
  13505. }
  13506. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13507. if (!noPreventDefault) {
  13508. evt.preventDefault();
  13509. }
  13510. _this._pointerPressed.push(evt.pointerId);
  13511. if (_this._pointerPressed.length !== 1) {
  13512. return;
  13513. }
  13514. previousPosition = {
  13515. x: evt.clientX,
  13516. y: evt.clientY
  13517. };
  13518. }
  13519. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13520. if (!noPreventDefault) {
  13521. evt.preventDefault();
  13522. }
  13523. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13524. if (index === -1) {
  13525. return;
  13526. }
  13527. _this._pointerPressed.splice(index, 1);
  13528. if (index != 0) {
  13529. return;
  13530. }
  13531. previousPosition = null;
  13532. _this._offsetX = null;
  13533. _this._offsetY = null;
  13534. }
  13535. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13536. if (!noPreventDefault) {
  13537. evt.preventDefault();
  13538. }
  13539. if (!previousPosition) {
  13540. return;
  13541. }
  13542. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13543. if (index != 0) {
  13544. return;
  13545. }
  13546. _this._offsetX = evt.clientX - previousPosition.x;
  13547. _this._offsetY = -(evt.clientY - previousPosition.y);
  13548. }
  13549. };
  13550. }
  13551. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13552. element.addEventListener("blur", this._onLostFocus);
  13553. };
  13554. FreeCameraTouchInput.prototype.detachControl = function (element) {
  13555. if (this._pointerInput && element) {
  13556. this.camera.getScene().onPointerObservable.remove(this._observer);
  13557. this._observer = null;
  13558. element.removeEventListener("blur", this._onLostFocus);
  13559. this._onLostFocus = null;
  13560. this._pointerPressed = [];
  13561. this._offsetX = null;
  13562. this._offsetY = null;
  13563. this._pointerCount = 0;
  13564. }
  13565. };
  13566. FreeCameraTouchInput.prototype.checkInputs = function () {
  13567. if (this._offsetX) {
  13568. var camera = this.camera;
  13569. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  13570. if (this._pointerPressed.length > 1) {
  13571. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  13572. }
  13573. else {
  13574. var speed = camera._computeLocalCameraSpeed();
  13575. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  13576. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  13577. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  13578. }
  13579. }
  13580. };
  13581. FreeCameraTouchInput.prototype.getTypeName = function () {
  13582. return "FreeCameraTouchInput";
  13583. };
  13584. FreeCameraTouchInput.prototype.getSimpleName = function () {
  13585. return "touch";
  13586. };
  13587. __decorate([
  13588. BABYLON.serialize()
  13589. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  13590. __decorate([
  13591. BABYLON.serialize()
  13592. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  13593. return FreeCameraTouchInput;
  13594. })();
  13595. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  13596. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  13597. })(BABYLON || (BABYLON = {}));
  13598. var BABYLON;
  13599. (function (BABYLON) {
  13600. var FreeCameraDeviceOrientationInput = (function () {
  13601. function FreeCameraDeviceOrientationInput() {
  13602. var _this = this;
  13603. this._screenOrientationAngle = 0;
  13604. this._screenQuaternion = new BABYLON.Quaternion();
  13605. this._alpha = 0;
  13606. this._beta = 0;
  13607. this._gamma = 0;
  13608. this._orientationChanged = function () {
  13609. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  13610. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  13611. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  13612. };
  13613. this._deviceOrientation = function (evt) {
  13614. _this._alpha = evt.alpha;
  13615. _this._beta = evt.beta;
  13616. _this._gamma = evt.gamma;
  13617. };
  13618. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  13619. this._orientationChanged();
  13620. }
  13621. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  13622. get: function () {
  13623. return this._camera;
  13624. },
  13625. set: function (camera) {
  13626. this._camera = camera;
  13627. if (!this._camera.rotationQuaternion)
  13628. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  13629. },
  13630. enumerable: true,
  13631. configurable: true
  13632. });
  13633. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13634. window.addEventListener("orientationchange", this._orientationChanged);
  13635. window.addEventListener("deviceorientation", this._deviceOrientation);
  13636. //In certain cases, the attach control is called AFTER orientation was changed,
  13637. //So this is needed.
  13638. this._orientationChanged();
  13639. };
  13640. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  13641. window.removeEventListener("orientationchange", this._orientationChanged);
  13642. window.removeEventListener("deviceorientation", this._deviceOrientation);
  13643. };
  13644. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  13645. //if no device orientation provided, don't update the rotation.
  13646. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  13647. if (!this._alpha)
  13648. return;
  13649. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  13650. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  13651. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  13652. //Mirror on XY Plane
  13653. this._camera.rotationQuaternion.z *= -1;
  13654. this._camera.rotationQuaternion.w *= -1;
  13655. };
  13656. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  13657. return "FreeCameraDeviceOrientationInput";
  13658. };
  13659. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  13660. return "deviceOrientation";
  13661. };
  13662. return FreeCameraDeviceOrientationInput;
  13663. })();
  13664. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  13665. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  13666. })(BABYLON || (BABYLON = {}));
  13667. var BABYLON;
  13668. (function (BABYLON) {
  13669. var FreeCameraGamepadInput = (function () {
  13670. function FreeCameraGamepadInput() {
  13671. this.gamepadAngularSensibility = 200;
  13672. this.gamepadMoveSensibility = 40;
  13673. }
  13674. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13675. var _this = this;
  13676. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13677. };
  13678. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  13679. if (this._gamepads) {
  13680. this._gamepads.dispose();
  13681. }
  13682. this.gamepad = null;
  13683. };
  13684. FreeCameraGamepadInput.prototype.checkInputs = function () {
  13685. if (this.gamepad) {
  13686. var camera = this.camera;
  13687. var LSValues = this.gamepad.leftStick;
  13688. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  13689. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13690. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  13691. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  13692. var RSValues = this.gamepad.rightStick;
  13693. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  13694. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  13695. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  13696. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  13697. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  13698. var speed = camera._computeLocalCameraSpeed() * 50.0;
  13699. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  13700. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  13701. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  13702. }
  13703. };
  13704. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13705. // Only the first gamepad can control the camera
  13706. if (gamepad.index === 0) {
  13707. this.gamepad = gamepad;
  13708. }
  13709. };
  13710. FreeCameraGamepadInput.prototype.getTypeName = function () {
  13711. return "FreeCameraGamepadInput";
  13712. };
  13713. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  13714. return "gamepad";
  13715. };
  13716. __decorate([
  13717. BABYLON.serialize()
  13718. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  13719. __decorate([
  13720. BABYLON.serialize()
  13721. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13722. return FreeCameraGamepadInput;
  13723. })();
  13724. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  13725. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  13726. })(BABYLON || (BABYLON = {}));
  13727. var BABYLON;
  13728. (function (BABYLON) {
  13729. var ArcRotateCameraKeyboardMoveInput = (function () {
  13730. function ArcRotateCameraKeyboardMoveInput() {
  13731. this._keys = [];
  13732. this.keysUp = [38];
  13733. this.keysDown = [40];
  13734. this.keysLeft = [37];
  13735. this.keysRight = [39];
  13736. }
  13737. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13738. var _this = this;
  13739. element.tabIndex = 1;
  13740. this._onKeyDown = function (evt) {
  13741. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13742. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13743. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13744. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13745. var index = _this._keys.indexOf(evt.keyCode);
  13746. if (index === -1) {
  13747. _this._keys.push(evt.keyCode);
  13748. }
  13749. if (evt.preventDefault) {
  13750. if (!noPreventDefault) {
  13751. evt.preventDefault();
  13752. }
  13753. }
  13754. }
  13755. };
  13756. this._onKeyUp = function (evt) {
  13757. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13758. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13759. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13760. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13761. var index = _this._keys.indexOf(evt.keyCode);
  13762. if (index >= 0) {
  13763. _this._keys.splice(index, 1);
  13764. }
  13765. if (evt.preventDefault) {
  13766. if (!noPreventDefault) {
  13767. evt.preventDefault();
  13768. }
  13769. }
  13770. }
  13771. };
  13772. this._onLostFocus = function () {
  13773. _this._keys = [];
  13774. };
  13775. element.addEventListener("keydown", this._onKeyDown, false);
  13776. element.addEventListener("keyup", this._onKeyUp, false);
  13777. BABYLON.Tools.RegisterTopRootEvents([
  13778. { name: "blur", handler: this._onLostFocus }
  13779. ]);
  13780. };
  13781. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13782. if (element) {
  13783. element.removeEventListener("keydown", this._onKeyDown);
  13784. element.removeEventListener("keyup", this._onKeyUp);
  13785. }
  13786. BABYLON.Tools.UnregisterTopRootEvents([
  13787. { name: "blur", handler: this._onLostFocus }
  13788. ]);
  13789. this._keys = [];
  13790. this._onKeyDown = null;
  13791. this._onKeyUp = null;
  13792. this._onLostFocus = null;
  13793. };
  13794. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13795. if (this._onKeyDown) {
  13796. var camera = this.camera;
  13797. for (var index = 0; index < this._keys.length; index++) {
  13798. var keyCode = this._keys[index];
  13799. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13800. camera.inertialAlphaOffset -= 0.01;
  13801. }
  13802. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13803. camera.inertialBetaOffset -= 0.01;
  13804. }
  13805. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13806. camera.inertialAlphaOffset += 0.01;
  13807. }
  13808. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13809. camera.inertialBetaOffset += 0.01;
  13810. }
  13811. }
  13812. }
  13813. };
  13814. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13815. return "ArcRotateCameraKeyboardMoveInput";
  13816. };
  13817. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13818. return "keyboard";
  13819. };
  13820. __decorate([
  13821. BABYLON.serialize()
  13822. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13823. __decorate([
  13824. BABYLON.serialize()
  13825. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13826. __decorate([
  13827. BABYLON.serialize()
  13828. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13829. __decorate([
  13830. BABYLON.serialize()
  13831. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13832. return ArcRotateCameraKeyboardMoveInput;
  13833. })();
  13834. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  13835. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  13836. })(BABYLON || (BABYLON = {}));
  13837. var BABYLON;
  13838. (function (BABYLON) {
  13839. var ArcRotateCameraMouseWheelInput = (function () {
  13840. function ArcRotateCameraMouseWheelInput() {
  13841. this.wheelPrecision = 3.0;
  13842. }
  13843. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  13844. var _this = this;
  13845. this._wheel = function (p, s) {
  13846. //sanity check - this should be a PointerWheel event.
  13847. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  13848. return;
  13849. var event = p.event;
  13850. var delta = 0;
  13851. if (event.wheelDelta) {
  13852. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  13853. }
  13854. else if (event.detail) {
  13855. delta = -event.detail / _this.wheelPrecision;
  13856. }
  13857. if (delta)
  13858. _this.camera.inertialRadiusOffset += delta;
  13859. if (event.preventDefault) {
  13860. if (!noPreventDefault) {
  13861. event.preventDefault();
  13862. }
  13863. }
  13864. };
  13865. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  13866. };
  13867. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  13868. if (this._observer && element) {
  13869. this.camera.getScene().onPointerObservable.remove(this._observer);
  13870. this._observer = null;
  13871. this._wheel = null;
  13872. }
  13873. };
  13874. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  13875. return "ArcRotateCameraMouseWheelInput";
  13876. };
  13877. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  13878. return "mousewheel";
  13879. };
  13880. __decorate([
  13881. BABYLON.serialize()
  13882. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  13883. return ArcRotateCameraMouseWheelInput;
  13884. })();
  13885. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  13886. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  13887. })(BABYLON || (BABYLON = {}));
  13888. var BABYLON;
  13889. (function (BABYLON) {
  13890. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13891. var ArcRotateCameraPointersInput = (function () {
  13892. function ArcRotateCameraPointersInput() {
  13893. this.angularSensibilityX = 1000.0;
  13894. this.angularSensibilityY = 1000.0;
  13895. this.pinchPrecision = 6.0;
  13896. this.panningSensibility = 50.0;
  13897. this._isPanClick = false;
  13898. this.pinchInwards = true;
  13899. }
  13900. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  13901. var _this = this;
  13902. var engine = this.camera.getEngine();
  13903. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  13904. var pointA, pointB;
  13905. var previousPinchDistance = 0;
  13906. this._pointerInput = function (p, s) {
  13907. var evt = p.event;
  13908. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13909. try {
  13910. evt.srcElement.setPointerCapture(evt.pointerId);
  13911. }
  13912. catch (e) {
  13913. }
  13914. // Manage panning with pan button click
  13915. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  13916. // manage pointers
  13917. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  13918. if (pointA === undefined) {
  13919. pointA = cacheSoloPointer;
  13920. }
  13921. else if (pointB === undefined) {
  13922. pointB = cacheSoloPointer;
  13923. }
  13924. if (!noPreventDefault) {
  13925. evt.preventDefault();
  13926. element.focus();
  13927. }
  13928. }
  13929. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13930. try {
  13931. evt.srcElement.releasePointerCapture(evt.pointerId);
  13932. }
  13933. catch (e) {
  13934. }
  13935. cacheSoloPointer = null;
  13936. previousPinchDistance = 0;
  13937. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  13938. //but emptying completly pointers collection is required to fix a bug on iPhone :
  13939. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  13940. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  13941. pointA = pointB = undefined;
  13942. if (!noPreventDefault) {
  13943. evt.preventDefault();
  13944. }
  13945. }
  13946. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13947. if (!noPreventDefault) {
  13948. evt.preventDefault();
  13949. }
  13950. // One button down
  13951. if (pointA && pointB === undefined) {
  13952. if (_this.panningSensibility !== 0 &&
  13953. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  13954. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  13955. _this.camera
  13956. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  13957. _this.camera
  13958. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  13959. }
  13960. else {
  13961. var offsetX = evt.clientX - cacheSoloPointer.x;
  13962. var offsetY = evt.clientY - cacheSoloPointer.y;
  13963. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  13964. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  13965. }
  13966. cacheSoloPointer.x = evt.clientX;
  13967. cacheSoloPointer.y = evt.clientY;
  13968. }
  13969. else if (pointA && pointB) {
  13970. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  13971. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  13972. ed.x = evt.clientX;
  13973. ed.y = evt.clientY;
  13974. var direction = _this.pinchInwards ? 1 : -1;
  13975. var distX = pointA.x - pointB.x;
  13976. var distY = pointA.y - pointB.y;
  13977. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  13978. if (previousPinchDistance === 0) {
  13979. previousPinchDistance = pinchSquaredDistance;
  13980. return;
  13981. }
  13982. if (pinchSquaredDistance !== previousPinchDistance) {
  13983. _this.camera
  13984. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  13985. (_this.pinchPrecision *
  13986. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  13987. direction);
  13988. previousPinchDistance = pinchSquaredDistance;
  13989. }
  13990. }
  13991. }
  13992. };
  13993. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13994. this._onContextMenu = function (evt) {
  13995. evt.preventDefault();
  13996. };
  13997. if (!this.camera._useCtrlForPanning) {
  13998. element.addEventListener("contextmenu", this._onContextMenu, false);
  13999. }
  14000. this._onLostFocus = function () {
  14001. //this._keys = [];
  14002. pointA = pointB = undefined;
  14003. previousPinchDistance = 0;
  14004. cacheSoloPointer = null;
  14005. };
  14006. this._onMouseMove = function (evt) {
  14007. if (!engine.isPointerLock) {
  14008. return;
  14009. }
  14010. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  14011. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  14012. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14013. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14014. if (!noPreventDefault) {
  14015. evt.preventDefault();
  14016. }
  14017. };
  14018. this._onGestureStart = function (e) {
  14019. if (window.MSGesture === undefined) {
  14020. return;
  14021. }
  14022. if (!_this._MSGestureHandler) {
  14023. _this._MSGestureHandler = new MSGesture();
  14024. _this._MSGestureHandler.target = element;
  14025. }
  14026. _this._MSGestureHandler.addPointer(e.pointerId);
  14027. };
  14028. this._onGesture = function (e) {
  14029. _this.camera.radius *= e.scale;
  14030. if (e.preventDefault) {
  14031. if (!noPreventDefault) {
  14032. e.stopPropagation();
  14033. e.preventDefault();
  14034. }
  14035. }
  14036. };
  14037. element.addEventListener("mousemove", this._onMouseMove, false);
  14038. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  14039. element.addEventListener("MSGestureChange", this._onGesture, false);
  14040. element.addEventListener("keydown", this._onKeyDown, false);
  14041. element.addEventListener("keyup", this._onKeyUp, false);
  14042. BABYLON.Tools.RegisterTopRootEvents([
  14043. { name: "blur", handler: this._onLostFocus }
  14044. ]);
  14045. };
  14046. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  14047. if (element && this._observer) {
  14048. this.camera.getScene().onPointerObservable.remove(this._observer);
  14049. this._observer = null;
  14050. element.removeEventListener("contextmenu", this._onContextMenu);
  14051. element.removeEventListener("mousemove", this._onMouseMove);
  14052. element.removeEventListener("MSPointerDown", this._onGestureStart);
  14053. element.removeEventListener("MSGestureChange", this._onGesture);
  14054. element.removeEventListener("keydown", this._onKeyDown);
  14055. element.removeEventListener("keyup", this._onKeyUp);
  14056. this._isPanClick = false;
  14057. this.pinchInwards = true;
  14058. this._onKeyDown = null;
  14059. this._onKeyUp = null;
  14060. this._onMouseMove = null;
  14061. this._onGestureStart = null;
  14062. this._onGesture = null;
  14063. this._MSGestureHandler = null;
  14064. this._onLostFocus = null;
  14065. this._onContextMenu = null;
  14066. }
  14067. BABYLON.Tools.UnregisterTopRootEvents([
  14068. { name: "blur", handler: this._onLostFocus }
  14069. ]);
  14070. };
  14071. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  14072. return "ArcRotateCameraPointersInput";
  14073. };
  14074. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  14075. return "pointers";
  14076. };
  14077. __decorate([
  14078. BABYLON.serialize()
  14079. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  14080. __decorate([
  14081. BABYLON.serialize()
  14082. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  14083. __decorate([
  14084. BABYLON.serialize()
  14085. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  14086. __decorate([
  14087. BABYLON.serialize()
  14088. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  14089. return ArcRotateCameraPointersInput;
  14090. })();
  14091. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  14092. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  14093. })(BABYLON || (BABYLON = {}));
  14094. var BABYLON;
  14095. (function (BABYLON) {
  14096. var ArcRotateCameraGamepadInput = (function () {
  14097. function ArcRotateCameraGamepadInput() {
  14098. this.gamepadRotationSensibility = 80;
  14099. this.gamepadMoveSensibility = 40;
  14100. }
  14101. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14102. var _this = this;
  14103. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14104. };
  14105. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  14106. if (this._gamepads) {
  14107. this._gamepads.dispose();
  14108. }
  14109. this.gamepad = null;
  14110. };
  14111. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  14112. if (this.gamepad) {
  14113. var camera = this.camera;
  14114. var RSValues = this.gamepad.rightStick;
  14115. if (RSValues.x != 0) {
  14116. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  14117. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  14118. camera.inertialAlphaOffset += normalizedRX;
  14119. }
  14120. }
  14121. if (RSValues.y != 0) {
  14122. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  14123. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  14124. camera.inertialBetaOffset += normalizedRY;
  14125. }
  14126. }
  14127. var LSValues = this.gamepad.leftStick;
  14128. if (LSValues.y != 0) {
  14129. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14130. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  14131. this.camera.inertialRadiusOffset -= normalizedLY;
  14132. }
  14133. }
  14134. }
  14135. };
  14136. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14137. // Only the first gamepad can control the camera
  14138. if (gamepad.index === 0) {
  14139. this.gamepad = gamepad;
  14140. }
  14141. };
  14142. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  14143. return "ArcRotateCameraGamepadInput";
  14144. };
  14145. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  14146. return "gamepad";
  14147. };
  14148. __decorate([
  14149. BABYLON.serialize()
  14150. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  14151. __decorate([
  14152. BABYLON.serialize()
  14153. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14154. return ArcRotateCameraGamepadInput;
  14155. })();
  14156. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  14157. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  14158. })(BABYLON || (BABYLON = {}));
  14159. var BABYLON;
  14160. (function (BABYLON) {
  14161. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  14162. function ArcRotateCameraVRDeviceOrientationInput() {
  14163. this.alphaCorrection = 1;
  14164. this.betaCorrection = 1;
  14165. this.gammaCorrection = 1;
  14166. this._alpha = 0;
  14167. this._beta = 0;
  14168. this._gamma = 0;
  14169. this._dirty = false;
  14170. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  14171. }
  14172. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14173. this.camera.attachControl(element, noPreventDefault);
  14174. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  14175. };
  14176. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  14177. var camera = this.camera;
  14178. this._alpha = +evt.alpha | 0;
  14179. this._beta = +evt.beta | 0;
  14180. this._gamma = +evt.gamma | 0;
  14181. this._dirty = true;
  14182. };
  14183. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  14184. if (this._dirty) {
  14185. this._dirty = false;
  14186. if (this._gamma < 0) {
  14187. this._gamma = 180 + this._gamma;
  14188. }
  14189. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  14190. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  14191. }
  14192. };
  14193. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  14194. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  14195. };
  14196. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  14197. return "ArcRotateCameraVRDeviceOrientationInput";
  14198. };
  14199. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  14200. return "VRDeviceOrientation";
  14201. };
  14202. return ArcRotateCameraVRDeviceOrientationInput;
  14203. })();
  14204. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  14205. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  14206. })(BABYLON || (BABYLON = {}));
  14207. var BABYLON;
  14208. (function (BABYLON) {
  14209. var TargetCamera = (function (_super) {
  14210. __extends(TargetCamera, _super);
  14211. function TargetCamera(name, position, scene) {
  14212. _super.call(this, name, position, scene);
  14213. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14214. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14215. this.rotation = new BABYLON.Vector3(0, 0, 0);
  14216. this.speed = 2.0;
  14217. this.noRotationConstraint = false;
  14218. this.lockedTarget = null;
  14219. this._currentTarget = BABYLON.Vector3.Zero();
  14220. this._viewMatrix = BABYLON.Matrix.Zero();
  14221. this._camMatrix = BABYLON.Matrix.Zero();
  14222. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  14223. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  14224. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  14225. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  14226. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  14227. this._lookAtTemp = BABYLON.Matrix.Zero();
  14228. this._tempMatrix = BABYLON.Matrix.Zero();
  14229. }
  14230. TargetCamera.prototype.getFrontPosition = function (distance) {
  14231. var direction = this.getTarget().subtract(this.position);
  14232. direction.normalize();
  14233. direction.scaleInPlace(distance);
  14234. return this.globalPosition.add(direction);
  14235. };
  14236. TargetCamera.prototype._getLockedTargetPosition = function () {
  14237. if (!this.lockedTarget) {
  14238. return null;
  14239. }
  14240. return this.lockedTarget.position || this.lockedTarget;
  14241. };
  14242. // Cache
  14243. TargetCamera.prototype._initCache = function () {
  14244. _super.prototype._initCache.call(this);
  14245. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14246. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14247. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14248. };
  14249. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  14250. if (!ignoreParentClass) {
  14251. _super.prototype._updateCache.call(this);
  14252. }
  14253. var lockedTargetPosition = this._getLockedTargetPosition();
  14254. if (!lockedTargetPosition) {
  14255. this._cache.lockedTarget = null;
  14256. }
  14257. else {
  14258. if (!this._cache.lockedTarget) {
  14259. this._cache.lockedTarget = lockedTargetPosition.clone();
  14260. }
  14261. else {
  14262. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  14263. }
  14264. }
  14265. this._cache.rotation.copyFrom(this.rotation);
  14266. if (this.rotationQuaternion)
  14267. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14268. };
  14269. // Synchronized
  14270. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  14271. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  14272. return false;
  14273. }
  14274. var lockedTargetPosition = this._getLockedTargetPosition();
  14275. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  14276. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  14277. };
  14278. // Methods
  14279. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  14280. var engine = this.getEngine();
  14281. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  14282. };
  14283. // Target
  14284. TargetCamera.prototype.setTarget = function (target) {
  14285. this.upVector.normalize();
  14286. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  14287. this._camMatrix.invert();
  14288. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  14289. var vDir = target.subtract(this.position);
  14290. if (vDir.x >= 0.0) {
  14291. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  14292. }
  14293. else {
  14294. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  14295. }
  14296. this.rotation.z = 0;
  14297. if (isNaN(this.rotation.x)) {
  14298. this.rotation.x = 0;
  14299. }
  14300. if (isNaN(this.rotation.y)) {
  14301. this.rotation.y = 0;
  14302. }
  14303. if (isNaN(this.rotation.z)) {
  14304. this.rotation.z = 0;
  14305. }
  14306. if (this.rotationQuaternion) {
  14307. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  14308. }
  14309. };
  14310. TargetCamera.prototype.getTarget = function () {
  14311. return this._currentTarget;
  14312. };
  14313. TargetCamera.prototype._decideIfNeedsToMove = function () {
  14314. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14315. };
  14316. TargetCamera.prototype._updatePosition = function () {
  14317. this.position.addInPlace(this.cameraDirection);
  14318. };
  14319. TargetCamera.prototype._checkInputs = function () {
  14320. var needToMove = this._decideIfNeedsToMove();
  14321. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  14322. // Move
  14323. if (needToMove) {
  14324. this._updatePosition();
  14325. }
  14326. // Rotate
  14327. if (needToRotate) {
  14328. this.rotation.x += this.cameraRotation.x;
  14329. this.rotation.y += this.cameraRotation.y;
  14330. if (!this.noRotationConstraint) {
  14331. var limit = (Math.PI / 2) * 0.95;
  14332. if (this.rotation.x > limit)
  14333. this.rotation.x = limit;
  14334. if (this.rotation.x < -limit)
  14335. this.rotation.x = -limit;
  14336. }
  14337. }
  14338. // Inertia
  14339. if (needToMove) {
  14340. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  14341. this.cameraDirection.x = 0;
  14342. }
  14343. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  14344. this.cameraDirection.y = 0;
  14345. }
  14346. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  14347. this.cameraDirection.z = 0;
  14348. }
  14349. this.cameraDirection.scaleInPlace(this.inertia);
  14350. }
  14351. if (needToRotate) {
  14352. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  14353. this.cameraRotation.x = 0;
  14354. }
  14355. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  14356. this.cameraRotation.y = 0;
  14357. }
  14358. this.cameraRotation.scaleInPlace(this.inertia);
  14359. }
  14360. _super.prototype._checkInputs.call(this);
  14361. };
  14362. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  14363. if (this.rotationQuaternion) {
  14364. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  14365. //update the up vector!
  14366. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  14367. }
  14368. else {
  14369. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  14370. }
  14371. };
  14372. TargetCamera.prototype._getViewMatrix = function () {
  14373. if (!this.lockedTarget) {
  14374. // Compute
  14375. this._updateCameraRotationMatrix();
  14376. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  14377. // Computing target and final matrix
  14378. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  14379. }
  14380. else {
  14381. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  14382. }
  14383. if (this.getScene().useRightHandedSystem) {
  14384. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14385. }
  14386. else {
  14387. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14388. }
  14389. return this._viewMatrix;
  14390. };
  14391. /**
  14392. * @override
  14393. * Override Camera.createRigCamera
  14394. */
  14395. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14396. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  14397. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  14398. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  14399. if (!this.rotationQuaternion) {
  14400. this.rotationQuaternion = new BABYLON.Quaternion();
  14401. }
  14402. rigCamera._cameraRigParams = {};
  14403. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  14404. }
  14405. return rigCamera;
  14406. }
  14407. return null;
  14408. };
  14409. /**
  14410. * @override
  14411. * Override Camera._updateRigCameras
  14412. */
  14413. TargetCamera.prototype._updateRigCameras = function () {
  14414. var camLeft = this._rigCameras[0];
  14415. var camRight = this._rigCameras[1];
  14416. switch (this.cameraRigMode) {
  14417. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14418. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14419. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14420. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14421. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  14422. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  14423. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  14424. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  14425. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  14426. camLeft.setTarget(this.getTarget());
  14427. camRight.setTarget(this.getTarget());
  14428. break;
  14429. case BABYLON.Camera.RIG_MODE_VR:
  14430. case BABYLON.Camera.RIG_MODE_WEBVR:
  14431. if (camLeft.rotationQuaternion) {
  14432. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14433. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14434. }
  14435. else {
  14436. camLeft.rotation.copyFrom(this.rotation);
  14437. camRight.rotation.copyFrom(this.rotation);
  14438. }
  14439. camLeft.position.copyFrom(this.position);
  14440. camRight.position.copyFrom(this.position);
  14441. break;
  14442. }
  14443. _super.prototype._updateRigCameras.call(this);
  14444. };
  14445. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  14446. if (!this._rigCamTransformMatrix) {
  14447. this._rigCamTransformMatrix = new BABYLON.Matrix();
  14448. }
  14449. var target = this.getTarget();
  14450. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  14451. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  14452. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  14453. };
  14454. TargetCamera.prototype.getTypeName = function () {
  14455. return "TargetCamera";
  14456. };
  14457. __decorate([
  14458. BABYLON.serializeAsVector3()
  14459. ], TargetCamera.prototype, "rotation", void 0);
  14460. __decorate([
  14461. BABYLON.serialize()
  14462. ], TargetCamera.prototype, "speed", void 0);
  14463. __decorate([
  14464. BABYLON.serializeAsMeshReference("lockedTargetId")
  14465. ], TargetCamera.prototype, "lockedTarget", void 0);
  14466. return TargetCamera;
  14467. })(BABYLON.Camera);
  14468. BABYLON.TargetCamera = TargetCamera;
  14469. })(BABYLON || (BABYLON = {}));
  14470. var BABYLON;
  14471. (function (BABYLON) {
  14472. var FreeCamera = (function (_super) {
  14473. __extends(FreeCamera, _super);
  14474. function FreeCamera(name, position, scene) {
  14475. var _this = this;
  14476. _super.call(this, name, position, scene);
  14477. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  14478. this.checkCollisions = false;
  14479. this.applyGravity = false;
  14480. this._collider = new BABYLON.Collider();
  14481. this._needMoveForGravity = false;
  14482. this._oldPosition = BABYLON.Vector3.Zero();
  14483. this._diffPosition = BABYLON.Vector3.Zero();
  14484. this._newPosition = BABYLON.Vector3.Zero();
  14485. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14486. if (collidedMesh === void 0) { collidedMesh = null; }
  14487. //TODO move this to the collision coordinator!
  14488. if (_this.getScene().workerCollisions)
  14489. newPosition.multiplyInPlace(_this._collider.radius);
  14490. var updatePosition = function (newPos) {
  14491. _this._newPosition.copyFrom(newPos);
  14492. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  14493. var oldPosition = _this.position.clone();
  14494. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  14495. _this.position.addInPlace(_this._diffPosition);
  14496. if (_this.onCollide && collidedMesh) {
  14497. _this.onCollide(collidedMesh);
  14498. }
  14499. }
  14500. };
  14501. updatePosition(newPosition);
  14502. };
  14503. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  14504. this.inputs.addKeyboard().addMouse();
  14505. }
  14506. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  14507. //-- begin properties for backward compatibility for inputs
  14508. get: function () {
  14509. var mouse = this.inputs.attached["mouse"];
  14510. if (mouse)
  14511. return mouse.angularSensibility;
  14512. },
  14513. set: function (value) {
  14514. var mouse = this.inputs.attached["mouse"];
  14515. if (mouse)
  14516. mouse.angularSensibility = value;
  14517. },
  14518. enumerable: true,
  14519. configurable: true
  14520. });
  14521. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  14522. get: function () {
  14523. var keyboard = this.inputs.attached["keyboard"];
  14524. if (keyboard)
  14525. return keyboard.keysUp;
  14526. },
  14527. set: function (value) {
  14528. var keyboard = this.inputs.attached["keyboard"];
  14529. if (keyboard)
  14530. keyboard.keysUp = value;
  14531. },
  14532. enumerable: true,
  14533. configurable: true
  14534. });
  14535. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  14536. get: function () {
  14537. var keyboard = this.inputs.attached["keyboard"];
  14538. if (keyboard)
  14539. return keyboard.keysDown;
  14540. },
  14541. set: function (value) {
  14542. var keyboard = this.inputs.attached["keyboard"];
  14543. if (keyboard)
  14544. keyboard.keysDown = value;
  14545. },
  14546. enumerable: true,
  14547. configurable: true
  14548. });
  14549. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  14550. get: function () {
  14551. var keyboard = this.inputs.attached["keyboard"];
  14552. if (keyboard)
  14553. return keyboard.keysLeft;
  14554. },
  14555. set: function (value) {
  14556. var keyboard = this.inputs.attached["keyboard"];
  14557. if (keyboard)
  14558. keyboard.keysLeft = value;
  14559. },
  14560. enumerable: true,
  14561. configurable: true
  14562. });
  14563. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  14564. get: function () {
  14565. var keyboard = this.inputs.attached["keyboard"];
  14566. if (keyboard)
  14567. return keyboard.keysRight;
  14568. },
  14569. set: function (value) {
  14570. var keyboard = this.inputs.attached["keyboard"];
  14571. if (keyboard)
  14572. keyboard.keysRight = value;
  14573. },
  14574. enumerable: true,
  14575. configurable: true
  14576. });
  14577. // Controls
  14578. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  14579. this.inputs.attachElement(element, noPreventDefault);
  14580. };
  14581. FreeCamera.prototype.detachControl = function (element) {
  14582. this.inputs.detachElement(element);
  14583. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14584. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14585. };
  14586. FreeCamera.prototype._collideWithWorld = function (velocity) {
  14587. var globalPosition;
  14588. if (this.parent) {
  14589. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  14590. }
  14591. else {
  14592. globalPosition = this.position;
  14593. }
  14594. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  14595. this._collider.radius = this.ellipsoid;
  14596. //no need for clone, as long as gravity is not on.
  14597. var actualVelocity = velocity;
  14598. //add gravity to the velocity to prevent the dual-collision checking
  14599. if (this.applyGravity) {
  14600. //this prevents mending with cameraDirection, a global variable of the free camera class.
  14601. actualVelocity = velocity.add(this.getScene().gravity);
  14602. }
  14603. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14604. };
  14605. FreeCamera.prototype._checkInputs = function () {
  14606. if (!this._localDirection) {
  14607. this._localDirection = BABYLON.Vector3.Zero();
  14608. this._transformedDirection = BABYLON.Vector3.Zero();
  14609. }
  14610. this.inputs.checkInputs();
  14611. _super.prototype._checkInputs.call(this);
  14612. };
  14613. FreeCamera.prototype._decideIfNeedsToMove = function () {
  14614. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14615. };
  14616. FreeCamera.prototype._updatePosition = function () {
  14617. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  14618. this._collideWithWorld(this.cameraDirection);
  14619. }
  14620. else {
  14621. this.position.addInPlace(this.cameraDirection);
  14622. }
  14623. };
  14624. FreeCamera.prototype.dispose = function () {
  14625. this.inputs.clear();
  14626. _super.prototype.dispose.call(this);
  14627. };
  14628. FreeCamera.prototype.getTypeName = function () {
  14629. return "FreeCamera";
  14630. };
  14631. __decorate([
  14632. BABYLON.serializeAsVector3()
  14633. ], FreeCamera.prototype, "ellipsoid", void 0);
  14634. __decorate([
  14635. BABYLON.serialize()
  14636. ], FreeCamera.prototype, "checkCollisions", void 0);
  14637. __decorate([
  14638. BABYLON.serialize()
  14639. ], FreeCamera.prototype, "applyGravity", void 0);
  14640. return FreeCamera;
  14641. })(BABYLON.TargetCamera);
  14642. BABYLON.FreeCamera = FreeCamera;
  14643. })(BABYLON || (BABYLON = {}));
  14644. var BABYLON;
  14645. (function (BABYLON) {
  14646. var FreeCameraInputsManager = (function (_super) {
  14647. __extends(FreeCameraInputsManager, _super);
  14648. function FreeCameraInputsManager(camera) {
  14649. _super.call(this, camera);
  14650. }
  14651. FreeCameraInputsManager.prototype.addKeyboard = function () {
  14652. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  14653. return this;
  14654. };
  14655. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  14656. if (touchEnabled === void 0) { touchEnabled = true; }
  14657. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  14658. return this;
  14659. };
  14660. FreeCameraInputsManager.prototype.addGamepad = function () {
  14661. this.add(new BABYLON.FreeCameraGamepadInput());
  14662. return this;
  14663. };
  14664. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  14665. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  14666. return this;
  14667. };
  14668. FreeCameraInputsManager.prototype.addTouch = function () {
  14669. this.add(new BABYLON.FreeCameraTouchInput());
  14670. return this;
  14671. };
  14672. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  14673. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  14674. return this;
  14675. };
  14676. return FreeCameraInputsManager;
  14677. })(BABYLON.CameraInputsManager);
  14678. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  14679. })(BABYLON || (BABYLON = {}));
  14680. var BABYLON;
  14681. (function (BABYLON) {
  14682. var FollowCamera = (function (_super) {
  14683. __extends(FollowCamera, _super);
  14684. function FollowCamera(name, position, scene, target) {
  14685. _super.call(this, name, position, scene);
  14686. this.radius = 12;
  14687. this.rotationOffset = 0;
  14688. this.heightOffset = 4;
  14689. this.cameraAcceleration = 0.05;
  14690. this.maxCameraSpeed = 20;
  14691. this.target = target;
  14692. }
  14693. FollowCamera.prototype.getRadians = function (degrees) {
  14694. return degrees * Math.PI / 180;
  14695. };
  14696. FollowCamera.prototype.follow = function (cameraTarget) {
  14697. if (!cameraTarget)
  14698. return;
  14699. var yRotation;
  14700. if (cameraTarget.rotationQuaternion) {
  14701. var rotMatrix = new BABYLON.Matrix();
  14702. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  14703. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  14704. }
  14705. else {
  14706. yRotation = cameraTarget.rotation.y;
  14707. }
  14708. var radians = this.getRadians(this.rotationOffset) + yRotation;
  14709. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  14710. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  14711. var dx = targetX - this.position.x;
  14712. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  14713. var dz = (targetZ) - this.position.z;
  14714. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  14715. var vy = dy * this.cameraAcceleration;
  14716. var vz = dz * this.cameraAcceleration * 2;
  14717. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  14718. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14719. }
  14720. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  14721. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14722. }
  14723. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  14724. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14725. }
  14726. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  14727. this.setTarget(cameraTarget.position);
  14728. };
  14729. FollowCamera.prototype._checkInputs = function () {
  14730. _super.prototype._checkInputs.call(this);
  14731. this.follow(this.target);
  14732. };
  14733. FollowCamera.prototype.getTypeName = function () {
  14734. return "FollowCamera";
  14735. };
  14736. __decorate([
  14737. BABYLON.serialize()
  14738. ], FollowCamera.prototype, "radius", void 0);
  14739. __decorate([
  14740. BABYLON.serialize()
  14741. ], FollowCamera.prototype, "rotationOffset", void 0);
  14742. __decorate([
  14743. BABYLON.serialize()
  14744. ], FollowCamera.prototype, "heightOffset", void 0);
  14745. __decorate([
  14746. BABYLON.serialize()
  14747. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  14748. __decorate([
  14749. BABYLON.serialize()
  14750. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  14751. __decorate([
  14752. BABYLON.serializeAsMeshReference("lockedTargetId")
  14753. ], FollowCamera.prototype, "target", void 0);
  14754. return FollowCamera;
  14755. })(BABYLON.TargetCamera);
  14756. BABYLON.FollowCamera = FollowCamera;
  14757. var ArcFollowCamera = (function (_super) {
  14758. __extends(ArcFollowCamera, _super);
  14759. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  14760. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14761. this.alpha = alpha;
  14762. this.beta = beta;
  14763. this.radius = radius;
  14764. this.target = target;
  14765. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  14766. this.follow();
  14767. }
  14768. ArcFollowCamera.prototype.follow = function () {
  14769. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  14770. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  14771. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  14772. this.position = this.target.position.add(this._cartesianCoordinates);
  14773. this.setTarget(this.target.position);
  14774. };
  14775. ArcFollowCamera.prototype._checkInputs = function () {
  14776. _super.prototype._checkInputs.call(this);
  14777. this.follow();
  14778. };
  14779. ArcFollowCamera.prototype.getTypeName = function () {
  14780. return "ArcFollowCamera";
  14781. };
  14782. return ArcFollowCamera;
  14783. })(BABYLON.TargetCamera);
  14784. BABYLON.ArcFollowCamera = ArcFollowCamera;
  14785. })(BABYLON || (BABYLON = {}));
  14786. var BABYLON;
  14787. (function (BABYLON) {
  14788. // We're mainly based on the logic defined into the FreeCamera code
  14789. var TouchCamera = (function (_super) {
  14790. __extends(TouchCamera, _super);
  14791. //-- end properties for backward compatibility for inputs
  14792. function TouchCamera(name, position, scene) {
  14793. _super.call(this, name, position, scene);
  14794. this.inputs.addTouch();
  14795. this._setupInputs();
  14796. }
  14797. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  14798. //-- Begin properties for backward compatibility for inputs
  14799. get: function () {
  14800. var touch = this.inputs.attached["touch"];
  14801. if (touch)
  14802. return touch.touchAngularSensibility;
  14803. },
  14804. set: function (value) {
  14805. var touch = this.inputs.attached["touch"];
  14806. if (touch)
  14807. touch.touchAngularSensibility = value;
  14808. },
  14809. enumerable: true,
  14810. configurable: true
  14811. });
  14812. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  14813. get: function () {
  14814. var touch = this.inputs.attached["touch"];
  14815. if (touch)
  14816. return touch.touchMoveSensibility;
  14817. },
  14818. set: function (value) {
  14819. var touch = this.inputs.attached["touch"];
  14820. if (touch)
  14821. touch.touchMoveSensibility = value;
  14822. },
  14823. enumerable: true,
  14824. configurable: true
  14825. });
  14826. TouchCamera.prototype.getTypeName = function () {
  14827. return "TouchCamera";
  14828. };
  14829. TouchCamera.prototype._setupInputs = function () {
  14830. var mouse = this.inputs.attached["mouse"];
  14831. if (mouse) {
  14832. mouse.touchEnabled = false;
  14833. }
  14834. };
  14835. return TouchCamera;
  14836. })(BABYLON.FreeCamera);
  14837. BABYLON.TouchCamera = TouchCamera;
  14838. })(BABYLON || (BABYLON = {}));
  14839. var BABYLON;
  14840. (function (BABYLON) {
  14841. var ArcRotateCamera = (function (_super) {
  14842. __extends(ArcRotateCamera, _super);
  14843. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  14844. var _this = this;
  14845. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14846. this.inertialAlphaOffset = 0;
  14847. this.inertialBetaOffset = 0;
  14848. this.inertialRadiusOffset = 0;
  14849. this.lowerAlphaLimit = null;
  14850. this.upperAlphaLimit = null;
  14851. this.lowerBetaLimit = 0.01;
  14852. this.upperBetaLimit = Math.PI;
  14853. this.lowerRadiusLimit = null;
  14854. this.upperRadiusLimit = null;
  14855. this.inertialPanningX = 0;
  14856. this.inertialPanningY = 0;
  14857. //-- end properties for backward compatibility for inputs
  14858. this.zoomOnFactor = 1;
  14859. this.targetScreenOffset = BABYLON.Vector2.Zero();
  14860. this.allowUpsideDown = true;
  14861. this._viewMatrix = new BABYLON.Matrix();
  14862. // Panning
  14863. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  14864. this.checkCollisions = false;
  14865. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14866. this._collider = new BABYLON.Collider();
  14867. this._previousPosition = BABYLON.Vector3.Zero();
  14868. this._collisionVelocity = BABYLON.Vector3.Zero();
  14869. this._newPosition = BABYLON.Vector3.Zero();
  14870. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14871. if (collidedMesh === void 0) { collidedMesh = null; }
  14872. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  14873. newPosition.multiplyInPlace(_this._collider.radius);
  14874. }
  14875. if (!collidedMesh) {
  14876. _this._previousPosition.copyFrom(_this.position);
  14877. }
  14878. else {
  14879. _this.setPosition(newPosition);
  14880. if (_this.onCollide) {
  14881. _this.onCollide(collidedMesh);
  14882. }
  14883. }
  14884. // Recompute because of constraints
  14885. var cosa = Math.cos(_this.alpha);
  14886. var sina = Math.sin(_this.alpha);
  14887. var cosb = Math.cos(_this.beta);
  14888. var sinb = Math.sin(_this.beta);
  14889. if (sinb === 0) {
  14890. sinb = 0.0001;
  14891. }
  14892. var target = _this._getTargetPosition();
  14893. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  14894. _this.position.copyFrom(_this._newPosition);
  14895. var up = _this.upVector;
  14896. if (_this.allowUpsideDown && _this.beta < 0) {
  14897. up = up.clone();
  14898. up = up.negate();
  14899. }
  14900. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  14901. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  14902. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  14903. _this._collisionTriggered = false;
  14904. };
  14905. if (!target) {
  14906. this.target = BABYLON.Vector3.Zero();
  14907. }
  14908. else {
  14909. this.target = target;
  14910. }
  14911. this.alpha = alpha;
  14912. this.beta = beta;
  14913. this.radius = radius;
  14914. this.getViewMatrix();
  14915. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  14916. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  14917. }
  14918. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  14919. //-- begin properties for backward compatibility for inputs
  14920. get: function () {
  14921. var pointers = this.inputs.attached["pointers"];
  14922. if (pointers)
  14923. return pointers.angularSensibilityX;
  14924. },
  14925. set: function (value) {
  14926. var pointers = this.inputs.attached["pointers"];
  14927. if (pointers) {
  14928. pointers.angularSensibilityX = value;
  14929. }
  14930. },
  14931. enumerable: true,
  14932. configurable: true
  14933. });
  14934. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  14935. get: function () {
  14936. var pointers = this.inputs.attached["pointers"];
  14937. if (pointers)
  14938. return pointers.angularSensibilityY;
  14939. },
  14940. set: function (value) {
  14941. var pointers = this.inputs.attached["pointers"];
  14942. if (pointers) {
  14943. pointers.angularSensibilityY = value;
  14944. }
  14945. },
  14946. enumerable: true,
  14947. configurable: true
  14948. });
  14949. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  14950. get: function () {
  14951. var pointers = this.inputs.attached["pointers"];
  14952. if (pointers)
  14953. return pointers.pinchPrecision;
  14954. },
  14955. set: function (value) {
  14956. var pointers = this.inputs.attached["pointers"];
  14957. if (pointers) {
  14958. pointers.pinchPrecision = value;
  14959. }
  14960. },
  14961. enumerable: true,
  14962. configurable: true
  14963. });
  14964. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  14965. get: function () {
  14966. var pointers = this.inputs.attached["pointers"];
  14967. if (pointers)
  14968. return pointers.panningSensibility;
  14969. },
  14970. set: function (value) {
  14971. var pointers = this.inputs.attached["pointers"];
  14972. if (pointers) {
  14973. pointers.panningSensibility = value;
  14974. }
  14975. },
  14976. enumerable: true,
  14977. configurable: true
  14978. });
  14979. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  14980. get: function () {
  14981. var keyboard = this.inputs.attached["keyboard"];
  14982. if (keyboard)
  14983. return keyboard.keysUp;
  14984. },
  14985. set: function (value) {
  14986. var keyboard = this.inputs.attached["keyboard"];
  14987. if (keyboard)
  14988. keyboard.keysUp = value;
  14989. },
  14990. enumerable: true,
  14991. configurable: true
  14992. });
  14993. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  14994. get: function () {
  14995. var keyboard = this.inputs.attached["keyboard"];
  14996. if (keyboard)
  14997. return keyboard.keysDown;
  14998. },
  14999. set: function (value) {
  15000. var keyboard = this.inputs.attached["keyboard"];
  15001. if (keyboard)
  15002. keyboard.keysDown = value;
  15003. },
  15004. enumerable: true,
  15005. configurable: true
  15006. });
  15007. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  15008. get: function () {
  15009. var keyboard = this.inputs.attached["keyboard"];
  15010. if (keyboard)
  15011. return keyboard.keysLeft;
  15012. },
  15013. set: function (value) {
  15014. var keyboard = this.inputs.attached["keyboard"];
  15015. if (keyboard)
  15016. keyboard.keysLeft = value;
  15017. },
  15018. enumerable: true,
  15019. configurable: true
  15020. });
  15021. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  15022. get: function () {
  15023. var keyboard = this.inputs.attached["keyboard"];
  15024. if (keyboard)
  15025. return keyboard.keysRight;
  15026. },
  15027. set: function (value) {
  15028. var keyboard = this.inputs.attached["keyboard"];
  15029. if (keyboard)
  15030. keyboard.keysRight = value;
  15031. },
  15032. enumerable: true,
  15033. configurable: true
  15034. });
  15035. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  15036. get: function () {
  15037. var mousewheel = this.inputs.attached["mousewheel"];
  15038. if (mousewheel)
  15039. return mousewheel.wheelPrecision;
  15040. },
  15041. set: function (value) {
  15042. var mousewheel = this.inputs.attached["mousewheel"];
  15043. if (mousewheel)
  15044. mousewheel.wheelPrecision = value;
  15045. },
  15046. enumerable: true,
  15047. configurable: true
  15048. });
  15049. // Cache
  15050. ArcRotateCamera.prototype._initCache = function () {
  15051. _super.prototype._initCache.call(this);
  15052. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15053. this._cache.alpha = undefined;
  15054. this._cache.beta = undefined;
  15055. this._cache.radius = undefined;
  15056. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  15057. };
  15058. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  15059. if (!ignoreParentClass) {
  15060. _super.prototype._updateCache.call(this);
  15061. }
  15062. this._cache.target.copyFrom(this._getTargetPosition());
  15063. this._cache.alpha = this.alpha;
  15064. this._cache.beta = this.beta;
  15065. this._cache.radius = this.radius;
  15066. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  15067. };
  15068. ArcRotateCamera.prototype._getTargetPosition = function () {
  15069. if (this.target.getAbsolutePosition) {
  15070. var pos = this.target.getAbsolutePosition();
  15071. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  15072. }
  15073. return this.target;
  15074. };
  15075. // Synchronized
  15076. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  15077. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  15078. return false;
  15079. return this._cache.target.equals(this.target)
  15080. && this._cache.alpha === this.alpha
  15081. && this._cache.beta === this.beta
  15082. && this._cache.radius === this.radius
  15083. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  15084. };
  15085. // Methods
  15086. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  15087. var _this = this;
  15088. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  15089. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  15090. this._useCtrlForPanning = useCtrlForPanning;
  15091. this._panningMouseButton = panningMouseButton;
  15092. this.inputs.attachElement(element, noPreventDefault);
  15093. this._reset = function () {
  15094. _this.inertialAlphaOffset = 0;
  15095. _this.inertialBetaOffset = 0;
  15096. _this.inertialRadiusOffset = 0;
  15097. };
  15098. };
  15099. ArcRotateCamera.prototype.detachControl = function (element) {
  15100. this.inputs.detachElement(element);
  15101. if (this._reset) {
  15102. this._reset();
  15103. }
  15104. };
  15105. ArcRotateCamera.prototype._checkInputs = function () {
  15106. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  15107. if (this._collisionTriggered) {
  15108. return;
  15109. }
  15110. this.inputs.checkInputs();
  15111. // Inertia
  15112. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  15113. this.beta += this.inertialBetaOffset;
  15114. if (this.getScene().useRightHandedSystem) {
  15115. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15116. }
  15117. else {
  15118. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15119. }
  15120. this.radius -= this.inertialRadiusOffset;
  15121. this.inertialAlphaOffset *= this.inertia;
  15122. this.inertialBetaOffset *= this.inertia;
  15123. this.inertialRadiusOffset *= this.inertia;
  15124. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  15125. this.inertialAlphaOffset = 0;
  15126. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  15127. this.inertialBetaOffset = 0;
  15128. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  15129. this.inertialRadiusOffset = 0;
  15130. }
  15131. // Panning inertia
  15132. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  15133. if (!this._localDirection) {
  15134. this._localDirection = BABYLON.Vector3.Zero();
  15135. this._transformedDirection = BABYLON.Vector3.Zero();
  15136. }
  15137. this.inertialPanningX *= this.inertia;
  15138. this.inertialPanningY *= this.inertia;
  15139. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  15140. this.inertialPanningX = 0;
  15141. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  15142. this.inertialPanningY = 0;
  15143. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  15144. this._localDirection.multiplyInPlace(this.panningAxis);
  15145. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  15146. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  15147. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  15148. if (!this.panningAxis.y) {
  15149. this._transformedDirection.y = 0;
  15150. }
  15151. if (!this.target.getAbsolutePosition) {
  15152. this.target.addInPlace(this._transformedDirection);
  15153. }
  15154. }
  15155. // Limits
  15156. this._checkLimits();
  15157. _super.prototype._checkInputs.call(this);
  15158. };
  15159. ArcRotateCamera.prototype._checkLimits = function () {
  15160. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  15161. if (this.allowUpsideDown && this.beta > Math.PI) {
  15162. this.beta = this.beta - (2 * Math.PI);
  15163. }
  15164. }
  15165. else {
  15166. if (this.beta < this.lowerBetaLimit) {
  15167. this.beta = this.lowerBetaLimit;
  15168. }
  15169. }
  15170. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  15171. if (this.allowUpsideDown && this.beta < -Math.PI) {
  15172. this.beta = this.beta + (2 * Math.PI);
  15173. }
  15174. }
  15175. else {
  15176. if (this.beta > this.upperBetaLimit) {
  15177. this.beta = this.upperBetaLimit;
  15178. }
  15179. }
  15180. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  15181. this.alpha = this.lowerAlphaLimit;
  15182. }
  15183. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  15184. this.alpha = this.upperAlphaLimit;
  15185. }
  15186. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  15187. this.radius = this.lowerRadiusLimit;
  15188. }
  15189. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  15190. this.radius = this.upperRadiusLimit;
  15191. }
  15192. };
  15193. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  15194. var radiusv3 = this.position.subtract(this._getTargetPosition());
  15195. this.radius = radiusv3.length();
  15196. // Alpha
  15197. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  15198. if (radiusv3.z < 0) {
  15199. this.alpha = 2 * Math.PI - this.alpha;
  15200. }
  15201. // Beta
  15202. this.beta = Math.acos(radiusv3.y / this.radius);
  15203. this._checkLimits();
  15204. };
  15205. ArcRotateCamera.prototype.setPosition = function (position) {
  15206. if (this.position.equals(position)) {
  15207. return;
  15208. }
  15209. this.position.copyFrom(position);
  15210. this.rebuildAnglesAndRadius();
  15211. };
  15212. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter) {
  15213. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  15214. if (this._getTargetPosition().equals(target)) {
  15215. return;
  15216. }
  15217. if (toBoundingCenter && target.getBoundingInfo) {
  15218. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.center.clone();
  15219. }
  15220. else {
  15221. this._targetBoundingCenter = null;
  15222. }
  15223. this.target = target;
  15224. this.rebuildAnglesAndRadius();
  15225. };
  15226. ArcRotateCamera.prototype._getViewMatrix = function () {
  15227. // Compute
  15228. var cosa = Math.cos(this.alpha);
  15229. var sina = Math.sin(this.alpha);
  15230. var cosb = Math.cos(this.beta);
  15231. var sinb = Math.sin(this.beta);
  15232. if (sinb === 0) {
  15233. sinb = 0.0001;
  15234. }
  15235. var target = this._getTargetPosition();
  15236. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  15237. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  15238. this._collider.radius = this.collisionRadius;
  15239. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  15240. this._collisionTriggered = true;
  15241. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15242. }
  15243. else {
  15244. this.position.copyFrom(this._newPosition);
  15245. var up = this.upVector;
  15246. if (this.allowUpsideDown && this.beta < 0) {
  15247. up = up.clone();
  15248. up = up.negate();
  15249. }
  15250. if (this.getScene().useRightHandedSystem) {
  15251. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  15252. }
  15253. else {
  15254. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  15255. }
  15256. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  15257. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  15258. }
  15259. return this._viewMatrix;
  15260. };
  15261. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  15262. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15263. meshes = meshes || this.getScene().meshes;
  15264. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  15265. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  15266. this.radius = distance * this.zoomOnFactor;
  15267. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  15268. };
  15269. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  15270. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15271. var meshesOrMinMaxVector;
  15272. var distance;
  15273. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  15274. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  15275. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  15276. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  15277. }
  15278. else {
  15279. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  15280. distance = meshesOrMinMaxVectorAndDistance.distance;
  15281. }
  15282. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  15283. if (!doNotUpdateMaxZ) {
  15284. this.maxZ = distance * 2;
  15285. }
  15286. };
  15287. /**
  15288. * @override
  15289. * Override Camera.createRigCamera
  15290. */
  15291. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  15292. var alphaShift;
  15293. switch (this.cameraRigMode) {
  15294. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15295. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15296. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15297. case BABYLON.Camera.RIG_MODE_VR:
  15298. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  15299. break;
  15300. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15301. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  15302. break;
  15303. }
  15304. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  15305. rigCam._cameraRigParams = {};
  15306. return rigCam;
  15307. };
  15308. /**
  15309. * @override
  15310. * Override Camera._updateRigCameras
  15311. */
  15312. ArcRotateCamera.prototype._updateRigCameras = function () {
  15313. var camLeft = this._rigCameras[0];
  15314. var camRight = this._rigCameras[1];
  15315. camLeft.beta = camRight.beta = this.beta;
  15316. camLeft.radius = camRight.radius = this.radius;
  15317. switch (this.cameraRigMode) {
  15318. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15319. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15320. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15321. case BABYLON.Camera.RIG_MODE_VR:
  15322. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15323. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15324. break;
  15325. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15326. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15327. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15328. break;
  15329. }
  15330. _super.prototype._updateRigCameras.call(this);
  15331. };
  15332. ArcRotateCamera.prototype.dispose = function () {
  15333. this.inputs.clear();
  15334. _super.prototype.dispose.call(this);
  15335. };
  15336. ArcRotateCamera.prototype.getTypeName = function () {
  15337. return "ArcRotateCamera";
  15338. };
  15339. __decorate([
  15340. BABYLON.serialize()
  15341. ], ArcRotateCamera.prototype, "alpha", void 0);
  15342. __decorate([
  15343. BABYLON.serialize()
  15344. ], ArcRotateCamera.prototype, "beta", void 0);
  15345. __decorate([
  15346. BABYLON.serialize()
  15347. ], ArcRotateCamera.prototype, "radius", void 0);
  15348. __decorate([
  15349. BABYLON.serializeAsVector3()
  15350. ], ArcRotateCamera.prototype, "target", void 0);
  15351. __decorate([
  15352. BABYLON.serialize()
  15353. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  15354. __decorate([
  15355. BABYLON.serialize()
  15356. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  15357. __decorate([
  15358. BABYLON.serialize()
  15359. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  15360. __decorate([
  15361. BABYLON.serialize()
  15362. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  15363. __decorate([
  15364. BABYLON.serialize()
  15365. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  15366. __decorate([
  15367. BABYLON.serialize()
  15368. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  15369. __decorate([
  15370. BABYLON.serialize()
  15371. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  15372. __decorate([
  15373. BABYLON.serialize()
  15374. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  15375. __decorate([
  15376. BABYLON.serialize()
  15377. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  15378. __decorate([
  15379. BABYLON.serialize()
  15380. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  15381. __decorate([
  15382. BABYLON.serialize()
  15383. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  15384. __decorate([
  15385. BABYLON.serialize()
  15386. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  15387. __decorate([
  15388. BABYLON.serialize()
  15389. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  15390. return ArcRotateCamera;
  15391. })(BABYLON.TargetCamera);
  15392. BABYLON.ArcRotateCamera = ArcRotateCamera;
  15393. })(BABYLON || (BABYLON = {}));
  15394. var BABYLON;
  15395. (function (BABYLON) {
  15396. var ArcRotateCameraInputsManager = (function (_super) {
  15397. __extends(ArcRotateCameraInputsManager, _super);
  15398. function ArcRotateCameraInputsManager(camera) {
  15399. _super.call(this, camera);
  15400. }
  15401. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  15402. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  15403. return this;
  15404. };
  15405. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  15406. this.add(new BABYLON.ArcRotateCameraPointersInput());
  15407. return this;
  15408. };
  15409. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  15410. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  15411. return this;
  15412. };
  15413. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  15414. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  15415. return this;
  15416. };
  15417. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  15418. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  15419. return this;
  15420. };
  15421. return ArcRotateCameraInputsManager;
  15422. })(BABYLON.CameraInputsManager);
  15423. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  15424. })(BABYLON || (BABYLON = {}));
  15425. var BABYLON;
  15426. (function (BABYLON) {
  15427. var RenderingManager = (function () {
  15428. function RenderingManager(scene) {
  15429. this._renderingGroups = new Array();
  15430. this._autoClearDepthStencil = {};
  15431. this._customOpaqueSortCompareFn = {};
  15432. this._customAlphaTestSortCompareFn = {};
  15433. this._customTransparentSortCompareFn = {};
  15434. this._scene = scene;
  15435. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15436. this._autoClearDepthStencil[i] = true;
  15437. }
  15438. }
  15439. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  15440. if (this._scene._activeParticleSystems.length === 0) {
  15441. return;
  15442. }
  15443. // Particles
  15444. var activeCamera = this._scene.activeCamera;
  15445. this._scene._particlesDuration.beginMonitoring();
  15446. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15447. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15448. if (particleSystem.renderingGroupId !== index) {
  15449. continue;
  15450. }
  15451. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15452. continue;
  15453. }
  15454. this._clearDepthStencilBuffer();
  15455. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15456. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15457. }
  15458. }
  15459. this._scene._particlesDuration.endMonitoring(false);
  15460. };
  15461. RenderingManager.prototype._renderSprites = function (index) {
  15462. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  15463. return;
  15464. }
  15465. // Sprites
  15466. var activeCamera = this._scene.activeCamera;
  15467. this._scene._spritesDuration.beginMonitoring();
  15468. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  15469. var spriteManager = this._scene.spriteManagers[id];
  15470. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15471. this._clearDepthStencilBuffer();
  15472. spriteManager.render();
  15473. }
  15474. }
  15475. this._scene._spritesDuration.endMonitoring(false);
  15476. };
  15477. RenderingManager.prototype._clearDepthStencilBuffer = function () {
  15478. if (this._depthStencilBufferAlreadyCleaned) {
  15479. return;
  15480. }
  15481. this._scene.getEngine().clear(0, false, true, true);
  15482. this._depthStencilBufferAlreadyCleaned = true;
  15483. };
  15484. RenderingManager.prototype._renderSpritesAndParticles = function () {
  15485. if (this._currentRenderSprites) {
  15486. this._renderSprites(this._currentIndex);
  15487. }
  15488. if (this._currentRenderParticles) {
  15489. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  15490. }
  15491. };
  15492. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15493. this._currentActiveMeshes = activeMeshes;
  15494. this._currentRenderParticles = renderParticles;
  15495. this._currentRenderSprites = renderSprites;
  15496. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15497. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15498. var renderingGroup = this._renderingGroups[index];
  15499. var needToStepBack = false;
  15500. this._currentIndex = index;
  15501. if (renderingGroup) {
  15502. if (this._autoClearDepthStencil[index]) {
  15503. this._clearDepthStencilBuffer();
  15504. }
  15505. if (!renderingGroup.onBeforeTransparentRendering) {
  15506. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  15507. }
  15508. if (!renderingGroup.render(customRenderFunction)) {
  15509. this._renderingGroups.splice(index, 1);
  15510. needToStepBack = true;
  15511. this._renderSpritesAndParticles();
  15512. }
  15513. }
  15514. else {
  15515. this._renderSpritesAndParticles();
  15516. }
  15517. if (needToStepBack) {
  15518. index--;
  15519. }
  15520. }
  15521. };
  15522. RenderingManager.prototype.reset = function () {
  15523. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15524. var renderingGroup = this._renderingGroups[index];
  15525. if (renderingGroup) {
  15526. renderingGroup.prepare();
  15527. }
  15528. }
  15529. };
  15530. RenderingManager.prototype.dispatch = function (subMesh) {
  15531. var mesh = subMesh.getMesh();
  15532. var renderingGroupId = mesh.renderingGroupId || 0;
  15533. if (!this._renderingGroups[renderingGroupId]) {
  15534. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15535. }
  15536. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15537. };
  15538. /**
  15539. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15540. * This allowed control for front to back rendering or reversly depending of the special needs.
  15541. *
  15542. * @param renderingGroupId The rendering group id corresponding to its index
  15543. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15544. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15545. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15546. */
  15547. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15548. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15549. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15550. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15551. if (this._renderingGroups[renderingGroupId]) {
  15552. var group = this._renderingGroups[renderingGroupId];
  15553. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15554. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15555. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15556. }
  15557. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15558. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15559. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15560. };
  15561. /**
  15562. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15563. *
  15564. * @param renderingGroupId The rendering group id corresponding to its index
  15565. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15566. */
  15567. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  15568. this._autoClearDepthStencil[renderingGroupId] = autoClearDepthStencil;
  15569. };
  15570. /**
  15571. * The max id used for rendering groups (not included)
  15572. */
  15573. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15574. /**
  15575. * The min id used for rendering groups (included)
  15576. */
  15577. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15578. return RenderingManager;
  15579. })();
  15580. BABYLON.RenderingManager = RenderingManager;
  15581. })(BABYLON || (BABYLON = {}));
  15582. var BABYLON;
  15583. (function (BABYLON) {
  15584. var RenderingGroup = (function () {
  15585. /**
  15586. * Creates a new rendering group.
  15587. * @param index The rendering group index
  15588. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15589. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15590. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15591. */
  15592. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15593. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15594. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15595. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15596. this.index = index;
  15597. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15598. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15599. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15600. this._scene = scene;
  15601. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15602. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15603. this.transparentSortCompareFn = transparentSortCompareFn;
  15604. }
  15605. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15606. /**
  15607. * Set the opaque sort comparison function.
  15608. * If null the sub meshes will be render in the order they were created
  15609. */
  15610. set: function (value) {
  15611. this._opaqueSortCompareFn = value;
  15612. if (value) {
  15613. this._renderOpaque = this.renderOpaqueSorted;
  15614. }
  15615. else {
  15616. this._renderOpaque = RenderingGroup.renderUnsorted;
  15617. }
  15618. },
  15619. enumerable: true,
  15620. configurable: true
  15621. });
  15622. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15623. /**
  15624. * Set the alpha test sort comparison function.
  15625. * If null the sub meshes will be render in the order they were created
  15626. */
  15627. set: function (value) {
  15628. this._alphaTestSortCompareFn = value;
  15629. if (value) {
  15630. this._renderAlphaTest = this.renderAlphaTestSorted;
  15631. }
  15632. else {
  15633. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15634. }
  15635. },
  15636. enumerable: true,
  15637. configurable: true
  15638. });
  15639. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15640. /**
  15641. * Set the transparent sort comparison function.
  15642. * If null the sub meshes will be render in the order they were created
  15643. */
  15644. set: function (value) {
  15645. if (value) {
  15646. this._transparentSortCompareFn = value;
  15647. }
  15648. else {
  15649. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15650. }
  15651. this._renderTransparent = this.renderTransparentSorted;
  15652. },
  15653. enumerable: true,
  15654. configurable: true
  15655. });
  15656. /**
  15657. * Render all the sub meshes contained in the group.
  15658. * @param customRenderFunction Used to override the default render behaviour of the group.
  15659. * @returns true if rendered some submeshes.
  15660. */
  15661. RenderingGroup.prototype.render = function (customRenderFunction) {
  15662. if (customRenderFunction) {
  15663. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15664. return true;
  15665. }
  15666. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  15667. if (this.onBeforeTransparentRendering) {
  15668. this.onBeforeTransparentRendering();
  15669. }
  15670. return false;
  15671. }
  15672. var engine = this._scene.getEngine();
  15673. // Opaque
  15674. this._renderOpaque(this._opaqueSubMeshes);
  15675. // Alpha test
  15676. engine.setAlphaTesting(true);
  15677. this._renderAlphaTest(this._alphaTestSubMeshes);
  15678. engine.setAlphaTesting(false);
  15679. if (this.onBeforeTransparentRendering) {
  15680. this.onBeforeTransparentRendering();
  15681. }
  15682. // Transparent
  15683. this._renderTransparent(this._transparentSubMeshes);
  15684. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15685. return true;
  15686. };
  15687. /**
  15688. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15689. * @param subMeshes The submeshes to render
  15690. */
  15691. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15692. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15693. };
  15694. /**
  15695. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15696. * @param subMeshes The submeshes to render
  15697. */
  15698. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15699. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15700. };
  15701. /**
  15702. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15703. * @param subMeshes The submeshes to render
  15704. */
  15705. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15706. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15707. };
  15708. /**
  15709. * Renders the submeshes in a specified order.
  15710. * @param subMeshes The submeshes to sort before render
  15711. * @param sortCompareFn The comparison function use to sort
  15712. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15713. * @param transparent Specifies to activate blending if true
  15714. */
  15715. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15716. var subIndex = 0;
  15717. var subMesh;
  15718. for (; subIndex < subMeshes.length; subIndex++) {
  15719. subMesh = subMeshes.data[subIndex];
  15720. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15721. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15722. }
  15723. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15724. sortedArray.sort(sortCompareFn);
  15725. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15726. subMesh = sortedArray[subIndex];
  15727. subMesh.render(transparent);
  15728. }
  15729. };
  15730. /**
  15731. * Renders the submeshes in the order they were dispatched (no sort applied).
  15732. * @param subMeshes The submeshes to render
  15733. */
  15734. RenderingGroup.renderUnsorted = function (subMeshes) {
  15735. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15736. var submesh = subMeshes.data[subIndex];
  15737. submesh.render(false);
  15738. }
  15739. };
  15740. /**
  15741. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15742. * are rendered back to front if in the same alpha index.
  15743. *
  15744. * @param a The first submesh
  15745. * @param b The second submesh
  15746. * @returns The result of the comparison
  15747. */
  15748. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15749. // Alpha index first
  15750. if (a._alphaIndex > b._alphaIndex) {
  15751. return 1;
  15752. }
  15753. if (a._alphaIndex < b._alphaIndex) {
  15754. return -1;
  15755. }
  15756. // Then distance to camera
  15757. return RenderingGroup.backToFrontSortCompare(a, b);
  15758. };
  15759. /**
  15760. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15761. * are rendered back to front.
  15762. *
  15763. * @param a The first submesh
  15764. * @param b The second submesh
  15765. * @returns The result of the comparison
  15766. */
  15767. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15768. // Then distance to camera
  15769. if (a._distanceToCamera < b._distanceToCamera) {
  15770. return 1;
  15771. }
  15772. if (a._distanceToCamera > b._distanceToCamera) {
  15773. return -1;
  15774. }
  15775. return 0;
  15776. };
  15777. /**
  15778. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15779. * are rendered front to back (prevent overdraw).
  15780. *
  15781. * @param a The first submesh
  15782. * @param b The second submesh
  15783. * @returns The result of the comparison
  15784. */
  15785. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15786. // Then distance to camera
  15787. if (a._distanceToCamera < b._distanceToCamera) {
  15788. return -1;
  15789. }
  15790. if (a._distanceToCamera > b._distanceToCamera) {
  15791. return 1;
  15792. }
  15793. return 0;
  15794. };
  15795. /**
  15796. * Resets the different lists of submeshes to prepare a new frame.
  15797. */
  15798. RenderingGroup.prototype.prepare = function () {
  15799. this._opaqueSubMeshes.reset();
  15800. this._transparentSubMeshes.reset();
  15801. this._alphaTestSubMeshes.reset();
  15802. };
  15803. /**
  15804. * Inserts the submesh in its correct queue depending on its material.
  15805. * @param subMesh The submesh to dispatch
  15806. */
  15807. RenderingGroup.prototype.dispatch = function (subMesh) {
  15808. var material = subMesh.getMaterial();
  15809. var mesh = subMesh.getMesh();
  15810. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15811. this._transparentSubMeshes.push(subMesh);
  15812. }
  15813. else if (material.needAlphaTesting()) {
  15814. this._alphaTestSubMeshes.push(subMesh);
  15815. }
  15816. else {
  15817. this._opaqueSubMeshes.push(subMesh); // Opaque
  15818. }
  15819. };
  15820. return RenderingGroup;
  15821. })();
  15822. BABYLON.RenderingGroup = RenderingGroup;
  15823. })(BABYLON || (BABYLON = {}));
  15824. var BABYLON;
  15825. (function (BABYLON) {
  15826. var PointerEventTypes = (function () {
  15827. function PointerEventTypes() {
  15828. }
  15829. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15830. get: function () {
  15831. return PointerEventTypes._POINTERDOWN;
  15832. },
  15833. enumerable: true,
  15834. configurable: true
  15835. });
  15836. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15837. get: function () {
  15838. return PointerEventTypes._POINTERUP;
  15839. },
  15840. enumerable: true,
  15841. configurable: true
  15842. });
  15843. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15844. get: function () {
  15845. return PointerEventTypes._POINTERMOVE;
  15846. },
  15847. enumerable: true,
  15848. configurable: true
  15849. });
  15850. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15851. get: function () {
  15852. return PointerEventTypes._POINTERWHEEL;
  15853. },
  15854. enumerable: true,
  15855. configurable: true
  15856. });
  15857. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15858. get: function () {
  15859. return PointerEventTypes._POINTERPICK;
  15860. },
  15861. enumerable: true,
  15862. configurable: true
  15863. });
  15864. PointerEventTypes._POINTERDOWN = 0x01;
  15865. PointerEventTypes._POINTERUP = 0x02;
  15866. PointerEventTypes._POINTERMOVE = 0x04;
  15867. PointerEventTypes._POINTERWHEEL = 0x08;
  15868. PointerEventTypes._POINTERPICK = 0x10;
  15869. return PointerEventTypes;
  15870. })();
  15871. BABYLON.PointerEventTypes = PointerEventTypes;
  15872. var PointerInfoBase = (function () {
  15873. function PointerInfoBase(type, event) {
  15874. this.type = type;
  15875. this.event = event;
  15876. }
  15877. return PointerInfoBase;
  15878. })();
  15879. BABYLON.PointerInfoBase = PointerInfoBase;
  15880. /**
  15881. * This class is used to store pointer related info for the onPrePointerObservable event.
  15882. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15883. */
  15884. var PointerInfoPre = (function (_super) {
  15885. __extends(PointerInfoPre, _super);
  15886. function PointerInfoPre(type, event, localX, localY) {
  15887. _super.call(this, type, event);
  15888. this.skipOnPointerObservable = false;
  15889. this.localPosition = new BABYLON.Vector2(localX, localY);
  15890. }
  15891. return PointerInfoPre;
  15892. })(PointerInfoBase);
  15893. BABYLON.PointerInfoPre = PointerInfoPre;
  15894. /**
  15895. * This type contains all the data related to a pointer event in Babylon.js.
  15896. * 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.
  15897. */
  15898. var PointerInfo = (function (_super) {
  15899. __extends(PointerInfo, _super);
  15900. function PointerInfo(type, event, pickInfo) {
  15901. _super.call(this, type, event);
  15902. this.pickInfo = pickInfo;
  15903. }
  15904. return PointerInfo;
  15905. })(PointerInfoBase);
  15906. BABYLON.PointerInfo = PointerInfo;
  15907. /**
  15908. * Represents a scene to be rendered by the engine.
  15909. * @see http://doc.babylonjs.com/page.php?p=21911
  15910. */
  15911. var Scene = (function () {
  15912. /**
  15913. * @constructor
  15914. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15915. */
  15916. function Scene(engine) {
  15917. // Members
  15918. this.autoClear = true;
  15919. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15920. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15921. this.forceWireframe = false;
  15922. this.forcePointsCloud = false;
  15923. this.forceShowBoundingBoxes = false;
  15924. this.animationsEnabled = true;
  15925. this.constantlyUpdateMeshUnderPointer = false;
  15926. this.useRightHandedSystem = false;
  15927. this.hoverCursor = "pointer";
  15928. // Events
  15929. /**
  15930. * An event triggered when the scene is disposed.
  15931. * @type {BABYLON.Observable}
  15932. */
  15933. this.onDisposeObservable = new BABYLON.Observable();
  15934. /**
  15935. * An event triggered before rendering the scene
  15936. * @type {BABYLON.Observable}
  15937. */
  15938. this.onBeforeRenderObservable = new BABYLON.Observable();
  15939. /**
  15940. * An event triggered after rendering the scene
  15941. * @type {BABYLON.Observable}
  15942. */
  15943. this.onAfterRenderObservable = new BABYLON.Observable();
  15944. /**
  15945. * An event triggered when the scene is ready
  15946. * @type {BABYLON.Observable}
  15947. */
  15948. this.onReadyObservable = new BABYLON.Observable();
  15949. /**
  15950. * An event triggered before rendering a camera
  15951. * @type {BABYLON.Observable}
  15952. */
  15953. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15954. /**
  15955. * An event triggered after rendering a camera
  15956. * @type {BABYLON.Observable}
  15957. */
  15958. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15959. /**
  15960. * An event triggered when a camera is created
  15961. * @type {BABYLON.Observable}
  15962. */
  15963. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15964. /**
  15965. * An event triggered when a camera is removed
  15966. * @type {BABYLON.Observable}
  15967. */
  15968. this.onCameraRemovedObservable = new BABYLON.Observable();
  15969. /**
  15970. * An event triggered when a light is created
  15971. * @type {BABYLON.Observable}
  15972. */
  15973. this.onNewLightAddedObservable = new BABYLON.Observable();
  15974. /**
  15975. * An event triggered when a light is removed
  15976. * @type {BABYLON.Observable}
  15977. */
  15978. this.onLightRemovedObservable = new BABYLON.Observable();
  15979. /**
  15980. * An event triggered when a geometry is created
  15981. * @type {BABYLON.Observable}
  15982. */
  15983. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15984. /**
  15985. * An event triggered when a geometry is removed
  15986. * @type {BABYLON.Observable}
  15987. */
  15988. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15989. /**
  15990. * An event triggered when a mesh is created
  15991. * @type {BABYLON.Observable}
  15992. */
  15993. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15994. /**
  15995. * An event triggered when a mesh is removed
  15996. * @type {BABYLON.Observable}
  15997. */
  15998. this.onMeshRemovedObservable = new BABYLON.Observable();
  15999. // Animations
  16000. this.animations = [];
  16001. /**
  16002. * 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).
  16003. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  16004. */
  16005. this.onPrePointerObservable = new BABYLON.Observable();
  16006. /**
  16007. * Observable event triggered each time an input event is received from the rendering canvas
  16008. */
  16009. this.onPointerObservable = new BABYLON.Observable();
  16010. 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
  16011. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16012. this._startingPointerTime = 0;
  16013. // Fog
  16014. /**
  16015. * is fog enabled on this scene.
  16016. * @type {boolean}
  16017. */
  16018. this.fogEnabled = true;
  16019. this.fogMode = Scene.FOGMODE_NONE;
  16020. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16021. this.fogDensity = 0.1;
  16022. this.fogStart = 0;
  16023. this.fogEnd = 1000.0;
  16024. // Lights
  16025. /**
  16026. * is shadow enabled on this scene.
  16027. * @type {boolean}
  16028. */
  16029. this.shadowsEnabled = true;
  16030. /**
  16031. * is light enabled on this scene.
  16032. * @type {boolean}
  16033. */
  16034. this.lightsEnabled = true;
  16035. /**
  16036. * All of the lights added to this scene.
  16037. * @see BABYLON.Light
  16038. * @type {BABYLON.Light[]}
  16039. */
  16040. this.lights = new Array();
  16041. // Cameras
  16042. /**
  16043. * All of the cameras added to this scene.
  16044. * @see BABYLON.Camera
  16045. * @type {BABYLON.Camera[]}
  16046. */
  16047. this.cameras = new Array();
  16048. this.activeCameras = new Array();
  16049. // Meshes
  16050. /**
  16051. * All of the (abstract) meshes added to this scene.
  16052. * @see BABYLON.AbstractMesh
  16053. * @type {BABYLON.AbstractMesh[]}
  16054. */
  16055. this.meshes = new Array();
  16056. // Geometries
  16057. this._geometries = new Array();
  16058. this.materials = new Array();
  16059. this.multiMaterials = new Array();
  16060. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16061. // Textures
  16062. this.texturesEnabled = true;
  16063. this.textures = new Array();
  16064. // Particles
  16065. this.particlesEnabled = true;
  16066. this.particleSystems = new Array();
  16067. // Sprites
  16068. this.spritesEnabled = true;
  16069. this.spriteManagers = new Array();
  16070. // Layers
  16071. this.layers = new Array();
  16072. // Skeletons
  16073. this.skeletonsEnabled = true;
  16074. this.skeletons = new Array();
  16075. // Lens flares
  16076. this.lensFlaresEnabled = true;
  16077. this.lensFlareSystems = new Array();
  16078. // Collisions
  16079. this.collisionsEnabled = true;
  16080. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16081. // Postprocesses
  16082. this.postProcessesEnabled = true;
  16083. // Customs render targets
  16084. this.renderTargetsEnabled = true;
  16085. this.dumpNextRenderTargets = false;
  16086. this.customRenderTargets = new Array();
  16087. // Imported meshes
  16088. this.importedMeshesFiles = new Array();
  16089. // Probes
  16090. this.probesEnabled = true;
  16091. this.reflectionProbes = new Array();
  16092. this._actionManagers = new Array();
  16093. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16094. // Procedural textures
  16095. this.proceduralTexturesEnabled = true;
  16096. this._proceduralTextures = new Array();
  16097. this.soundTracks = new Array();
  16098. this._audioEnabled = true;
  16099. this._headphone = false;
  16100. // Performance counters
  16101. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16102. this._totalLightsCounter = new BABYLON.PerfCounter();
  16103. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16104. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16105. this._totalVertices = new BABYLON.PerfCounter();
  16106. this._activeIndices = new BABYLON.PerfCounter();
  16107. this._activeParticles = new BABYLON.PerfCounter();
  16108. this._lastFrameDuration = new BABYLON.PerfCounter();
  16109. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16110. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16111. this._particlesDuration = new BABYLON.PerfCounter();
  16112. this._renderDuration = new BABYLON.PerfCounter();
  16113. this._spritesDuration = new BABYLON.PerfCounter();
  16114. this._activeBones = new BABYLON.PerfCounter();
  16115. this._renderId = 0;
  16116. this._executeWhenReadyTimeoutId = -1;
  16117. this._intermediateRendering = false;
  16118. this._toBeDisposed = new BABYLON.SmartArray(256);
  16119. this._pendingData = []; //ANY
  16120. this._activeMeshes = new BABYLON.SmartArray(256);
  16121. this._processedMaterials = new BABYLON.SmartArray(256);
  16122. this._renderTargets = new BABYLON.SmartArray(256);
  16123. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16124. this._activeSkeletons = new BABYLON.SmartArray(32);
  16125. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16126. this._activeAnimatables = new Array();
  16127. this._transformMatrix = BABYLON.Matrix.Zero();
  16128. this._edgesRenderers = new BABYLON.SmartArray(16);
  16129. this._uniqueIdCounter = 0;
  16130. this._engine = engine;
  16131. engine.scenes.push(this);
  16132. this._renderingManager = new BABYLON.RenderingManager(this);
  16133. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16134. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16135. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16136. if (BABYLON.OutlineRenderer) {
  16137. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16138. }
  16139. this.attachControl();
  16140. if (BABYLON.SoundTrack) {
  16141. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16142. }
  16143. //simplification queue
  16144. if (BABYLON.SimplificationQueue) {
  16145. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16146. }
  16147. //collision coordinator initialization. For now legacy per default.
  16148. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16149. }
  16150. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16151. get: function () {
  16152. return Scene._FOGMODE_NONE;
  16153. },
  16154. enumerable: true,
  16155. configurable: true
  16156. });
  16157. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16158. get: function () {
  16159. return Scene._FOGMODE_EXP;
  16160. },
  16161. enumerable: true,
  16162. configurable: true
  16163. });
  16164. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16165. get: function () {
  16166. return Scene._FOGMODE_EXP2;
  16167. },
  16168. enumerable: true,
  16169. configurable: true
  16170. });
  16171. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16172. get: function () {
  16173. return Scene._FOGMODE_LINEAR;
  16174. },
  16175. enumerable: true,
  16176. configurable: true
  16177. });
  16178. Object.defineProperty(Scene.prototype, "onDispose", {
  16179. set: function (callback) {
  16180. if (this._onDisposeObserver) {
  16181. this.onDisposeObservable.remove(this._onDisposeObserver);
  16182. }
  16183. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16184. },
  16185. enumerable: true,
  16186. configurable: true
  16187. });
  16188. Object.defineProperty(Scene.prototype, "beforeRender", {
  16189. set: function (callback) {
  16190. if (this._onBeforeRenderObserver) {
  16191. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16192. }
  16193. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16194. },
  16195. enumerable: true,
  16196. configurable: true
  16197. });
  16198. Object.defineProperty(Scene.prototype, "afterRender", {
  16199. set: function (callback) {
  16200. if (this._onAfterRenderObserver) {
  16201. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16202. }
  16203. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16204. },
  16205. enumerable: true,
  16206. configurable: true
  16207. });
  16208. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16209. set: function (callback) {
  16210. if (this._onBeforeCameraRenderObserver) {
  16211. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16212. }
  16213. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16214. },
  16215. enumerable: true,
  16216. configurable: true
  16217. });
  16218. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16219. set: function (callback) {
  16220. if (this._onAfterCameraRenderObserver) {
  16221. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16222. }
  16223. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16224. },
  16225. enumerable: true,
  16226. configurable: true
  16227. });
  16228. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16229. get: function () {
  16230. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16231. },
  16232. enumerable: true,
  16233. configurable: true
  16234. });
  16235. Object.defineProperty(Scene.prototype, "debugLayer", {
  16236. // Properties
  16237. get: function () {
  16238. if (!this._debugLayer) {
  16239. this._debugLayer = new BABYLON.DebugLayer(this);
  16240. }
  16241. return this._debugLayer;
  16242. },
  16243. enumerable: true,
  16244. configurable: true
  16245. });
  16246. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16247. get: function () {
  16248. return this._workerCollisions;
  16249. },
  16250. set: function (enabled) {
  16251. enabled = (enabled && !!Worker);
  16252. this._workerCollisions = enabled;
  16253. if (this.collisionCoordinator) {
  16254. this.collisionCoordinator.destroy();
  16255. }
  16256. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16257. this.collisionCoordinator.init(this);
  16258. },
  16259. enumerable: true,
  16260. configurable: true
  16261. });
  16262. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  16263. get: function () {
  16264. return this._selectionOctree;
  16265. },
  16266. enumerable: true,
  16267. configurable: true
  16268. });
  16269. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16270. /**
  16271. * The mesh that is currently under the pointer.
  16272. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16273. */
  16274. get: function () {
  16275. return this._pointerOverMesh;
  16276. },
  16277. enumerable: true,
  16278. configurable: true
  16279. });
  16280. Object.defineProperty(Scene.prototype, "pointerX", {
  16281. /**
  16282. * Current on-screen X position of the pointer
  16283. * @return {number} X position of the pointer
  16284. */
  16285. get: function () {
  16286. return this._pointerX;
  16287. },
  16288. enumerable: true,
  16289. configurable: true
  16290. });
  16291. Object.defineProperty(Scene.prototype, "pointerY", {
  16292. /**
  16293. * Current on-screen Y position of the pointer
  16294. * @return {number} Y position of the pointer
  16295. */
  16296. get: function () {
  16297. return this._pointerY;
  16298. },
  16299. enumerable: true,
  16300. configurable: true
  16301. });
  16302. Scene.prototype.getCachedMaterial = function () {
  16303. return this._cachedMaterial;
  16304. };
  16305. Scene.prototype.getBoundingBoxRenderer = function () {
  16306. return this._boundingBoxRenderer;
  16307. };
  16308. Scene.prototype.getOutlineRenderer = function () {
  16309. return this._outlineRenderer;
  16310. };
  16311. Scene.prototype.getEngine = function () {
  16312. return this._engine;
  16313. };
  16314. Scene.prototype.getTotalVertices = function () {
  16315. return this._totalVertices.current;
  16316. };
  16317. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16318. get: function () {
  16319. return this._totalVertices;
  16320. },
  16321. enumerable: true,
  16322. configurable: true
  16323. });
  16324. Scene.prototype.getActiveIndices = function () {
  16325. return this._activeIndices.current;
  16326. };
  16327. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16328. get: function () {
  16329. return this._activeIndices;
  16330. },
  16331. enumerable: true,
  16332. configurable: true
  16333. });
  16334. Scene.prototype.getActiveParticles = function () {
  16335. return this._activeParticles.current;
  16336. };
  16337. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16338. get: function () {
  16339. return this._activeParticles;
  16340. },
  16341. enumerable: true,
  16342. configurable: true
  16343. });
  16344. Scene.prototype.getActiveBones = function () {
  16345. return this._activeBones.current;
  16346. };
  16347. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16348. get: function () {
  16349. return this._activeBones;
  16350. },
  16351. enumerable: true,
  16352. configurable: true
  16353. });
  16354. // Stats
  16355. Scene.prototype.getLastFrameDuration = function () {
  16356. return this._lastFrameDuration.current;
  16357. };
  16358. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16359. get: function () {
  16360. return this._lastFrameDuration;
  16361. },
  16362. enumerable: true,
  16363. configurable: true
  16364. });
  16365. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16366. return this._evaluateActiveMeshesDuration.current;
  16367. };
  16368. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16369. get: function () {
  16370. return this._evaluateActiveMeshesDuration;
  16371. },
  16372. enumerable: true,
  16373. configurable: true
  16374. });
  16375. Scene.prototype.getActiveMeshes = function () {
  16376. return this._activeMeshes;
  16377. };
  16378. Scene.prototype.getRenderTargetsDuration = function () {
  16379. return this._renderTargetsDuration.current;
  16380. };
  16381. Scene.prototype.getRenderDuration = function () {
  16382. return this._renderDuration.current;
  16383. };
  16384. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16385. get: function () {
  16386. return this._renderDuration;
  16387. },
  16388. enumerable: true,
  16389. configurable: true
  16390. });
  16391. Scene.prototype.getParticlesDuration = function () {
  16392. return this._particlesDuration.current;
  16393. };
  16394. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16395. get: function () {
  16396. return this._particlesDuration;
  16397. },
  16398. enumerable: true,
  16399. configurable: true
  16400. });
  16401. Scene.prototype.getSpritesDuration = function () {
  16402. return this._spritesDuration.current;
  16403. };
  16404. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16405. get: function () {
  16406. return this._spritesDuration;
  16407. },
  16408. enumerable: true,
  16409. configurable: true
  16410. });
  16411. Scene.prototype.getAnimationRatio = function () {
  16412. return this._animationRatio;
  16413. };
  16414. Scene.prototype.getRenderId = function () {
  16415. return this._renderId;
  16416. };
  16417. Scene.prototype.incrementRenderId = function () {
  16418. this._renderId++;
  16419. };
  16420. Scene.prototype._updatePointerPosition = function (evt) {
  16421. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16422. this._pointerX = evt.clientX - canvasRect.left;
  16423. this._pointerY = evt.clientY - canvasRect.top;
  16424. this._unTranslatedPointerX = this._pointerX;
  16425. this._unTranslatedPointerY = this._pointerY;
  16426. if (this.cameraToUseForPointers) {
  16427. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16428. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16429. }
  16430. };
  16431. // Pointers handling
  16432. /**
  16433. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16434. * @param attachUp defines if you want to attach events to pointerup
  16435. * @param attachDown defines if you want to attach events to pointerdown
  16436. * @param attachMove defines if you want to attach events to pointermove
  16437. */
  16438. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16439. var _this = this;
  16440. if (attachUp === void 0) { attachUp = true; }
  16441. if (attachDown === void 0) { attachDown = true; }
  16442. if (attachMove === void 0) { attachMove = true; }
  16443. var spritePredicate = function (sprite) {
  16444. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16445. };
  16446. this._onPointerMove = function (evt) {
  16447. _this._updatePointerPosition(evt);
  16448. // PreObservable support
  16449. if (_this.onPrePointerObservable.hasObservers()) {
  16450. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16451. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16452. _this.onPrePointerObservable.notifyObservers(pi, type);
  16453. if (pi.skipOnPointerObservable) {
  16454. return;
  16455. }
  16456. }
  16457. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16458. return;
  16459. }
  16460. var canvas = _this._engine.getRenderingCanvas();
  16461. if (!_this.pointerMovePredicate) {
  16462. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  16463. }
  16464. // Meshes
  16465. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16466. if (pickResult.hit && pickResult.pickedMesh) {
  16467. _this.setPointerOverSprite(null);
  16468. _this.setPointerOverMesh(pickResult.pickedMesh);
  16469. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16470. canvas.style.cursor = _this.hoverCursor;
  16471. }
  16472. else {
  16473. canvas.style.cursor = "";
  16474. }
  16475. }
  16476. else {
  16477. _this.setPointerOverMesh(null);
  16478. // Sprites
  16479. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16480. if (pickResult.hit && pickResult.pickedSprite) {
  16481. canvas.style.cursor = _this.hoverCursor;
  16482. _this.setPointerOverSprite(pickResult.pickedSprite);
  16483. }
  16484. else {
  16485. _this.setPointerOverSprite(null);
  16486. // Restore pointer
  16487. canvas.style.cursor = "";
  16488. }
  16489. }
  16490. if (_this.onPointerMove) {
  16491. _this.onPointerMove(evt, pickResult);
  16492. }
  16493. if (_this.onPointerObservable.hasObservers()) {
  16494. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16495. var pi = new PointerInfo(type, evt, pickResult);
  16496. _this.onPointerObservable.notifyObservers(pi, type);
  16497. }
  16498. };
  16499. this._onPointerDown = function (evt) {
  16500. _this._updatePointerPosition(evt);
  16501. // PreObservable support
  16502. if (_this.onPrePointerObservable.hasObservers()) {
  16503. var type = PointerEventTypes.POINTERDOWN;
  16504. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16505. _this.onPrePointerObservable.notifyObservers(pi, type);
  16506. if (pi.skipOnPointerObservable) {
  16507. return;
  16508. }
  16509. }
  16510. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16511. return;
  16512. }
  16513. _this._startingPointerPosition.x = _this._pointerX;
  16514. _this._startingPointerPosition.y = _this._pointerY;
  16515. _this._startingPointerTime = new Date().getTime();
  16516. if (!_this.pointerDownPredicate) {
  16517. _this.pointerDownPredicate = function (mesh) {
  16518. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  16519. };
  16520. }
  16521. // Meshes
  16522. _this._pickedDownMesh = null;
  16523. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16524. if (pickResult.hit && pickResult.pickedMesh) {
  16525. if (pickResult.pickedMesh.actionManager) {
  16526. _this._pickedDownMesh = pickResult.pickedMesh;
  16527. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  16528. switch (evt.button) {
  16529. case 0:
  16530. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16531. break;
  16532. case 1:
  16533. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16534. break;
  16535. case 2:
  16536. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16537. break;
  16538. }
  16539. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16540. }
  16541. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16542. var that = _this;
  16543. window.setTimeout(function () {
  16544. 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);
  16545. if (pickResult.hit && pickResult.pickedMesh) {
  16546. if (pickResult.pickedMesh.actionManager) {
  16547. 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)) {
  16548. that._startingPointerTime = 0;
  16549. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16550. }
  16551. }
  16552. }
  16553. }, BABYLON.ActionManager.LongPressDelay);
  16554. }
  16555. }
  16556. }
  16557. if (_this.onPointerDown) {
  16558. _this.onPointerDown(evt, pickResult);
  16559. }
  16560. if (_this.onPointerObservable.hasObservers()) {
  16561. var type = PointerEventTypes.POINTERDOWN;
  16562. var pi = new PointerInfo(type, evt, pickResult);
  16563. _this.onPointerObservable.notifyObservers(pi, type);
  16564. }
  16565. // Sprites
  16566. _this._pickedDownSprite = null;
  16567. if (_this.spriteManagers.length > 0) {
  16568. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16569. if (pickResult.hit && pickResult.pickedSprite) {
  16570. if (pickResult.pickedSprite.actionManager) {
  16571. _this._pickedDownSprite = pickResult.pickedSprite;
  16572. switch (evt.button) {
  16573. case 0:
  16574. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16575. break;
  16576. case 1:
  16577. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16578. break;
  16579. case 2:
  16580. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16581. break;
  16582. }
  16583. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16584. }
  16585. }
  16586. }
  16587. };
  16588. this._onPointerUp = function (evt) {
  16589. _this._updatePointerPosition(evt);
  16590. // PreObservable support
  16591. if (_this.onPrePointerObservable.hasObservers()) {
  16592. var type = PointerEventTypes.POINTERUP;
  16593. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16594. _this.onPrePointerObservable.notifyObservers(pi, type);
  16595. if (pi.skipOnPointerObservable) {
  16596. return;
  16597. }
  16598. }
  16599. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16600. return;
  16601. }
  16602. if (!_this.pointerUpPredicate) {
  16603. _this.pointerUpPredicate = function (mesh) {
  16604. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  16605. };
  16606. }
  16607. // Meshes
  16608. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  16609. if (pickResult.hit && pickResult.pickedMesh) {
  16610. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  16611. if (_this.onPointerPick) {
  16612. _this.onPointerPick(evt, pickResult);
  16613. }
  16614. if (_this.onPointerObservable.hasObservers()) {
  16615. var type = PointerEventTypes.POINTERPICK;
  16616. var pi = new PointerInfo(type, evt, pickResult);
  16617. _this.onPointerObservable.notifyObservers(pi, type);
  16618. }
  16619. }
  16620. if (pickResult.pickedMesh.actionManager) {
  16621. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16622. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  16623. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16624. }
  16625. }
  16626. }
  16627. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  16628. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  16629. }
  16630. if (_this.onPointerUp) {
  16631. _this.onPointerUp(evt, pickResult);
  16632. }
  16633. if (_this.onPointerObservable.hasObservers()) {
  16634. var type = PointerEventTypes.POINTERUP;
  16635. var pi = new PointerInfo(type, evt, pickResult);
  16636. _this.onPointerObservable.notifyObservers(pi, type);
  16637. }
  16638. _this._startingPointerTime = 0;
  16639. // Sprites
  16640. if (_this.spriteManagers.length > 0) {
  16641. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16642. if (pickResult.hit && pickResult.pickedSprite) {
  16643. if (pickResult.pickedSprite.actionManager) {
  16644. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16645. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  16646. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16647. }
  16648. }
  16649. }
  16650. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  16651. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  16652. }
  16653. }
  16654. };
  16655. this._onKeyDown = function (evt) {
  16656. if (_this.actionManager) {
  16657. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16658. }
  16659. };
  16660. this._onKeyUp = function (evt) {
  16661. if (_this.actionManager) {
  16662. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16663. }
  16664. };
  16665. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16666. var canvas = this._engine.getRenderingCanvas();
  16667. if (attachMove) {
  16668. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16669. // Wheel
  16670. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16671. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16672. }
  16673. if (attachDown) {
  16674. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16675. }
  16676. if (attachUp) {
  16677. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16678. }
  16679. canvas.tabIndex = 1;
  16680. canvas.addEventListener("keydown", this._onKeyDown, false);
  16681. canvas.addEventListener("keyup", this._onKeyUp, false);
  16682. };
  16683. Scene.prototype.detachControl = function () {
  16684. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16685. var canvas = this._engine.getRenderingCanvas();
  16686. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16687. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16688. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16689. // Wheel
  16690. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16691. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16692. canvas.removeEventListener("keydown", this._onKeyDown);
  16693. canvas.removeEventListener("keyup", this._onKeyUp);
  16694. };
  16695. // Ready
  16696. Scene.prototype.isReady = function () {
  16697. if (this._pendingData.length > 0) {
  16698. return false;
  16699. }
  16700. var index;
  16701. for (index = 0; index < this._geometries.length; index++) {
  16702. var geometry = this._geometries[index];
  16703. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16704. return false;
  16705. }
  16706. }
  16707. for (index = 0; index < this.meshes.length; index++) {
  16708. var mesh = this.meshes[index];
  16709. if (!mesh.isReady()) {
  16710. return false;
  16711. }
  16712. var mat = mesh.material;
  16713. if (mat) {
  16714. if (!mat.isReady(mesh)) {
  16715. return false;
  16716. }
  16717. }
  16718. }
  16719. return true;
  16720. };
  16721. Scene.prototype.resetCachedMaterial = function () {
  16722. this._cachedMaterial = null;
  16723. };
  16724. Scene.prototype.registerBeforeRender = function (func) {
  16725. this.onBeforeRenderObservable.add(func);
  16726. };
  16727. Scene.prototype.unregisterBeforeRender = function (func) {
  16728. this.onBeforeRenderObservable.removeCallback(func);
  16729. };
  16730. Scene.prototype.registerAfterRender = function (func) {
  16731. this.onAfterRenderObservable.add(func);
  16732. };
  16733. Scene.prototype.unregisterAfterRender = function (func) {
  16734. this.onAfterRenderObservable.removeCallback(func);
  16735. };
  16736. Scene.prototype._addPendingData = function (data) {
  16737. this._pendingData.push(data);
  16738. };
  16739. Scene.prototype._removePendingData = function (data) {
  16740. var index = this._pendingData.indexOf(data);
  16741. if (index !== -1) {
  16742. this._pendingData.splice(index, 1);
  16743. }
  16744. };
  16745. Scene.prototype.getWaitingItemsCount = function () {
  16746. return this._pendingData.length;
  16747. };
  16748. /**
  16749. * Registers a function to be executed when the scene is ready.
  16750. * @param {Function} func - the function to be executed.
  16751. */
  16752. Scene.prototype.executeWhenReady = function (func) {
  16753. var _this = this;
  16754. this.onReadyObservable.add(func);
  16755. if (this._executeWhenReadyTimeoutId !== -1) {
  16756. return;
  16757. }
  16758. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16759. _this._checkIsReady();
  16760. }, 150);
  16761. };
  16762. Scene.prototype._checkIsReady = function () {
  16763. var _this = this;
  16764. if (this.isReady()) {
  16765. this.onReadyObservable.notifyObservers(this);
  16766. this.onReadyObservable.clear();
  16767. this._executeWhenReadyTimeoutId = -1;
  16768. return;
  16769. }
  16770. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16771. _this._checkIsReady();
  16772. }, 150);
  16773. };
  16774. // Animations
  16775. /**
  16776. * Will start the animation sequence of a given target
  16777. * @param target - the target
  16778. * @param {number} from - from which frame should animation start
  16779. * @param {number} to - till which frame should animation run.
  16780. * @param {boolean} [loop] - should the animation loop
  16781. * @param {number} [speedRatio] - the speed in which to run the animation
  16782. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16783. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16784. * @return {BABYLON.Animatable} the animatable object created for this animation
  16785. * @see BABYLON.Animatable
  16786. * @see http://doc.babylonjs.com/page.php?p=22081
  16787. */
  16788. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16789. if (speedRatio === void 0) { speedRatio = 1.0; }
  16790. this.stopAnimation(target);
  16791. if (!animatable) {
  16792. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16793. }
  16794. // Local animations
  16795. if (target.animations) {
  16796. animatable.appendAnimations(target, target.animations);
  16797. }
  16798. // Children animations
  16799. if (target.getAnimatables) {
  16800. var animatables = target.getAnimatables();
  16801. for (var index = 0; index < animatables.length; index++) {
  16802. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16803. }
  16804. }
  16805. animatable.reset();
  16806. return animatable;
  16807. };
  16808. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16809. if (speedRatio === undefined) {
  16810. speedRatio = 1.0;
  16811. }
  16812. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16813. return animatable;
  16814. };
  16815. Scene.prototype.getAnimatableByTarget = function (target) {
  16816. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16817. if (this._activeAnimatables[index].target === target) {
  16818. return this._activeAnimatables[index];
  16819. }
  16820. }
  16821. return null;
  16822. };
  16823. Object.defineProperty(Scene.prototype, "Animatables", {
  16824. get: function () {
  16825. return this._activeAnimatables;
  16826. },
  16827. enumerable: true,
  16828. configurable: true
  16829. });
  16830. /**
  16831. * Will stop the animation of the given target
  16832. * @param target - the target
  16833. * @see beginAnimation
  16834. */
  16835. Scene.prototype.stopAnimation = function (target) {
  16836. var animatable = this.getAnimatableByTarget(target);
  16837. if (animatable) {
  16838. animatable.stop();
  16839. }
  16840. };
  16841. Scene.prototype._animate = function () {
  16842. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  16843. return;
  16844. }
  16845. if (!this._animationStartDate) {
  16846. if (this._pendingData.length > 0) {
  16847. return;
  16848. }
  16849. this._animationStartDate = BABYLON.Tools.Now;
  16850. }
  16851. // Getting time
  16852. var now = BABYLON.Tools.Now;
  16853. var delay = now - this._animationStartDate;
  16854. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16855. this._activeAnimatables[index]._animate(delay);
  16856. }
  16857. };
  16858. // Matrix
  16859. Scene.prototype.getViewMatrix = function () {
  16860. return this._viewMatrix;
  16861. };
  16862. Scene.prototype.getProjectionMatrix = function () {
  16863. return this._projectionMatrix;
  16864. };
  16865. Scene.prototype.getTransformMatrix = function () {
  16866. return this._transformMatrix;
  16867. };
  16868. Scene.prototype.setTransformMatrix = function (view, projection) {
  16869. this._viewMatrix = view;
  16870. this._projectionMatrix = projection;
  16871. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16872. // Update frustum
  16873. if (!this._frustumPlanes) {
  16874. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16875. }
  16876. else {
  16877. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16878. }
  16879. };
  16880. // Methods
  16881. Scene.prototype.addMesh = function (newMesh) {
  16882. newMesh.uniqueId = this._uniqueIdCounter++;
  16883. var position = this.meshes.push(newMesh);
  16884. //notify the collision coordinator
  16885. this.collisionCoordinator.onMeshAdded(newMesh);
  16886. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  16887. };
  16888. Scene.prototype.removeMesh = function (toRemove) {
  16889. var index = this.meshes.indexOf(toRemove);
  16890. if (index !== -1) {
  16891. // Remove from the scene if mesh found
  16892. this.meshes.splice(index, 1);
  16893. }
  16894. //notify the collision coordinator
  16895. this.collisionCoordinator.onMeshRemoved(toRemove);
  16896. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16897. return index;
  16898. };
  16899. Scene.prototype.removeSkeleton = function (toRemove) {
  16900. var index = this.skeletons.indexOf(toRemove);
  16901. if (index !== -1) {
  16902. // Remove from the scene if mesh found
  16903. this.skeletons.splice(index, 1);
  16904. }
  16905. return index;
  16906. };
  16907. Scene.prototype.removeLight = function (toRemove) {
  16908. var index = this.lights.indexOf(toRemove);
  16909. if (index !== -1) {
  16910. // Remove from the scene if mesh found
  16911. this.lights.splice(index, 1);
  16912. }
  16913. this.onLightRemovedObservable.notifyObservers(toRemove);
  16914. return index;
  16915. };
  16916. Scene.prototype.removeCamera = function (toRemove) {
  16917. var index = this.cameras.indexOf(toRemove);
  16918. if (index !== -1) {
  16919. // Remove from the scene if mesh found
  16920. this.cameras.splice(index, 1);
  16921. }
  16922. // Remove from activeCameras
  16923. var index2 = this.activeCameras.indexOf(toRemove);
  16924. if (index2 !== -1) {
  16925. // Remove from the scene if mesh found
  16926. this.activeCameras.splice(index2, 1);
  16927. }
  16928. // Reset the activeCamera
  16929. if (this.activeCamera === toRemove) {
  16930. if (this.cameras.length > 0) {
  16931. this.activeCamera = this.cameras[0];
  16932. }
  16933. else {
  16934. this.activeCamera = null;
  16935. }
  16936. }
  16937. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16938. return index;
  16939. };
  16940. Scene.prototype.addLight = function (newLight) {
  16941. newLight.uniqueId = this._uniqueIdCounter++;
  16942. var position = this.lights.push(newLight);
  16943. this.onNewLightAddedObservable.notifyObservers(newLight);
  16944. };
  16945. Scene.prototype.addCamera = function (newCamera) {
  16946. newCamera.uniqueId = this._uniqueIdCounter++;
  16947. var position = this.cameras.push(newCamera);
  16948. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16949. };
  16950. /**
  16951. * Switch active camera
  16952. * @param {Camera} newCamera - new active camera
  16953. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16954. */
  16955. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16956. if (attachControl === void 0) { attachControl = true; }
  16957. var canvas = this._engine.getRenderingCanvas();
  16958. this.activeCamera.detachControl(canvas);
  16959. this.activeCamera = newCamera;
  16960. if (attachControl) {
  16961. newCamera.attachControl(canvas);
  16962. }
  16963. };
  16964. /**
  16965. * sets the active camera of the scene using its ID
  16966. * @param {string} id - the camera's ID
  16967. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16968. * @see activeCamera
  16969. */
  16970. Scene.prototype.setActiveCameraByID = function (id) {
  16971. var camera = this.getCameraByID(id);
  16972. if (camera) {
  16973. this.activeCamera = camera;
  16974. return camera;
  16975. }
  16976. return null;
  16977. };
  16978. /**
  16979. * sets the active camera of the scene using its name
  16980. * @param {string} name - the camera's name
  16981. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16982. * @see activeCamera
  16983. */
  16984. Scene.prototype.setActiveCameraByName = function (name) {
  16985. var camera = this.getCameraByName(name);
  16986. if (camera) {
  16987. this.activeCamera = camera;
  16988. return camera;
  16989. }
  16990. return null;
  16991. };
  16992. /**
  16993. * get a material using its id
  16994. * @param {string} the material's ID
  16995. * @return {BABYLON.Material|null} the material or null if none found.
  16996. */
  16997. Scene.prototype.getMaterialByID = function (id) {
  16998. for (var index = 0; index < this.materials.length; index++) {
  16999. if (this.materials[index].id === id) {
  17000. return this.materials[index];
  17001. }
  17002. }
  17003. return null;
  17004. };
  17005. /**
  17006. * get a material using its name
  17007. * @param {string} the material's name
  17008. * @return {BABYLON.Material|null} the material or null if none found.
  17009. */
  17010. Scene.prototype.getMaterialByName = function (name) {
  17011. for (var index = 0; index < this.materials.length; index++) {
  17012. if (this.materials[index].name === name) {
  17013. return this.materials[index];
  17014. }
  17015. }
  17016. return null;
  17017. };
  17018. Scene.prototype.getLensFlareSystemByName = function (name) {
  17019. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17020. if (this.lensFlareSystems[index].name === name) {
  17021. return this.lensFlareSystems[index];
  17022. }
  17023. }
  17024. return null;
  17025. };
  17026. Scene.prototype.getLensFlareSystemByID = function (id) {
  17027. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17028. if (this.lensFlareSystems[index].id === id) {
  17029. return this.lensFlareSystems[index];
  17030. }
  17031. }
  17032. return null;
  17033. };
  17034. Scene.prototype.getCameraByID = function (id) {
  17035. for (var index = 0; index < this.cameras.length; index++) {
  17036. if (this.cameras[index].id === id) {
  17037. return this.cameras[index];
  17038. }
  17039. }
  17040. return null;
  17041. };
  17042. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17043. for (var index = 0; index < this.cameras.length; index++) {
  17044. if (this.cameras[index].uniqueId === uniqueId) {
  17045. return this.cameras[index];
  17046. }
  17047. }
  17048. return null;
  17049. };
  17050. /**
  17051. * get a camera using its name
  17052. * @param {string} the camera's name
  17053. * @return {BABYLON.Camera|null} the camera or null if none found.
  17054. */
  17055. Scene.prototype.getCameraByName = function (name) {
  17056. for (var index = 0; index < this.cameras.length; index++) {
  17057. if (this.cameras[index].name === name) {
  17058. return this.cameras[index];
  17059. }
  17060. }
  17061. return null;
  17062. };
  17063. /**
  17064. * get a bone using its id
  17065. * @param {string} the bone's id
  17066. * @return {BABYLON.Bone|null} the bone or null if not found
  17067. */
  17068. Scene.prototype.getBoneByID = function (id) {
  17069. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17070. var skeleton = this.skeletons[skeletonIndex];
  17071. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17072. if (skeleton.bones[boneIndex].id === id) {
  17073. return skeleton.bones[boneIndex];
  17074. }
  17075. }
  17076. }
  17077. return null;
  17078. };
  17079. /**
  17080. * get a bone using its id
  17081. * @param {string} the bone's name
  17082. * @return {BABYLON.Bone|null} the bone or null if not found
  17083. */
  17084. Scene.prototype.getBoneByName = function (name) {
  17085. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17086. var skeleton = this.skeletons[skeletonIndex];
  17087. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17088. if (skeleton.bones[boneIndex].name === name) {
  17089. return skeleton.bones[boneIndex];
  17090. }
  17091. }
  17092. }
  17093. return null;
  17094. };
  17095. /**
  17096. * get a light node using its name
  17097. * @param {string} the light's name
  17098. * @return {BABYLON.Light|null} the light or null if none found.
  17099. */
  17100. Scene.prototype.getLightByName = function (name) {
  17101. for (var index = 0; index < this.lights.length; index++) {
  17102. if (this.lights[index].name === name) {
  17103. return this.lights[index];
  17104. }
  17105. }
  17106. return null;
  17107. };
  17108. /**
  17109. * get a light node using its ID
  17110. * @param {string} the light's id
  17111. * @return {BABYLON.Light|null} the light or null if none found.
  17112. */
  17113. Scene.prototype.getLightByID = function (id) {
  17114. for (var index = 0; index < this.lights.length; index++) {
  17115. if (this.lights[index].id === id) {
  17116. return this.lights[index];
  17117. }
  17118. }
  17119. return null;
  17120. };
  17121. /**
  17122. * get a light node using its scene-generated unique ID
  17123. * @param {number} the light's unique id
  17124. * @return {BABYLON.Light|null} the light or null if none found.
  17125. */
  17126. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17127. for (var index = 0; index < this.lights.length; index++) {
  17128. if (this.lights[index].uniqueId === uniqueId) {
  17129. return this.lights[index];
  17130. }
  17131. }
  17132. return null;
  17133. };
  17134. /**
  17135. * get a particle system by id
  17136. * @param id {number} the particle system id
  17137. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  17138. */
  17139. Scene.prototype.getParticleSystemByID = function (id) {
  17140. for (var index = 0; index < this.particleSystems.length; index++) {
  17141. if (this.particleSystems[index].id === id) {
  17142. return this.particleSystems[index];
  17143. }
  17144. }
  17145. return null;
  17146. };
  17147. /**
  17148. * get a geometry using its ID
  17149. * @param {string} the geometry's id
  17150. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17151. */
  17152. Scene.prototype.getGeometryByID = function (id) {
  17153. for (var index = 0; index < this._geometries.length; index++) {
  17154. if (this._geometries[index].id === id) {
  17155. return this._geometries[index];
  17156. }
  17157. }
  17158. return null;
  17159. };
  17160. /**
  17161. * add a new geometry to this scene.
  17162. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17163. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17164. * @return {boolean} was the geometry added or not
  17165. */
  17166. Scene.prototype.pushGeometry = function (geometry, force) {
  17167. if (!force && this.getGeometryByID(geometry.id)) {
  17168. return false;
  17169. }
  17170. this._geometries.push(geometry);
  17171. //notify the collision coordinator
  17172. this.collisionCoordinator.onGeometryAdded(geometry);
  17173. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17174. return true;
  17175. };
  17176. /**
  17177. * Removes an existing geometry
  17178. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17179. * @return {boolean} was the geometry removed or not
  17180. */
  17181. Scene.prototype.removeGeometry = function (geometry) {
  17182. var index = this._geometries.indexOf(geometry);
  17183. if (index > -1) {
  17184. this._geometries.splice(index, 1);
  17185. //notify the collision coordinator
  17186. this.collisionCoordinator.onGeometryDeleted(geometry);
  17187. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17188. return true;
  17189. }
  17190. return false;
  17191. };
  17192. Scene.prototype.getGeometries = function () {
  17193. return this._geometries;
  17194. };
  17195. /**
  17196. * Get the first added mesh found of a given ID
  17197. * @param {string} id - the id to search for
  17198. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17199. */
  17200. Scene.prototype.getMeshByID = function (id) {
  17201. for (var index = 0; index < this.meshes.length; index++) {
  17202. if (this.meshes[index].id === id) {
  17203. return this.meshes[index];
  17204. }
  17205. }
  17206. return null;
  17207. };
  17208. Scene.prototype.getMeshesByID = function (id) {
  17209. return this.meshes.filter(function (m) {
  17210. return m.id === id;
  17211. });
  17212. };
  17213. /**
  17214. * Get a mesh with its auto-generated unique id
  17215. * @param {number} uniqueId - the unique id to search for
  17216. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17217. */
  17218. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17219. for (var index = 0; index < this.meshes.length; index++) {
  17220. if (this.meshes[index].uniqueId === uniqueId) {
  17221. return this.meshes[index];
  17222. }
  17223. }
  17224. return null;
  17225. };
  17226. /**
  17227. * Get a the last added mesh found of a given ID
  17228. * @param {string} id - the id to search for
  17229. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17230. */
  17231. Scene.prototype.getLastMeshByID = function (id) {
  17232. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17233. if (this.meshes[index].id === id) {
  17234. return this.meshes[index];
  17235. }
  17236. }
  17237. return null;
  17238. };
  17239. /**
  17240. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17241. * @param {string} id - the id to search for
  17242. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17243. */
  17244. Scene.prototype.getLastEntryByID = function (id) {
  17245. var index;
  17246. for (index = this.meshes.length - 1; index >= 0; index--) {
  17247. if (this.meshes[index].id === id) {
  17248. return this.meshes[index];
  17249. }
  17250. }
  17251. for (index = this.cameras.length - 1; index >= 0; index--) {
  17252. if (this.cameras[index].id === id) {
  17253. return this.cameras[index];
  17254. }
  17255. }
  17256. for (index = this.lights.length - 1; index >= 0; index--) {
  17257. if (this.lights[index].id === id) {
  17258. return this.lights[index];
  17259. }
  17260. }
  17261. return null;
  17262. };
  17263. Scene.prototype.getNodeByID = function (id) {
  17264. var mesh = this.getMeshByID(id);
  17265. if (mesh) {
  17266. return mesh;
  17267. }
  17268. var light = this.getLightByID(id);
  17269. if (light) {
  17270. return light;
  17271. }
  17272. var camera = this.getCameraByID(id);
  17273. if (camera) {
  17274. return camera;
  17275. }
  17276. var bone = this.getBoneByID(id);
  17277. return bone;
  17278. };
  17279. Scene.prototype.getNodeByName = function (name) {
  17280. var mesh = this.getMeshByName(name);
  17281. if (mesh) {
  17282. return mesh;
  17283. }
  17284. var light = this.getLightByName(name);
  17285. if (light) {
  17286. return light;
  17287. }
  17288. var camera = this.getCameraByName(name);
  17289. if (camera) {
  17290. return camera;
  17291. }
  17292. var bone = this.getBoneByName(name);
  17293. return bone;
  17294. };
  17295. Scene.prototype.getMeshByName = function (name) {
  17296. for (var index = 0; index < this.meshes.length; index++) {
  17297. if (this.meshes[index].name === name) {
  17298. return this.meshes[index];
  17299. }
  17300. }
  17301. return null;
  17302. };
  17303. Scene.prototype.getSoundByName = function (name) {
  17304. var index;
  17305. if (BABYLON.AudioEngine) {
  17306. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17307. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17308. return this.mainSoundTrack.soundCollection[index];
  17309. }
  17310. }
  17311. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17312. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17313. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17314. return this.soundTracks[sdIndex].soundCollection[index];
  17315. }
  17316. }
  17317. }
  17318. }
  17319. return null;
  17320. };
  17321. Scene.prototype.getLastSkeletonByID = function (id) {
  17322. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17323. if (this.skeletons[index].id === id) {
  17324. return this.skeletons[index];
  17325. }
  17326. }
  17327. return null;
  17328. };
  17329. Scene.prototype.getSkeletonById = function (id) {
  17330. for (var index = 0; index < this.skeletons.length; index++) {
  17331. if (this.skeletons[index].id === id) {
  17332. return this.skeletons[index];
  17333. }
  17334. }
  17335. return null;
  17336. };
  17337. Scene.prototype.getSkeletonByName = function (name) {
  17338. for (var index = 0; index < this.skeletons.length; index++) {
  17339. if (this.skeletons[index].name === name) {
  17340. return this.skeletons[index];
  17341. }
  17342. }
  17343. return null;
  17344. };
  17345. Scene.prototype.isActiveMesh = function (mesh) {
  17346. return (this._activeMeshes.indexOf(mesh) !== -1);
  17347. };
  17348. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17349. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17350. var material = subMesh.getMaterial();
  17351. if (mesh.showSubMeshesBoundingBox) {
  17352. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  17353. }
  17354. if (material) {
  17355. // Render targets
  17356. if (material.getRenderTargetTextures) {
  17357. if (this._processedMaterials.indexOf(material) === -1) {
  17358. this._processedMaterials.push(material);
  17359. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17360. }
  17361. }
  17362. // Dispatch
  17363. this._activeIndices.addCount(subMesh.indexCount, false);
  17364. this._renderingManager.dispatch(subMesh);
  17365. }
  17366. }
  17367. };
  17368. Scene.prototype._isInIntermediateRendering = function () {
  17369. return this._intermediateRendering;
  17370. };
  17371. Scene.prototype._evaluateActiveMeshes = function () {
  17372. this.activeCamera._activeMeshes.reset();
  17373. this._activeMeshes.reset();
  17374. this._renderingManager.reset();
  17375. this._processedMaterials.reset();
  17376. this._activeParticleSystems.reset();
  17377. this._activeSkeletons.reset();
  17378. this._softwareSkinnedMeshes.reset();
  17379. this._boundingBoxRenderer.reset();
  17380. this._edgesRenderers.reset();
  17381. // Meshes
  17382. var meshes;
  17383. var len;
  17384. if (this._selectionOctree) {
  17385. var selection = this._selectionOctree.select(this._frustumPlanes);
  17386. meshes = selection.data;
  17387. len = selection.length;
  17388. }
  17389. else {
  17390. len = this.meshes.length;
  17391. meshes = this.meshes;
  17392. }
  17393. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17394. var mesh = meshes[meshIndex];
  17395. if (mesh.isBlocked) {
  17396. continue;
  17397. }
  17398. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17399. if (!mesh.isReady() || !mesh.isEnabled()) {
  17400. continue;
  17401. }
  17402. mesh.computeWorldMatrix();
  17403. // Intersections
  17404. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17405. this._meshesForIntersections.pushNoDuplicate(mesh);
  17406. }
  17407. // Switch to current LOD
  17408. var meshLOD = mesh.getLOD(this.activeCamera);
  17409. if (!meshLOD) {
  17410. continue;
  17411. }
  17412. mesh._preActivate();
  17413. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17414. this._activeMeshes.push(mesh);
  17415. this.activeCamera._activeMeshes.push(mesh);
  17416. mesh._activate(this._renderId);
  17417. this._activeMesh(mesh, meshLOD);
  17418. }
  17419. }
  17420. // Particle systems
  17421. this._particlesDuration.beginMonitoring();
  17422. var beforeParticlesDate = BABYLON.Tools.Now;
  17423. if (this.particlesEnabled) {
  17424. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17425. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17426. var particleSystem = this.particleSystems[particleIndex];
  17427. if (!particleSystem.isStarted()) {
  17428. continue;
  17429. }
  17430. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17431. this._activeParticleSystems.push(particleSystem);
  17432. particleSystem.animate();
  17433. }
  17434. }
  17435. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17436. }
  17437. this._particlesDuration.endMonitoring(false);
  17438. };
  17439. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17440. if (mesh.skeleton && this.skeletonsEnabled) {
  17441. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17442. mesh.skeleton.prepare();
  17443. }
  17444. if (!mesh.computeBonesUsingShaders) {
  17445. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17446. }
  17447. }
  17448. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17449. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17450. }
  17451. if (sourceMesh._edgesRenderer) {
  17452. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  17453. }
  17454. if (mesh && mesh.subMeshes) {
  17455. // Submeshes Octrees
  17456. var len;
  17457. var subMeshes;
  17458. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17459. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17460. len = intersections.length;
  17461. subMeshes = intersections.data;
  17462. }
  17463. else {
  17464. subMeshes = mesh.subMeshes;
  17465. len = subMeshes.length;
  17466. }
  17467. for (var subIndex = 0; subIndex < len; subIndex++) {
  17468. var subMesh = subMeshes[subIndex];
  17469. this._evaluateSubMesh(subMesh, mesh);
  17470. }
  17471. }
  17472. };
  17473. Scene.prototype.updateTransformMatrix = function (force) {
  17474. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17475. };
  17476. Scene.prototype._renderForCamera = function (camera) {
  17477. var engine = this._engine;
  17478. var startTime = BABYLON.Tools.Now;
  17479. this.activeCamera = camera;
  17480. if (!this.activeCamera)
  17481. throw new Error("Active camera not set");
  17482. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17483. // Viewport
  17484. engine.setViewport(this.activeCamera.viewport);
  17485. // Camera
  17486. this.resetCachedMaterial();
  17487. this._renderId++;
  17488. this.updateTransformMatrix();
  17489. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17490. // Meshes
  17491. this._evaluateActiveMeshesDuration.beginMonitoring();
  17492. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17493. this._evaluateActiveMeshes();
  17494. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17495. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17496. // Software skinning
  17497. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17498. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17499. mesh.applySkeleton(mesh.skeleton);
  17500. }
  17501. // Render targets
  17502. this._renderTargetsDuration.beginMonitoring();
  17503. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17504. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17505. this._intermediateRendering = true;
  17506. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17507. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17508. var renderTarget = this._renderTargets.data[renderIndex];
  17509. if (renderTarget._shouldRender()) {
  17510. this._renderId++;
  17511. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17512. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17513. }
  17514. }
  17515. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17516. this._intermediateRendering = false;
  17517. this._renderId++;
  17518. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17519. }
  17520. this._renderTargetsDuration.endMonitoring(false);
  17521. // Prepare Frame
  17522. this.postProcessManager._prepareFrame();
  17523. this._renderDuration.beginMonitoring();
  17524. // Backgrounds
  17525. var layerIndex;
  17526. var layer;
  17527. if (this.layers.length) {
  17528. engine.setDepthBuffer(false);
  17529. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17530. layer = this.layers[layerIndex];
  17531. if (layer.isBackground) {
  17532. layer.render();
  17533. }
  17534. }
  17535. engine.setDepthBuffer(true);
  17536. }
  17537. // Render
  17538. BABYLON.Tools.StartPerformanceCounter("Main render");
  17539. this._renderingManager.render(null, null, true, true);
  17540. BABYLON.Tools.EndPerformanceCounter("Main render");
  17541. // Bounding boxes
  17542. this._boundingBoxRenderer.render();
  17543. // Edges
  17544. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17545. this._edgesRenderers.data[edgesRendererIndex].render();
  17546. }
  17547. // Lens flares
  17548. if (this.lensFlaresEnabled) {
  17549. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17550. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17551. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17552. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17553. lensFlareSystem.render();
  17554. }
  17555. }
  17556. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17557. }
  17558. // Foregrounds
  17559. if (this.layers.length) {
  17560. engine.setDepthBuffer(false);
  17561. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17562. layer = this.layers[layerIndex];
  17563. if (!layer.isBackground) {
  17564. layer.render();
  17565. }
  17566. }
  17567. engine.setDepthBuffer(true);
  17568. }
  17569. this._renderDuration.endMonitoring(false);
  17570. // Finalize frame
  17571. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17572. // Update camera
  17573. this.activeCamera._updateFromScene();
  17574. // Reset some special arrays
  17575. this._renderTargets.reset();
  17576. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17577. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17578. };
  17579. Scene.prototype._processSubCameras = function (camera) {
  17580. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17581. this._renderForCamera(camera);
  17582. return;
  17583. }
  17584. // rig cameras
  17585. for (var index = 0; index < camera._rigCameras.length; index++) {
  17586. this._renderForCamera(camera._rigCameras[index]);
  17587. }
  17588. this.activeCamera = camera;
  17589. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17590. // Update camera
  17591. this.activeCamera._updateFromScene();
  17592. };
  17593. Scene.prototype._checkIntersections = function () {
  17594. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17595. var sourceMesh = this._meshesForIntersections.data[index];
  17596. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17597. var action = sourceMesh.actionManager.actions[actionIndex];
  17598. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17599. var parameters = action.getTriggerParameter();
  17600. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17601. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17602. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17603. if (areIntersecting && currentIntersectionInProgress === -1) {
  17604. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17605. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17606. sourceMesh._intersectionsInProgress.push(otherMesh);
  17607. }
  17608. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17609. sourceMesh._intersectionsInProgress.push(otherMesh);
  17610. }
  17611. }
  17612. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17613. //They intersected, and now they don't.
  17614. //is this trigger an exit trigger? execute an event.
  17615. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17616. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17617. }
  17618. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17619. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17620. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17621. }
  17622. }
  17623. }
  17624. }
  17625. }
  17626. };
  17627. Scene.prototype.render = function () {
  17628. this._lastFrameDuration.beginMonitoring();
  17629. this._particlesDuration.fetchNewFrame();
  17630. this._spritesDuration.fetchNewFrame();
  17631. this._activeParticles.fetchNewFrame();
  17632. this._renderDuration.fetchNewFrame();
  17633. this._renderTargetsDuration.fetchNewFrame();
  17634. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17635. this._totalVertices.fetchNewFrame();
  17636. this._activeIndices.fetchNewFrame();
  17637. this._activeBones.fetchNewFrame();
  17638. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17639. this._meshesForIntersections.reset();
  17640. this.resetCachedMaterial();
  17641. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17642. // Actions
  17643. if (this.actionManager) {
  17644. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17645. }
  17646. //Simplification Queue
  17647. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17648. this.simplificationQueue.executeNext();
  17649. }
  17650. // Animations
  17651. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17652. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17653. this._animate();
  17654. // Physics
  17655. if (this._physicsEngine) {
  17656. BABYLON.Tools.StartPerformanceCounter("Physics");
  17657. this._physicsEngine._step(deltaTime / 1000.0);
  17658. BABYLON.Tools.EndPerformanceCounter("Physics");
  17659. }
  17660. // Before render
  17661. this.onBeforeRenderObservable.notifyObservers(this);
  17662. // Customs render targets
  17663. this._renderTargetsDuration.beginMonitoring();
  17664. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17665. var engine = this.getEngine();
  17666. var currentActiveCamera = this.activeCamera;
  17667. if (this.renderTargetsEnabled) {
  17668. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17669. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17670. var renderTarget = this.customRenderTargets[customIndex];
  17671. if (renderTarget._shouldRender()) {
  17672. this._renderId++;
  17673. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17674. if (!this.activeCamera)
  17675. throw new Error("Active camera not set");
  17676. // Viewport
  17677. engine.setViewport(this.activeCamera.viewport);
  17678. // Camera
  17679. this.updateTransformMatrix();
  17680. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17681. }
  17682. }
  17683. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17684. this._renderId++;
  17685. }
  17686. if (this.customRenderTargets.length > 0) {
  17687. engine.restoreDefaultFramebuffer();
  17688. }
  17689. this._renderTargetsDuration.endMonitoring();
  17690. this.activeCamera = currentActiveCamera;
  17691. // Procedural textures
  17692. if (this.proceduralTexturesEnabled) {
  17693. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17694. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17695. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17696. if (proceduralTexture._shouldRender()) {
  17697. proceduralTexture.render();
  17698. }
  17699. }
  17700. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17701. }
  17702. // Clear
  17703. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  17704. // Shadows
  17705. if (this.shadowsEnabled) {
  17706. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17707. var light = this.lights[lightIndex];
  17708. var shadowGenerator = light.getShadowGenerator();
  17709. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  17710. this._renderTargets.push(shadowGenerator.getShadowMap());
  17711. }
  17712. }
  17713. }
  17714. // Depth renderer
  17715. if (this._depthRenderer) {
  17716. this._renderTargets.push(this._depthRenderer.getDepthMap());
  17717. }
  17718. // RenderPipeline
  17719. this.postProcessRenderPipelineManager.update();
  17720. // Multi-cameras?
  17721. if (this.activeCameras.length > 0) {
  17722. var currentRenderId = this._renderId;
  17723. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  17724. this._renderId = currentRenderId;
  17725. if (cameraIndex > 0) {
  17726. this._engine.clear(0, false, true, true);
  17727. }
  17728. this._processSubCameras(this.activeCameras[cameraIndex]);
  17729. }
  17730. }
  17731. else {
  17732. if (!this.activeCamera) {
  17733. throw new Error("No camera defined");
  17734. }
  17735. this._processSubCameras(this.activeCamera);
  17736. }
  17737. // Intersection checks
  17738. this._checkIntersections();
  17739. // Update the audio listener attached to the camera
  17740. if (BABYLON.AudioEngine) {
  17741. this._updateAudioParameters();
  17742. }
  17743. // After render
  17744. if (this.afterRender) {
  17745. this.afterRender();
  17746. }
  17747. this.onAfterRenderObservable.notifyObservers(this);
  17748. // Cleaning
  17749. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17750. this._toBeDisposed.data[index].dispose();
  17751. this._toBeDisposed[index] = null;
  17752. }
  17753. this._toBeDisposed.reset();
  17754. if (this.dumpNextRenderTargets) {
  17755. this.dumpNextRenderTargets = false;
  17756. }
  17757. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17758. this._lastFrameDuration.endMonitoring();
  17759. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17760. this._totalLightsCounter.addCount(this.lights.length, true);
  17761. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17762. this._totalTexturesCounter.addCount(this.textures.length, true);
  17763. this._activeBones.addCount(0, true);
  17764. this._activeIndices.addCount(0, true);
  17765. this._activeParticles.addCount(0, true);
  17766. };
  17767. Scene.prototype._updateAudioParameters = function () {
  17768. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17769. return;
  17770. }
  17771. var listeningCamera;
  17772. var audioEngine = BABYLON.Engine.audioEngine;
  17773. if (this.activeCameras.length > 0) {
  17774. listeningCamera = this.activeCameras[0];
  17775. }
  17776. else {
  17777. listeningCamera = this.activeCamera;
  17778. }
  17779. if (listeningCamera && audioEngine.canUseWebAudio) {
  17780. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17781. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17782. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17783. cameraDirection.normalize();
  17784. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17785. var i;
  17786. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17787. var sound = this.mainSoundTrack.soundCollection[i];
  17788. if (sound.useCustomAttenuation) {
  17789. sound.updateDistanceFromListener();
  17790. }
  17791. }
  17792. for (i = 0; i < this.soundTracks.length; i++) {
  17793. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17794. sound = this.soundTracks[i].soundCollection[j];
  17795. if (sound.useCustomAttenuation) {
  17796. sound.updateDistanceFromListener();
  17797. }
  17798. }
  17799. }
  17800. }
  17801. };
  17802. Object.defineProperty(Scene.prototype, "audioEnabled", {
  17803. // Audio
  17804. get: function () {
  17805. return this._audioEnabled;
  17806. },
  17807. set: function (value) {
  17808. this._audioEnabled = value;
  17809. if (BABYLON.AudioEngine) {
  17810. if (this._audioEnabled) {
  17811. this._enableAudio();
  17812. }
  17813. else {
  17814. this._disableAudio();
  17815. }
  17816. }
  17817. },
  17818. enumerable: true,
  17819. configurable: true
  17820. });
  17821. Scene.prototype._disableAudio = function () {
  17822. var i;
  17823. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17824. this.mainSoundTrack.soundCollection[i].pause();
  17825. }
  17826. for (i = 0; i < this.soundTracks.length; i++) {
  17827. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17828. this.soundTracks[i].soundCollection[j].pause();
  17829. }
  17830. }
  17831. };
  17832. Scene.prototype._enableAudio = function () {
  17833. var i;
  17834. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17835. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17836. this.mainSoundTrack.soundCollection[i].play();
  17837. }
  17838. }
  17839. for (i = 0; i < this.soundTracks.length; i++) {
  17840. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17841. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17842. this.soundTracks[i].soundCollection[j].play();
  17843. }
  17844. }
  17845. }
  17846. };
  17847. Object.defineProperty(Scene.prototype, "headphone", {
  17848. get: function () {
  17849. return this._headphone;
  17850. },
  17851. set: function (value) {
  17852. this._headphone = value;
  17853. if (BABYLON.AudioEngine) {
  17854. if (this._headphone) {
  17855. this._switchAudioModeForHeadphones();
  17856. }
  17857. else {
  17858. this._switchAudioModeForNormalSpeakers();
  17859. }
  17860. }
  17861. },
  17862. enumerable: true,
  17863. configurable: true
  17864. });
  17865. Scene.prototype._switchAudioModeForHeadphones = function () {
  17866. this.mainSoundTrack.switchPanningModelToHRTF();
  17867. for (var i = 0; i < this.soundTracks.length; i++) {
  17868. this.soundTracks[i].switchPanningModelToHRTF();
  17869. }
  17870. };
  17871. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17872. this.mainSoundTrack.switchPanningModelToEqualPower();
  17873. for (var i = 0; i < this.soundTracks.length; i++) {
  17874. this.soundTracks[i].switchPanningModelToEqualPower();
  17875. }
  17876. };
  17877. Scene.prototype.enableDepthRenderer = function () {
  17878. if (this._depthRenderer) {
  17879. return this._depthRenderer;
  17880. }
  17881. this._depthRenderer = new BABYLON.DepthRenderer(this);
  17882. return this._depthRenderer;
  17883. };
  17884. Scene.prototype.disableDepthRenderer = function () {
  17885. if (!this._depthRenderer) {
  17886. return;
  17887. }
  17888. this._depthRenderer.dispose();
  17889. this._depthRenderer = null;
  17890. };
  17891. Scene.prototype.freezeMaterials = function () {
  17892. for (var i = 0; i < this.materials.length; i++) {
  17893. this.materials[i].freeze();
  17894. }
  17895. };
  17896. Scene.prototype.unfreezeMaterials = function () {
  17897. for (var i = 0; i < this.materials.length; i++) {
  17898. this.materials[i].unfreeze();
  17899. }
  17900. };
  17901. Scene.prototype.dispose = function () {
  17902. this.beforeRender = null;
  17903. this.afterRender = null;
  17904. this.skeletons = [];
  17905. this._boundingBoxRenderer.dispose();
  17906. if (this._depthRenderer) {
  17907. this._depthRenderer.dispose();
  17908. }
  17909. // Debug layer
  17910. if (this._debugLayer) {
  17911. this._debugLayer.hide();
  17912. }
  17913. // Events
  17914. this.onDisposeObservable.notifyObservers(this);
  17915. this.onDisposeObservable.clear();
  17916. this.onBeforeRenderObservable.clear();
  17917. this.onAfterRenderObservable.clear();
  17918. this.detachControl();
  17919. // Release sounds & sounds tracks
  17920. if (BABYLON.AudioEngine) {
  17921. this.disposeSounds();
  17922. }
  17923. // Detach cameras
  17924. var canvas = this._engine.getRenderingCanvas();
  17925. var index;
  17926. for (index = 0; index < this.cameras.length; index++) {
  17927. this.cameras[index].detachControl(canvas);
  17928. }
  17929. // Release lights
  17930. while (this.lights.length) {
  17931. this.lights[0].dispose();
  17932. }
  17933. // Release meshes
  17934. while (this.meshes.length) {
  17935. this.meshes[0].dispose(true);
  17936. }
  17937. // Release cameras
  17938. while (this.cameras.length) {
  17939. this.cameras[0].dispose();
  17940. }
  17941. // Release materials
  17942. while (this.materials.length) {
  17943. this.materials[0].dispose();
  17944. }
  17945. // Release particles
  17946. while (this.particleSystems.length) {
  17947. this.particleSystems[0].dispose();
  17948. }
  17949. // Release sprites
  17950. while (this.spriteManagers.length) {
  17951. this.spriteManagers[0].dispose();
  17952. }
  17953. // Release layers
  17954. while (this.layers.length) {
  17955. this.layers[0].dispose();
  17956. }
  17957. // Release textures
  17958. while (this.textures.length) {
  17959. this.textures[0].dispose();
  17960. }
  17961. // Post-processes
  17962. this.postProcessManager.dispose();
  17963. // Physics
  17964. if (this._physicsEngine) {
  17965. this.disablePhysicsEngine();
  17966. }
  17967. // Remove from engine
  17968. index = this._engine.scenes.indexOf(this);
  17969. if (index > -1) {
  17970. this._engine.scenes.splice(index, 1);
  17971. }
  17972. this._engine.wipeCaches();
  17973. };
  17974. // Release sounds & sounds tracks
  17975. Scene.prototype.disposeSounds = function () {
  17976. this.mainSoundTrack.dispose();
  17977. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  17978. this.soundTracks[scIndex].dispose();
  17979. }
  17980. };
  17981. // Octrees
  17982. Scene.prototype.getWorldExtends = function () {
  17983. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17984. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17985. for (var index = 0; index < this.meshes.length; index++) {
  17986. var mesh = this.meshes[index];
  17987. mesh.computeWorldMatrix(true);
  17988. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  17989. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  17990. BABYLON.Tools.CheckExtends(minBox, min, max);
  17991. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17992. }
  17993. return {
  17994. min: min,
  17995. max: max
  17996. };
  17997. };
  17998. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  17999. if (maxCapacity === void 0) { maxCapacity = 64; }
  18000. if (maxDepth === void 0) { maxDepth = 2; }
  18001. if (!this._selectionOctree) {
  18002. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18003. }
  18004. var worldExtends = this.getWorldExtends();
  18005. // Update octree
  18006. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18007. return this._selectionOctree;
  18008. };
  18009. // Picking
  18010. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18011. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18012. var engine = this._engine;
  18013. if (!camera) {
  18014. if (!this.activeCamera)
  18015. throw new Error("Active camera not set");
  18016. camera = this.activeCamera;
  18017. }
  18018. var cameraViewport = camera.viewport;
  18019. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18020. // Moving coordinates to local viewport world
  18021. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18022. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18023. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18024. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18025. };
  18026. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18027. var engine = this._engine;
  18028. if (!camera) {
  18029. if (!this.activeCamera)
  18030. throw new Error("Active camera not set");
  18031. camera = this.activeCamera;
  18032. }
  18033. var cameraViewport = camera.viewport;
  18034. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18035. var identity = BABYLON.Matrix.Identity();
  18036. // Moving coordinates to local viewport world
  18037. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18038. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18039. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18040. };
  18041. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18042. var pickingInfo = null;
  18043. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18044. var mesh = this.meshes[meshIndex];
  18045. if (predicate) {
  18046. if (!predicate(mesh)) {
  18047. continue;
  18048. }
  18049. }
  18050. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18051. continue;
  18052. }
  18053. var world = mesh.getWorldMatrix();
  18054. var ray = rayFunction(world);
  18055. var result = mesh.intersects(ray, fastCheck);
  18056. if (!result || !result.hit)
  18057. continue;
  18058. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18059. continue;
  18060. pickingInfo = result;
  18061. if (fastCheck) {
  18062. break;
  18063. }
  18064. }
  18065. return pickingInfo || new BABYLON.PickingInfo();
  18066. };
  18067. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18068. var pickingInfo = null;
  18069. camera = camera || this.activeCamera;
  18070. if (this.spriteManagers.length > 0) {
  18071. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18072. var spriteManager = this.spriteManagers[spriteIndex];
  18073. if (!spriteManager.isPickable) {
  18074. continue;
  18075. }
  18076. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18077. if (!result || !result.hit)
  18078. continue;
  18079. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18080. continue;
  18081. pickingInfo = result;
  18082. if (fastCheck) {
  18083. break;
  18084. }
  18085. }
  18086. }
  18087. return pickingInfo || new BABYLON.PickingInfo();
  18088. };
  18089. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18090. var _this = this;
  18091. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18092. /// <param name="x">X position on screen</param>
  18093. /// <param name="y">Y position on screen</param>
  18094. /// <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>
  18095. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18096. /// <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>
  18097. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18098. };
  18099. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18100. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18101. /// <param name="x">X position on screen</param>
  18102. /// <param name="y">Y position on screen</param>
  18103. /// <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>
  18104. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18105. /// <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>
  18106. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18107. };
  18108. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18109. var _this = this;
  18110. return this._internalPick(function (world) {
  18111. if (!_this._pickWithRayInverseMatrix) {
  18112. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18113. }
  18114. world.invertToRef(_this._pickWithRayInverseMatrix);
  18115. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18116. }, predicate, fastCheck);
  18117. };
  18118. Scene.prototype.setPointerOverMesh = function (mesh) {
  18119. if (this._pointerOverMesh === mesh) {
  18120. return;
  18121. }
  18122. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18123. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18124. }
  18125. this._pointerOverMesh = mesh;
  18126. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18127. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18128. }
  18129. };
  18130. Scene.prototype.getPointerOverMesh = function () {
  18131. return this._pointerOverMesh;
  18132. };
  18133. Scene.prototype.setPointerOverSprite = function (sprite) {
  18134. if (this._pointerOverSprite === sprite) {
  18135. return;
  18136. }
  18137. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18138. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18139. }
  18140. this._pointerOverSprite = sprite;
  18141. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18142. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18143. }
  18144. };
  18145. Scene.prototype.getPointerOverSprite = function () {
  18146. return this._pointerOverSprite;
  18147. };
  18148. // Physics
  18149. Scene.prototype.getPhysicsEngine = function () {
  18150. return this._physicsEngine;
  18151. };
  18152. /**
  18153. * Enables physics to the current scene
  18154. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18155. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18156. * @return {boolean} was the physics engine initialized
  18157. */
  18158. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18159. if (this._physicsEngine) {
  18160. return true;
  18161. }
  18162. try {
  18163. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18164. return true;
  18165. }
  18166. catch (e) {
  18167. BABYLON.Tools.Error(e.message);
  18168. return false;
  18169. }
  18170. };
  18171. Scene.prototype.disablePhysicsEngine = function () {
  18172. if (!this._physicsEngine) {
  18173. return;
  18174. }
  18175. this._physicsEngine.dispose();
  18176. this._physicsEngine = undefined;
  18177. };
  18178. Scene.prototype.isPhysicsEnabled = function () {
  18179. return this._physicsEngine !== undefined;
  18180. };
  18181. /**
  18182. *
  18183. * Sets the gravity of the physics engine (and NOT of the scene)
  18184. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  18185. */
  18186. Scene.prototype.setGravity = function (gravity) {
  18187. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  18188. if (!this._physicsEngine) {
  18189. return;
  18190. }
  18191. this._physicsEngine.setGravity(gravity);
  18192. };
  18193. /**
  18194. * Legacy support, using the new API
  18195. * @Deprecated
  18196. */
  18197. Scene.prototype.createCompoundImpostor = function (parts, options) {
  18198. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  18199. if (parts.parts) {
  18200. options = parts;
  18201. parts = parts.parts;
  18202. }
  18203. var mainMesh = parts[0].mesh;
  18204. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  18205. for (var index = 1; index < parts.length; index++) {
  18206. var mesh = parts[index].mesh;
  18207. if (mesh.parent !== mainMesh) {
  18208. mesh.position = mesh.position.subtract(mainMesh.position);
  18209. mesh.parent = mainMesh;
  18210. }
  18211. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  18212. }
  18213. mainMesh.physicsImpostor.forceUpdate();
  18214. };
  18215. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18216. var mesh = compound.parts[0].mesh;
  18217. mesh.physicsImpostor.dispose();
  18218. mesh.physicsImpostor = null;
  18219. };
  18220. // Misc.
  18221. Scene.prototype.createDefaultCameraOrLight = function () {
  18222. // Light
  18223. if (this.lights.length === 0) {
  18224. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18225. }
  18226. // Camera
  18227. if (!this.activeCamera) {
  18228. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  18229. // Compute position
  18230. var worldExtends = this.getWorldExtends();
  18231. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  18232. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  18233. camera.setTarget(worldCenter);
  18234. this.activeCamera = camera;
  18235. }
  18236. };
  18237. // Tags
  18238. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18239. if (tagsQuery === undefined) {
  18240. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18241. return list;
  18242. }
  18243. var listByTags = [];
  18244. forEach = forEach || (function (item) { return; });
  18245. for (var i in list) {
  18246. var item = list[i];
  18247. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18248. listByTags.push(item);
  18249. forEach(item);
  18250. }
  18251. }
  18252. return listByTags;
  18253. };
  18254. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18255. return this._getByTags(this.meshes, tagsQuery, forEach);
  18256. };
  18257. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18258. return this._getByTags(this.cameras, tagsQuery, forEach);
  18259. };
  18260. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18261. return this._getByTags(this.lights, tagsQuery, forEach);
  18262. };
  18263. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18264. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18265. };
  18266. /**
  18267. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18268. * This allowed control for front to back rendering or reversly depending of the special needs.
  18269. *
  18270. * @param renderingGroupId The rendering group id corresponding to its index
  18271. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18272. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18273. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18274. */
  18275. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18276. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18277. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18278. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18279. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18280. };
  18281. /**
  18282. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18283. *
  18284. * @param renderingGroupId The rendering group id corresponding to its index
  18285. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18286. */
  18287. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  18288. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  18289. };
  18290. // Statics
  18291. Scene._FOGMODE_NONE = 0;
  18292. Scene._FOGMODE_EXP = 1;
  18293. Scene._FOGMODE_EXP2 = 2;
  18294. Scene._FOGMODE_LINEAR = 3;
  18295. Scene.MinDeltaTime = 1.0;
  18296. Scene.MaxDeltaTime = 1000.0;
  18297. return Scene;
  18298. })();
  18299. BABYLON.Scene = Scene;
  18300. })(BABYLON || (BABYLON = {}));
  18301. var BABYLON;
  18302. (function (BABYLON) {
  18303. var Buffer = (function () {
  18304. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18305. if (engine instanceof BABYLON.Mesh) {
  18306. this._engine = engine.getScene().getEngine();
  18307. }
  18308. else {
  18309. this._engine = engine;
  18310. }
  18311. this._updatable = updatable;
  18312. this._data = data;
  18313. this._strideSize = stride;
  18314. if (!postponeInternalCreation) {
  18315. this.create();
  18316. }
  18317. this._instanced = instanced;
  18318. }
  18319. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18320. // a lot of these parameters are ignored as they are overriden by the buffer
  18321. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18322. };
  18323. // Properties
  18324. Buffer.prototype.isUpdatable = function () {
  18325. return this._updatable;
  18326. };
  18327. Buffer.prototype.getData = function () {
  18328. return this._data;
  18329. };
  18330. Buffer.prototype.getBuffer = function () {
  18331. return this._buffer;
  18332. };
  18333. Buffer.prototype.getStrideSize = function () {
  18334. return this._strideSize;
  18335. };
  18336. Buffer.prototype.getIsInstanced = function () {
  18337. return this._instanced;
  18338. };
  18339. // Methods
  18340. Buffer.prototype.create = function (data) {
  18341. if (!data && this._buffer) {
  18342. return; // nothing to do
  18343. }
  18344. data = data || this._data;
  18345. if (!this._buffer) {
  18346. if (this._updatable) {
  18347. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18348. this._data = data;
  18349. }
  18350. else {
  18351. this._buffer = this._engine.createVertexBuffer(data);
  18352. }
  18353. }
  18354. else if (this._updatable) {
  18355. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18356. this._data = data;
  18357. }
  18358. };
  18359. Buffer.prototype.update = function (data) {
  18360. this.create(data);
  18361. };
  18362. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18363. if (!this._buffer) {
  18364. return;
  18365. }
  18366. if (this._updatable) {
  18367. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18368. this._data = null;
  18369. }
  18370. };
  18371. Buffer.prototype.dispose = function () {
  18372. if (!this._buffer) {
  18373. return;
  18374. }
  18375. if (this._engine._releaseBuffer(this._buffer)) {
  18376. this._buffer = null;
  18377. }
  18378. };
  18379. return Buffer;
  18380. })();
  18381. BABYLON.Buffer = Buffer;
  18382. })(BABYLON || (BABYLON = {}));
  18383. var BABYLON;
  18384. (function (BABYLON) {
  18385. var VertexBuffer = (function () {
  18386. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18387. if (!stride) {
  18388. // Deduce stride from kind
  18389. switch (kind) {
  18390. case VertexBuffer.PositionKind:
  18391. stride = 3;
  18392. break;
  18393. case VertexBuffer.NormalKind:
  18394. stride = 3;
  18395. break;
  18396. case VertexBuffer.UVKind:
  18397. case VertexBuffer.UV2Kind:
  18398. case VertexBuffer.UV3Kind:
  18399. case VertexBuffer.UV4Kind:
  18400. case VertexBuffer.UV5Kind:
  18401. case VertexBuffer.UV6Kind:
  18402. stride = 2;
  18403. break;
  18404. case VertexBuffer.ColorKind:
  18405. stride = 4;
  18406. break;
  18407. case VertexBuffer.MatricesIndicesKind:
  18408. case VertexBuffer.MatricesIndicesExtraKind:
  18409. stride = 4;
  18410. break;
  18411. case VertexBuffer.MatricesWeightsKind:
  18412. case VertexBuffer.MatricesWeightsExtraKind:
  18413. stride = 4;
  18414. break;
  18415. }
  18416. }
  18417. if (data instanceof BABYLON.Buffer) {
  18418. if (!stride) {
  18419. stride = data.getStrideSize();
  18420. }
  18421. this._buffer = data;
  18422. this._ownsBuffer = false;
  18423. }
  18424. else {
  18425. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18426. this._ownsBuffer = true;
  18427. }
  18428. this._stride = stride;
  18429. this._offset = offset ? offset : 0;
  18430. this._size = size ? size : stride;
  18431. this._kind = kind;
  18432. }
  18433. VertexBuffer.prototype.getKind = function () {
  18434. return this._kind;
  18435. };
  18436. // Properties
  18437. VertexBuffer.prototype.isUpdatable = function () {
  18438. return this._buffer.isUpdatable();
  18439. };
  18440. VertexBuffer.prototype.getData = function () {
  18441. return this._buffer.getData();
  18442. };
  18443. VertexBuffer.prototype.getBuffer = function () {
  18444. return this._buffer.getBuffer();
  18445. };
  18446. VertexBuffer.prototype.getStrideSize = function () {
  18447. return this._stride;
  18448. };
  18449. VertexBuffer.prototype.getOffset = function () {
  18450. return this._offset;
  18451. };
  18452. VertexBuffer.prototype.getSize = function () {
  18453. return this._size;
  18454. };
  18455. VertexBuffer.prototype.getIsInstanced = function () {
  18456. return this._buffer.getIsInstanced();
  18457. };
  18458. // Methods
  18459. VertexBuffer.prototype.create = function (data) {
  18460. return this._buffer.create(data);
  18461. };
  18462. VertexBuffer.prototype.update = function (data) {
  18463. return this._buffer.update(data);
  18464. };
  18465. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18466. return this._buffer.updateDirectly(data, offset);
  18467. };
  18468. VertexBuffer.prototype.dispose = function () {
  18469. if (this._ownsBuffer) {
  18470. this._buffer.dispose();
  18471. }
  18472. };
  18473. Object.defineProperty(VertexBuffer, "PositionKind", {
  18474. get: function () {
  18475. return VertexBuffer._PositionKind;
  18476. },
  18477. enumerable: true,
  18478. configurable: true
  18479. });
  18480. Object.defineProperty(VertexBuffer, "NormalKind", {
  18481. get: function () {
  18482. return VertexBuffer._NormalKind;
  18483. },
  18484. enumerable: true,
  18485. configurable: true
  18486. });
  18487. Object.defineProperty(VertexBuffer, "UVKind", {
  18488. get: function () {
  18489. return VertexBuffer._UVKind;
  18490. },
  18491. enumerable: true,
  18492. configurable: true
  18493. });
  18494. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18495. get: function () {
  18496. return VertexBuffer._UV2Kind;
  18497. },
  18498. enumerable: true,
  18499. configurable: true
  18500. });
  18501. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18502. get: function () {
  18503. return VertexBuffer._UV3Kind;
  18504. },
  18505. enumerable: true,
  18506. configurable: true
  18507. });
  18508. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18509. get: function () {
  18510. return VertexBuffer._UV4Kind;
  18511. },
  18512. enumerable: true,
  18513. configurable: true
  18514. });
  18515. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18516. get: function () {
  18517. return VertexBuffer._UV5Kind;
  18518. },
  18519. enumerable: true,
  18520. configurable: true
  18521. });
  18522. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18523. get: function () {
  18524. return VertexBuffer._UV6Kind;
  18525. },
  18526. enumerable: true,
  18527. configurable: true
  18528. });
  18529. Object.defineProperty(VertexBuffer, "ColorKind", {
  18530. get: function () {
  18531. return VertexBuffer._ColorKind;
  18532. },
  18533. enumerable: true,
  18534. configurable: true
  18535. });
  18536. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18537. get: function () {
  18538. return VertexBuffer._MatricesIndicesKind;
  18539. },
  18540. enumerable: true,
  18541. configurable: true
  18542. });
  18543. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18544. get: function () {
  18545. return VertexBuffer._MatricesWeightsKind;
  18546. },
  18547. enumerable: true,
  18548. configurable: true
  18549. });
  18550. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18551. get: function () {
  18552. return VertexBuffer._MatricesIndicesExtraKind;
  18553. },
  18554. enumerable: true,
  18555. configurable: true
  18556. });
  18557. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18558. get: function () {
  18559. return VertexBuffer._MatricesWeightsExtraKind;
  18560. },
  18561. enumerable: true,
  18562. configurable: true
  18563. });
  18564. // Enums
  18565. VertexBuffer._PositionKind = "position";
  18566. VertexBuffer._NormalKind = "normal";
  18567. VertexBuffer._UVKind = "uv";
  18568. VertexBuffer._UV2Kind = "uv2";
  18569. VertexBuffer._UV3Kind = "uv3";
  18570. VertexBuffer._UV4Kind = "uv4";
  18571. VertexBuffer._UV5Kind = "uv5";
  18572. VertexBuffer._UV6Kind = "uv6";
  18573. VertexBuffer._ColorKind = "color";
  18574. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18575. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18576. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18577. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18578. return VertexBuffer;
  18579. })();
  18580. BABYLON.VertexBuffer = VertexBuffer;
  18581. })(BABYLON || (BABYLON = {}));
  18582. var BABYLON;
  18583. (function (BABYLON) {
  18584. /**
  18585. * Creates an instance based on a source mesh.
  18586. */
  18587. var InstancedMesh = (function (_super) {
  18588. __extends(InstancedMesh, _super);
  18589. function InstancedMesh(name, source) {
  18590. _super.call(this, name, source.getScene());
  18591. source.instances.push(this);
  18592. this._sourceMesh = source;
  18593. this.position.copyFrom(source.position);
  18594. this.rotation.copyFrom(source.rotation);
  18595. this.scaling.copyFrom(source.scaling);
  18596. if (source.rotationQuaternion) {
  18597. this.rotationQuaternion = source.rotationQuaternion.clone();
  18598. }
  18599. this.infiniteDistance = source.infiniteDistance;
  18600. this.setPivotMatrix(source.getPivotMatrix());
  18601. this.refreshBoundingInfo();
  18602. this._syncSubMeshes();
  18603. }
  18604. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  18605. // Methods
  18606. get: function () {
  18607. return this._sourceMesh.receiveShadows;
  18608. },
  18609. enumerable: true,
  18610. configurable: true
  18611. });
  18612. Object.defineProperty(InstancedMesh.prototype, "material", {
  18613. get: function () {
  18614. return this._sourceMesh.material;
  18615. },
  18616. enumerable: true,
  18617. configurable: true
  18618. });
  18619. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  18620. get: function () {
  18621. return this._sourceMesh.visibility;
  18622. },
  18623. enumerable: true,
  18624. configurable: true
  18625. });
  18626. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  18627. get: function () {
  18628. return this._sourceMesh.skeleton;
  18629. },
  18630. enumerable: true,
  18631. configurable: true
  18632. });
  18633. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  18634. get: function () {
  18635. return this._sourceMesh.renderingGroupId;
  18636. },
  18637. enumerable: true,
  18638. configurable: true
  18639. });
  18640. InstancedMesh.prototype.getTotalVertices = function () {
  18641. return this._sourceMesh.getTotalVertices();
  18642. };
  18643. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  18644. get: function () {
  18645. return this._sourceMesh;
  18646. },
  18647. enumerable: true,
  18648. configurable: true
  18649. });
  18650. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  18651. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  18652. };
  18653. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  18654. return this._sourceMesh.isVerticesDataPresent(kind);
  18655. };
  18656. InstancedMesh.prototype.getIndices = function () {
  18657. return this._sourceMesh.getIndices();
  18658. };
  18659. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  18660. get: function () {
  18661. return this._sourceMesh._positions;
  18662. },
  18663. enumerable: true,
  18664. configurable: true
  18665. });
  18666. InstancedMesh.prototype.refreshBoundingInfo = function () {
  18667. var meshBB = this._sourceMesh.getBoundingInfo();
  18668. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  18669. this._updateBoundingInfo();
  18670. };
  18671. InstancedMesh.prototype._preActivate = function () {
  18672. if (this._currentLOD) {
  18673. this._currentLOD._preActivate();
  18674. }
  18675. };
  18676. InstancedMesh.prototype._activate = function (renderId) {
  18677. if (this._currentLOD) {
  18678. this._currentLOD._registerInstanceForRenderId(this, renderId);
  18679. }
  18680. };
  18681. InstancedMesh.prototype.getLOD = function (camera) {
  18682. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  18683. if (this._currentLOD === this.sourceMesh) {
  18684. return this;
  18685. }
  18686. return this._currentLOD;
  18687. };
  18688. InstancedMesh.prototype._syncSubMeshes = function () {
  18689. this.releaseSubMeshes();
  18690. if (this._sourceMesh.subMeshes) {
  18691. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  18692. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  18693. }
  18694. }
  18695. };
  18696. InstancedMesh.prototype._generatePointsArray = function () {
  18697. return this._sourceMesh._generatePointsArray();
  18698. };
  18699. // Clone
  18700. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18701. var result = this._sourceMesh.createInstance(name);
  18702. // Deep copy
  18703. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  18704. // Bounding info
  18705. this.refreshBoundingInfo();
  18706. // Parent
  18707. if (newParent) {
  18708. result.parent = newParent;
  18709. }
  18710. if (!doNotCloneChildren) {
  18711. // Children
  18712. for (var index = 0; index < this.getScene().meshes.length; index++) {
  18713. var mesh = this.getScene().meshes[index];
  18714. if (mesh.parent === this) {
  18715. mesh.clone(mesh.name, result);
  18716. }
  18717. }
  18718. }
  18719. result.computeWorldMatrix(true);
  18720. return result;
  18721. };
  18722. // Dispoe
  18723. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  18724. // Remove from mesh
  18725. var index = this._sourceMesh.instances.indexOf(this);
  18726. this._sourceMesh.instances.splice(index, 1);
  18727. _super.prototype.dispose.call(this, doNotRecurse);
  18728. };
  18729. return InstancedMesh;
  18730. })(BABYLON.AbstractMesh);
  18731. BABYLON.InstancedMesh = InstancedMesh;
  18732. })(BABYLON || (BABYLON = {}));
  18733. var BABYLON;
  18734. (function (BABYLON) {
  18735. var _InstancesBatch = (function () {
  18736. function _InstancesBatch() {
  18737. this.mustReturn = false;
  18738. this.visibleInstances = new Array();
  18739. this.renderSelf = new Array();
  18740. }
  18741. return _InstancesBatch;
  18742. })();
  18743. BABYLON._InstancesBatch = _InstancesBatch;
  18744. var Mesh = (function (_super) {
  18745. __extends(Mesh, _super);
  18746. /**
  18747. * @constructor
  18748. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  18749. * @param {Scene} scene The scene to add this mesh to.
  18750. * @param {Node} parent The parent of this mesh, if it has one
  18751. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  18752. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  18753. * When false, achieved by calling a clone(), also passing False.
  18754. * This will make creation of children, recursive.
  18755. */
  18756. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  18757. if (parent === void 0) { parent = null; }
  18758. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  18759. _super.call(this, name, scene);
  18760. // Events
  18761. /**
  18762. * An event triggered before rendering the mesh
  18763. * @type {BABYLON.Observable}
  18764. */
  18765. this.onBeforeRenderObservable = new BABYLON.Observable();
  18766. /**
  18767. * An event triggered after rendering the mesh
  18768. * @type {BABYLON.Observable}
  18769. */
  18770. this.onAfterRenderObservable = new BABYLON.Observable();
  18771. /**
  18772. * An event triggered before drawing the mesh
  18773. * @type {BABYLON.Observable}
  18774. */
  18775. this.onBeforeDrawObservable = new BABYLON.Observable();
  18776. // Members
  18777. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18778. this.instances = new Array();
  18779. this._LODLevels = new Array();
  18780. this._visibleInstances = {};
  18781. this._renderIdForInstances = new Array();
  18782. this._batchCache = new _InstancesBatch();
  18783. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  18784. this._sideOrientation = Mesh._DEFAULTSIDE;
  18785. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  18786. if (source) {
  18787. // Geometry
  18788. if (source._geometry) {
  18789. source._geometry.applyToMesh(this);
  18790. }
  18791. // Deep copy
  18792. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  18793. // Pivot
  18794. this.setPivotMatrix(source.getPivotMatrix());
  18795. this.id = name + "." + source.id;
  18796. // Material
  18797. this.material = source.material;
  18798. var index;
  18799. if (!doNotCloneChildren) {
  18800. // Children
  18801. for (index = 0; index < scene.meshes.length; index++) {
  18802. var mesh = scene.meshes[index];
  18803. if (mesh.parent === source) {
  18804. // doNotCloneChildren is always going to be False
  18805. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  18806. }
  18807. }
  18808. }
  18809. // Physics clone
  18810. var physicsEngine = this.getScene().getPhysicsEngine();
  18811. if (clonePhysicsImpostor && physicsEngine) {
  18812. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  18813. if (impostor) {
  18814. this.physicsImpostor = impostor.clone(this);
  18815. }
  18816. }
  18817. // Particles
  18818. for (index = 0; index < scene.particleSystems.length; index++) {
  18819. var system = scene.particleSystems[index];
  18820. if (system.emitter === source) {
  18821. system.clone(system.name, this);
  18822. }
  18823. }
  18824. this.computeWorldMatrix(true);
  18825. }
  18826. // Parent
  18827. if (parent !== null) {
  18828. this.parent = parent;
  18829. }
  18830. }
  18831. Object.defineProperty(Mesh, "FRONTSIDE", {
  18832. /**
  18833. * Mesh side orientation : usually the external or front surface
  18834. */
  18835. get: function () {
  18836. return Mesh._FRONTSIDE;
  18837. },
  18838. enumerable: true,
  18839. configurable: true
  18840. });
  18841. Object.defineProperty(Mesh, "BACKSIDE", {
  18842. /**
  18843. * Mesh side orientation : usually the internal or back surface
  18844. */
  18845. get: function () {
  18846. return Mesh._BACKSIDE;
  18847. },
  18848. enumerable: true,
  18849. configurable: true
  18850. });
  18851. Object.defineProperty(Mesh, "DOUBLESIDE", {
  18852. /**
  18853. * Mesh side orientation : both internal and external or front and back surfaces
  18854. */
  18855. get: function () {
  18856. return Mesh._DOUBLESIDE;
  18857. },
  18858. enumerable: true,
  18859. configurable: true
  18860. });
  18861. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  18862. /**
  18863. * Mesh side orientation : by default, `FRONTSIDE`
  18864. */
  18865. get: function () {
  18866. return Mesh._DEFAULTSIDE;
  18867. },
  18868. enumerable: true,
  18869. configurable: true
  18870. });
  18871. Object.defineProperty(Mesh, "NO_CAP", {
  18872. /**
  18873. * Mesh cap setting : no cap
  18874. */
  18875. get: function () {
  18876. return Mesh._NO_CAP;
  18877. },
  18878. enumerable: true,
  18879. configurable: true
  18880. });
  18881. Object.defineProperty(Mesh, "CAP_START", {
  18882. /**
  18883. * Mesh cap setting : one cap at the beginning of the mesh
  18884. */
  18885. get: function () {
  18886. return Mesh._CAP_START;
  18887. },
  18888. enumerable: true,
  18889. configurable: true
  18890. });
  18891. Object.defineProperty(Mesh, "CAP_END", {
  18892. /**
  18893. * Mesh cap setting : one cap at the end of the mesh
  18894. */
  18895. get: function () {
  18896. return Mesh._CAP_END;
  18897. },
  18898. enumerable: true,
  18899. configurable: true
  18900. });
  18901. Object.defineProperty(Mesh, "CAP_ALL", {
  18902. /**
  18903. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  18904. */
  18905. get: function () {
  18906. return Mesh._CAP_ALL;
  18907. },
  18908. enumerable: true,
  18909. configurable: true
  18910. });
  18911. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  18912. set: function (callback) {
  18913. if (this._onBeforeDrawObserver) {
  18914. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  18915. }
  18916. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  18917. },
  18918. enumerable: true,
  18919. configurable: true
  18920. });
  18921. // Methods
  18922. /**
  18923. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18924. */
  18925. Mesh.prototype.toString = function (fullDetails) {
  18926. var ret = _super.prototype.toString.call(this, fullDetails);
  18927. ret += ", n vertices: " + this.getTotalVertices();
  18928. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  18929. if (this.animations) {
  18930. for (var i = 0; i < this.animations.length; i++) {
  18931. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18932. }
  18933. }
  18934. if (fullDetails) {
  18935. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  18936. }
  18937. return ret;
  18938. };
  18939. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  18940. get: function () {
  18941. return this._LODLevels.length > 0;
  18942. },
  18943. enumerable: true,
  18944. configurable: true
  18945. });
  18946. Mesh.prototype._sortLODLevels = function () {
  18947. this._LODLevels.sort(function (a, b) {
  18948. if (a.distance < b.distance) {
  18949. return 1;
  18950. }
  18951. if (a.distance > b.distance) {
  18952. return -1;
  18953. }
  18954. return 0;
  18955. });
  18956. };
  18957. /**
  18958. * Add a mesh as LOD level triggered at the given distance.
  18959. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18960. * @param {number} distance The distance from the center of the object to show this level
  18961. * @param {Mesh} mesh The mesh to be added as LOD level
  18962. * @return {Mesh} This mesh (for chaining)
  18963. */
  18964. Mesh.prototype.addLODLevel = function (distance, mesh) {
  18965. if (mesh && mesh._masterMesh) {
  18966. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  18967. return this;
  18968. }
  18969. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  18970. this._LODLevels.push(level);
  18971. if (mesh) {
  18972. mesh._masterMesh = this;
  18973. }
  18974. this._sortLODLevels();
  18975. return this;
  18976. };
  18977. /**
  18978. * Returns the LOD level mesh at the passed distance or null if not found.
  18979. * It is related to the method `addLODLevel(distance, mesh)`.
  18980. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18981. */
  18982. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  18983. for (var index = 0; index < this._LODLevels.length; index++) {
  18984. var level = this._LODLevels[index];
  18985. if (level.distance === distance) {
  18986. return level.mesh;
  18987. }
  18988. }
  18989. return null;
  18990. };
  18991. /**
  18992. * Remove a mesh from the LOD array
  18993. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18994. * @param {Mesh} mesh The mesh to be removed.
  18995. * @return {Mesh} This mesh (for chaining)
  18996. */
  18997. Mesh.prototype.removeLODLevel = function (mesh) {
  18998. for (var index = 0; index < this._LODLevels.length; index++) {
  18999. if (this._LODLevels[index].mesh === mesh) {
  19000. this._LODLevels.splice(index, 1);
  19001. if (mesh) {
  19002. mesh._masterMesh = null;
  19003. }
  19004. }
  19005. }
  19006. this._sortLODLevels();
  19007. return this;
  19008. };
  19009. /**
  19010. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19011. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19012. */
  19013. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19014. if (!this._LODLevels || this._LODLevels.length === 0) {
  19015. return this;
  19016. }
  19017. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19018. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19019. if (this.onLODLevelSelection) {
  19020. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19021. }
  19022. return this;
  19023. }
  19024. for (var index = 0; index < this._LODLevels.length; index++) {
  19025. var level = this._LODLevels[index];
  19026. if (level.distance < distanceToCamera) {
  19027. if (level.mesh) {
  19028. level.mesh._preActivate();
  19029. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19030. }
  19031. if (this.onLODLevelSelection) {
  19032. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19033. }
  19034. return level.mesh;
  19035. }
  19036. }
  19037. if (this.onLODLevelSelection) {
  19038. this.onLODLevelSelection(distanceToCamera, this, this);
  19039. }
  19040. return this;
  19041. };
  19042. Object.defineProperty(Mesh.prototype, "geometry", {
  19043. /**
  19044. * Returns the mesh internal Geometry object.
  19045. */
  19046. get: function () {
  19047. return this._geometry;
  19048. },
  19049. enumerable: true,
  19050. configurable: true
  19051. });
  19052. /**
  19053. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19054. */
  19055. Mesh.prototype.getTotalVertices = function () {
  19056. if (!this._geometry) {
  19057. return 0;
  19058. }
  19059. return this._geometry.getTotalVertices();
  19060. };
  19061. /**
  19062. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19063. * 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.
  19064. * Returns null if the mesh has no geometry or no vertex buffer.
  19065. * Possible `kind` values :
  19066. * - BABYLON.VertexBuffer.PositionKind
  19067. * - BABYLON.VertexBuffer.UVKind
  19068. * - BABYLON.VertexBuffer.UV2Kind
  19069. * - BABYLON.VertexBuffer.UV3Kind
  19070. * - BABYLON.VertexBuffer.UV4Kind
  19071. * - BABYLON.VertexBuffer.UV5Kind
  19072. * - BABYLON.VertexBuffer.UV6Kind
  19073. * - BABYLON.VertexBuffer.ColorKind
  19074. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19075. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19076. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19077. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19078. */
  19079. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19080. if (!this._geometry) {
  19081. return null;
  19082. }
  19083. return this._geometry.getVerticesData(kind, copyWhenShared);
  19084. };
  19085. /**
  19086. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19087. * Returns `undefined` if the mesh has no geometry.
  19088. * Possible `kind` values :
  19089. * - BABYLON.VertexBuffer.PositionKind
  19090. * - BABYLON.VertexBuffer.UVKind
  19091. * - BABYLON.VertexBuffer.UV2Kind
  19092. * - BABYLON.VertexBuffer.UV3Kind
  19093. * - BABYLON.VertexBuffer.UV4Kind
  19094. * - BABYLON.VertexBuffer.UV5Kind
  19095. * - BABYLON.VertexBuffer.UV6Kind
  19096. * - BABYLON.VertexBuffer.ColorKind
  19097. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19098. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19099. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19100. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19101. */
  19102. Mesh.prototype.getVertexBuffer = function (kind) {
  19103. if (!this._geometry) {
  19104. return undefined;
  19105. }
  19106. return this._geometry.getVertexBuffer(kind);
  19107. };
  19108. /**
  19109. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19110. * Possible `kind` values :
  19111. * - BABYLON.VertexBuffer.PositionKind
  19112. * - BABYLON.VertexBuffer.UVKind
  19113. * - BABYLON.VertexBuffer.UV2Kind
  19114. * - BABYLON.VertexBuffer.UV3Kind
  19115. * - BABYLON.VertexBuffer.UV4Kind
  19116. * - BABYLON.VertexBuffer.UV5Kind
  19117. * - BABYLON.VertexBuffer.UV6Kind
  19118. * - BABYLON.VertexBuffer.ColorKind
  19119. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19120. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19121. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19122. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19123. */
  19124. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19125. if (!this._geometry) {
  19126. if (this._delayInfo) {
  19127. return this._delayInfo.indexOf(kind) !== -1;
  19128. }
  19129. return false;
  19130. }
  19131. return this._geometry.isVerticesDataPresent(kind);
  19132. };
  19133. /**
  19134. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  19135. * Possible `kind` values :
  19136. * - BABYLON.VertexBuffer.PositionKind
  19137. * - BABYLON.VertexBuffer.UVKind
  19138. * - BABYLON.VertexBuffer.UV2Kind
  19139. * - BABYLON.VertexBuffer.UV3Kind
  19140. * - BABYLON.VertexBuffer.UV4Kind
  19141. * - BABYLON.VertexBuffer.UV5Kind
  19142. * - BABYLON.VertexBuffer.UV6Kind
  19143. * - BABYLON.VertexBuffer.ColorKind
  19144. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19145. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19146. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19147. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19148. */
  19149. Mesh.prototype.getVerticesDataKinds = function () {
  19150. if (!this._geometry) {
  19151. var result = [];
  19152. if (this._delayInfo) {
  19153. for (var kind in this._delayInfo) {
  19154. result.push(kind);
  19155. }
  19156. }
  19157. return result;
  19158. }
  19159. return this._geometry.getVerticesDataKinds();
  19160. };
  19161. /**
  19162. * Returns a positive integer : the total number of indices in this mesh geometry.
  19163. * Returns zero if the mesh has no geometry.
  19164. */
  19165. Mesh.prototype.getTotalIndices = function () {
  19166. if (!this._geometry) {
  19167. return 0;
  19168. }
  19169. return this._geometry.getTotalIndices();
  19170. };
  19171. /**
  19172. * Returns an array of integers or a Int32Array populated with the mesh indices.
  19173. * 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.
  19174. * Returns an empty array if the mesh has no geometry.
  19175. */
  19176. Mesh.prototype.getIndices = function (copyWhenShared) {
  19177. if (!this._geometry) {
  19178. return [];
  19179. }
  19180. return this._geometry.getIndices(copyWhenShared);
  19181. };
  19182. Object.defineProperty(Mesh.prototype, "isBlocked", {
  19183. get: function () {
  19184. return this._masterMesh !== null && this._masterMesh !== undefined;
  19185. },
  19186. enumerable: true,
  19187. configurable: true
  19188. });
  19189. /**
  19190. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  19191. */
  19192. Mesh.prototype.isReady = function () {
  19193. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19194. return false;
  19195. }
  19196. return _super.prototype.isReady.call(this);
  19197. };
  19198. /**
  19199. * Boolean : true if the mesh has been disposed.
  19200. */
  19201. Mesh.prototype.isDisposed = function () {
  19202. return this._isDisposed;
  19203. };
  19204. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  19205. get: function () {
  19206. return this._sideOrientation;
  19207. },
  19208. /**
  19209. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  19210. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  19211. */
  19212. set: function (sideO) {
  19213. this._sideOrientation = sideO;
  19214. },
  19215. enumerable: true,
  19216. configurable: true
  19217. });
  19218. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  19219. /**
  19220. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  19221. * This property is pertinent only for updatable parametric shapes.
  19222. */
  19223. get: function () {
  19224. return this._areNormalsFrozen;
  19225. },
  19226. enumerable: true,
  19227. configurable: true
  19228. });
  19229. /**
  19230. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19231. * It has no effect at all on other shapes.
  19232. * It prevents the mesh normals from being recomputed on next `positions` array update.
  19233. */
  19234. Mesh.prototype.freezeNormals = function () {
  19235. this._areNormalsFrozen = true;
  19236. };
  19237. /**
  19238. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19239. * It has no effect at all on other shapes.
  19240. * It reactivates the mesh normals computation if it was previously frozen.
  19241. */
  19242. Mesh.prototype.unfreezeNormals = function () {
  19243. this._areNormalsFrozen = false;
  19244. };
  19245. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  19246. /**
  19247. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  19248. */
  19249. set: function (count) {
  19250. this._overridenInstanceCount = count;
  19251. },
  19252. enumerable: true,
  19253. configurable: true
  19254. });
  19255. // Methods
  19256. Mesh.prototype._preActivate = function () {
  19257. var sceneRenderId = this.getScene().getRenderId();
  19258. if (this._preActivateId === sceneRenderId) {
  19259. return;
  19260. }
  19261. this._preActivateId = sceneRenderId;
  19262. this._visibleInstances = null;
  19263. };
  19264. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19265. if (this._visibleInstances) {
  19266. this._visibleInstances.intermediateDefaultRenderId = renderId;
  19267. }
  19268. };
  19269. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  19270. if (!this._visibleInstances) {
  19271. this._visibleInstances = {};
  19272. this._visibleInstances.defaultRenderId = renderId;
  19273. this._visibleInstances.selfDefaultRenderId = this._renderId;
  19274. }
  19275. if (!this._visibleInstances[renderId]) {
  19276. this._visibleInstances[renderId] = new Array();
  19277. }
  19278. this._visibleInstances[renderId].push(instance);
  19279. };
  19280. /**
  19281. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  19282. * This means the mesh underlying bounding box and sphere are recomputed.
  19283. */
  19284. Mesh.prototype.refreshBoundingInfo = function () {
  19285. if (this._boundingInfo.isLocked) {
  19286. return;
  19287. }
  19288. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19289. if (data) {
  19290. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  19291. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19292. }
  19293. if (this.subMeshes) {
  19294. for (var index = 0; index < this.subMeshes.length; index++) {
  19295. this.subMeshes[index].refreshBoundingInfo();
  19296. }
  19297. }
  19298. this._updateBoundingInfo();
  19299. };
  19300. Mesh.prototype._createGlobalSubMesh = function () {
  19301. var totalVertices = this.getTotalVertices();
  19302. if (!totalVertices || !this.getIndices()) {
  19303. return null;
  19304. }
  19305. this.releaseSubMeshes();
  19306. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  19307. };
  19308. Mesh.prototype.subdivide = function (count) {
  19309. if (count < 1) {
  19310. return;
  19311. }
  19312. var totalIndices = this.getTotalIndices();
  19313. var subdivisionSize = (totalIndices / count) | 0;
  19314. var offset = 0;
  19315. // Ensure that subdivisionSize is a multiple of 3
  19316. while (subdivisionSize % 3 !== 0) {
  19317. subdivisionSize++;
  19318. }
  19319. this.releaseSubMeshes();
  19320. for (var index = 0; index < count; index++) {
  19321. if (offset >= totalIndices) {
  19322. break;
  19323. }
  19324. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  19325. offset += subdivisionSize;
  19326. }
  19327. this.synchronizeInstances();
  19328. };
  19329. /**
  19330. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19331. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19332. * The `data` are either a numeric array either a Float32Array.
  19333. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19334. * 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).
  19335. * Note that a new underlying VertexBuffer object is created each call.
  19336. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19337. *
  19338. * Possible `kind` values :
  19339. * - BABYLON.VertexBuffer.PositionKind
  19340. * - BABYLON.VertexBuffer.UVKind
  19341. * - BABYLON.VertexBuffer.UV2Kind
  19342. * - BABYLON.VertexBuffer.UV3Kind
  19343. * - BABYLON.VertexBuffer.UV4Kind
  19344. * - BABYLON.VertexBuffer.UV5Kind
  19345. * - BABYLON.VertexBuffer.UV6Kind
  19346. * - BABYLON.VertexBuffer.ColorKind
  19347. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19348. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19349. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19350. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19351. */
  19352. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19353. if (!this._geometry) {
  19354. var vertexData = new BABYLON.VertexData();
  19355. vertexData.set(data, kind);
  19356. var scene = this.getScene();
  19357. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  19358. }
  19359. else {
  19360. this._geometry.setVerticesData(kind, data, updatable, stride);
  19361. }
  19362. };
  19363. Mesh.prototype.setVerticesBuffer = function (buffer) {
  19364. if (!this._geometry) {
  19365. var scene = this.getScene();
  19366. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  19367. }
  19368. this._geometry.setVerticesBuffer(buffer);
  19369. };
  19370. /**
  19371. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19372. * If the mesh has no geometry, it is simply returned as it is.
  19373. * The `data` are either a numeric array either a Float32Array.
  19374. * No new underlying VertexBuffer object is created.
  19375. * 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.
  19376. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19377. *
  19378. * Possible `kind` values :
  19379. * - BABYLON.VertexBuffer.PositionKind
  19380. * - BABYLON.VertexBuffer.UVKind
  19381. * - BABYLON.VertexBuffer.UV2Kind
  19382. * - BABYLON.VertexBuffer.UV3Kind
  19383. * - BABYLON.VertexBuffer.UV4Kind
  19384. * - BABYLON.VertexBuffer.UV5Kind
  19385. * - BABYLON.VertexBuffer.UV6Kind
  19386. * - BABYLON.VertexBuffer.ColorKind
  19387. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19388. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19389. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19390. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19391. */
  19392. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19393. if (!this._geometry) {
  19394. return;
  19395. }
  19396. if (!makeItUnique) {
  19397. this._geometry.updateVerticesData(kind, data, updateExtends);
  19398. }
  19399. else {
  19400. this.makeGeometryUnique();
  19401. this.updateVerticesData(kind, data, updateExtends, false);
  19402. }
  19403. };
  19404. /**
  19405. * Deprecated since BabylonJS v2.3
  19406. */
  19407. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  19408. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  19409. if (!this._geometry) {
  19410. return;
  19411. }
  19412. if (!makeItUnique) {
  19413. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  19414. }
  19415. else {
  19416. this.makeGeometryUnique();
  19417. this.updateVerticesDataDirectly(kind, data, offset, false);
  19418. }
  19419. };
  19420. /**
  19421. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  19422. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  19423. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  19424. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  19425. */
  19426. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  19427. if (computeNormals === void 0) { computeNormals = true; }
  19428. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19429. positionFunction(positions);
  19430. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19431. if (computeNormals) {
  19432. var indices = this.getIndices();
  19433. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19434. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19435. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19436. }
  19437. };
  19438. Mesh.prototype.makeGeometryUnique = function () {
  19439. if (!this._geometry) {
  19440. return;
  19441. }
  19442. var oldGeometry = this._geometry;
  19443. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  19444. oldGeometry.releaseForMesh(this, true);
  19445. geometry.applyToMesh(this);
  19446. };
  19447. /**
  19448. * Sets the mesh indices.
  19449. * Expects an array populated with integers or a Int32Array.
  19450. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19451. * This method creates a new index buffer each call.
  19452. */
  19453. Mesh.prototype.setIndices = function (indices, totalVertices) {
  19454. if (!this._geometry) {
  19455. var vertexData = new BABYLON.VertexData();
  19456. vertexData.indices = indices;
  19457. var scene = this.getScene();
  19458. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  19459. }
  19460. else {
  19461. this._geometry.setIndices(indices, totalVertices);
  19462. }
  19463. };
  19464. /**
  19465. * Invert the geometry to move from a right handed system to a left handed one.
  19466. */
  19467. Mesh.prototype.toLeftHanded = function () {
  19468. if (!this._geometry) {
  19469. return;
  19470. }
  19471. this._geometry.toLeftHanded();
  19472. };
  19473. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  19474. var engine = this.getScene().getEngine();
  19475. // Wireframe
  19476. var indexToBind;
  19477. if (this._unIndexed) {
  19478. indexToBind = null;
  19479. }
  19480. else {
  19481. switch (fillMode) {
  19482. case BABYLON.Material.PointFillMode:
  19483. indexToBind = null;
  19484. break;
  19485. case BABYLON.Material.WireFrameFillMode:
  19486. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  19487. break;
  19488. default:
  19489. case BABYLON.Material.TriangleFillMode:
  19490. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  19491. break;
  19492. }
  19493. }
  19494. // VBOs
  19495. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  19496. };
  19497. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  19498. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19499. return;
  19500. }
  19501. this.onBeforeDrawObservable.notifyObservers(this);
  19502. var engine = this.getScene().getEngine();
  19503. // Draw order
  19504. switch (fillMode) {
  19505. case BABYLON.Material.PointFillMode:
  19506. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19507. break;
  19508. case BABYLON.Material.WireFrameFillMode:
  19509. if (this._unIndexed) {
  19510. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19511. }
  19512. else {
  19513. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  19514. }
  19515. break;
  19516. default:
  19517. if (this._unIndexed) {
  19518. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19519. }
  19520. else {
  19521. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  19522. }
  19523. }
  19524. };
  19525. /**
  19526. * Registers for this mesh a javascript function called just before the rendering process.
  19527. * This function is passed the current mesh and doesn't return anything.
  19528. */
  19529. Mesh.prototype.registerBeforeRender = function (func) {
  19530. this.onBeforeRenderObservable.add(func);
  19531. };
  19532. /**
  19533. * Disposes a previously registered javascript function called before the rendering.
  19534. * This function is passed the current mesh and doesn't return anything.
  19535. */
  19536. Mesh.prototype.unregisterBeforeRender = function (func) {
  19537. this.onBeforeRenderObservable.removeCallback(func);
  19538. };
  19539. /**
  19540. * Registers for this mesh a javascript function called just after the rendering is complete.
  19541. * This function is passed the current mesh and doesn't return anything.
  19542. */
  19543. Mesh.prototype.registerAfterRender = function (func) {
  19544. this.onAfterRenderObservable.add(func);
  19545. };
  19546. /**
  19547. * Disposes a previously registered javascript function called after the rendering.
  19548. * This function is passed the current mesh and doesn't return anything.
  19549. */
  19550. Mesh.prototype.unregisterAfterRender = function (func) {
  19551. this.onAfterRenderObservable.removeCallback(func);
  19552. };
  19553. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  19554. var scene = this.getScene();
  19555. this._batchCache.mustReturn = false;
  19556. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  19557. this._batchCache.visibleInstances[subMeshId] = null;
  19558. if (this._visibleInstances) {
  19559. var currentRenderId = scene.getRenderId();
  19560. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  19561. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  19562. var selfRenderId = this._renderId;
  19563. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  19564. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  19565. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  19566. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  19567. }
  19568. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  19569. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  19570. this._batchCache.mustReturn = true;
  19571. return this._batchCache;
  19572. }
  19573. if (currentRenderId !== selfRenderId) {
  19574. this._batchCache.renderSelf[subMeshId] = false;
  19575. }
  19576. }
  19577. this._renderIdForInstances[subMeshId] = currentRenderId;
  19578. }
  19579. return this._batchCache;
  19580. };
  19581. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  19582. var visibleInstances = batch.visibleInstances[subMesh._id];
  19583. var matricesCount = visibleInstances.length + 1;
  19584. var bufferSize = matricesCount * 16 * 4;
  19585. var currentInstancesBufferSize = this._instancesBufferSize;
  19586. var instancesBuffer = this._instancesBuffer;
  19587. while (this._instancesBufferSize < bufferSize) {
  19588. this._instancesBufferSize *= 2;
  19589. }
  19590. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  19591. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  19592. }
  19593. var offset = 0;
  19594. var instancesCount = 0;
  19595. var world = this.getWorldMatrix();
  19596. if (batch.renderSelf[subMesh._id]) {
  19597. world.copyToArray(this._instancesData, offset);
  19598. offset += 16;
  19599. instancesCount++;
  19600. }
  19601. if (visibleInstances) {
  19602. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  19603. var instance = visibleInstances[instanceIndex];
  19604. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  19605. offset += 16;
  19606. instancesCount++;
  19607. }
  19608. }
  19609. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  19610. if (instancesBuffer) {
  19611. instancesBuffer.dispose();
  19612. }
  19613. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  19614. this._instancesBuffer = instancesBuffer;
  19615. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  19616. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  19617. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  19618. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  19619. }
  19620. else {
  19621. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  19622. }
  19623. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  19624. this._draw(subMesh, fillMode, instancesCount);
  19625. engine.unbindInstanceAttributes();
  19626. };
  19627. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  19628. var scene = this.getScene();
  19629. var engine = scene.getEngine();
  19630. if (hardwareInstancedRendering) {
  19631. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  19632. }
  19633. else {
  19634. if (batch.renderSelf[subMesh._id]) {
  19635. // Draw
  19636. if (onBeforeDraw) {
  19637. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  19638. }
  19639. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  19640. }
  19641. if (batch.visibleInstances[subMesh._id]) {
  19642. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  19643. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  19644. // World
  19645. var world = instance.getWorldMatrix();
  19646. if (onBeforeDraw) {
  19647. onBeforeDraw(true, world, effectiveMaterial);
  19648. }
  19649. // Draw
  19650. this._draw(subMesh, fillMode);
  19651. }
  19652. }
  19653. }
  19654. };
  19655. /**
  19656. * Triggers the draw call for the mesh.
  19657. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  19658. */
  19659. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  19660. var scene = this.getScene();
  19661. // Managing instances
  19662. var batch = this._getInstancesRenderList(subMesh._id);
  19663. if (batch.mustReturn) {
  19664. return;
  19665. }
  19666. // Checking geometry state
  19667. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19668. return;
  19669. }
  19670. var callbackIndex;
  19671. this.onBeforeRenderObservable.notifyObservers(this);
  19672. var engine = scene.getEngine();
  19673. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  19674. // Material
  19675. var effectiveMaterial = subMesh.getMaterial();
  19676. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  19677. return;
  19678. }
  19679. // Outline - step 1
  19680. var savedDepthWrite = engine.getDepthWrite();
  19681. if (this.renderOutline) {
  19682. engine.setDepthWrite(false);
  19683. scene.getOutlineRenderer().render(subMesh, batch);
  19684. engine.setDepthWrite(savedDepthWrite);
  19685. }
  19686. effectiveMaterial._preBind();
  19687. var effect = effectiveMaterial.getEffect();
  19688. // Bind
  19689. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  19690. this._bind(subMesh, effect, fillMode);
  19691. var world = this.getWorldMatrix();
  19692. effectiveMaterial.bind(world, this);
  19693. // Alpha mode
  19694. if (enableAlphaMode) {
  19695. engine.setAlphaMode(effectiveMaterial.alphaMode);
  19696. }
  19697. // Draw
  19698. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw);
  19699. // Unbind
  19700. effectiveMaterial.unbind();
  19701. // Outline - step 2
  19702. if (this.renderOutline && savedDepthWrite) {
  19703. engine.setDepthWrite(true);
  19704. engine.setColorWrite(false);
  19705. scene.getOutlineRenderer().render(subMesh, batch);
  19706. engine.setColorWrite(true);
  19707. }
  19708. // Overlay
  19709. if (this.renderOverlay) {
  19710. var currentMode = engine.getAlphaMode();
  19711. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19712. scene.getOutlineRenderer().render(subMesh, batch, true);
  19713. engine.setAlphaMode(currentMode);
  19714. }
  19715. this.onAfterRenderObservable.notifyObservers(this);
  19716. };
  19717. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  19718. if (isInstance) {
  19719. effectiveMaterial.bindOnlyWorldMatrix(world);
  19720. }
  19721. };
  19722. /**
  19723. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  19724. */
  19725. Mesh.prototype.getEmittedParticleSystems = function () {
  19726. var results = new Array();
  19727. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19728. var particleSystem = this.getScene().particleSystems[index];
  19729. if (particleSystem.emitter === this) {
  19730. results.push(particleSystem);
  19731. }
  19732. }
  19733. return results;
  19734. };
  19735. /**
  19736. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  19737. */
  19738. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  19739. var results = new Array();
  19740. var descendants = this.getDescendants();
  19741. descendants.push(this);
  19742. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19743. var particleSystem = this.getScene().particleSystems[index];
  19744. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  19745. results.push(particleSystem);
  19746. }
  19747. }
  19748. return results;
  19749. };
  19750. Mesh.prototype._checkDelayState = function () {
  19751. var scene = this.getScene();
  19752. if (this._geometry) {
  19753. this._geometry.load(scene);
  19754. }
  19755. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19756. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  19757. this._queueLoad(this, scene);
  19758. }
  19759. };
  19760. Mesh.prototype._queueLoad = function (mesh, scene) {
  19761. var _this = this;
  19762. scene._addPendingData(mesh);
  19763. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  19764. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  19765. if (data instanceof ArrayBuffer) {
  19766. _this._delayLoadingFunction(data, _this);
  19767. }
  19768. else {
  19769. _this._delayLoadingFunction(JSON.parse(data), _this);
  19770. }
  19771. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19772. scene._removePendingData(_this);
  19773. }, function () { }, scene.database, getBinaryData);
  19774. };
  19775. /**
  19776. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  19777. */
  19778. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  19779. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19780. return false;
  19781. }
  19782. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  19783. return false;
  19784. }
  19785. this._checkDelayState();
  19786. return true;
  19787. };
  19788. /**
  19789. * Sets the mesh material by the material or multiMaterial `id` property.
  19790. * The material `id` is a string identifying the material or the multiMaterial.
  19791. * This method returns nothing.
  19792. */
  19793. Mesh.prototype.setMaterialByID = function (id) {
  19794. var materials = this.getScene().materials;
  19795. var index;
  19796. for (index = 0; index < materials.length; index++) {
  19797. if (materials[index].id === id) {
  19798. this.material = materials[index];
  19799. return;
  19800. }
  19801. }
  19802. // Multi
  19803. var multiMaterials = this.getScene().multiMaterials;
  19804. for (index = 0; index < multiMaterials.length; index++) {
  19805. if (multiMaterials[index].id === id) {
  19806. this.material = multiMaterials[index];
  19807. return;
  19808. }
  19809. }
  19810. };
  19811. /**
  19812. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  19813. */
  19814. Mesh.prototype.getAnimatables = function () {
  19815. var results = [];
  19816. if (this.material) {
  19817. results.push(this.material);
  19818. }
  19819. if (this.skeleton) {
  19820. results.push(this.skeleton);
  19821. }
  19822. return results;
  19823. };
  19824. /**
  19825. * Modifies the mesh geometry according to the passed transformation matrix.
  19826. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  19827. * The mesh normals are modified accordingly the same transformation.
  19828. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19829. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19830. */
  19831. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  19832. // Position
  19833. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19834. return;
  19835. }
  19836. var submeshes = this.subMeshes.splice(0);
  19837. this._resetPointsArrayCache();
  19838. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19839. var temp = [];
  19840. var index;
  19841. for (index = 0; index < data.length; index += 3) {
  19842. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  19843. }
  19844. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  19845. // Normals
  19846. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19847. return;
  19848. }
  19849. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19850. temp = [];
  19851. for (index = 0; index < data.length; index += 3) {
  19852. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  19853. }
  19854. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  19855. // flip faces?
  19856. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  19857. this.flipFaces();
  19858. }
  19859. // Restore submeshes
  19860. this.releaseSubMeshes();
  19861. this.subMeshes = submeshes;
  19862. };
  19863. /**
  19864. * Modifies the mesh geometry according to its own current World Matrix.
  19865. * The mesh World Matrix is then reset.
  19866. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  19867. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19868. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19869. */
  19870. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  19871. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  19872. this.scaling.copyFromFloats(1, 1, 1);
  19873. this.position.copyFromFloats(0, 0, 0);
  19874. this.rotation.copyFromFloats(0, 0, 0);
  19875. //only if quaternion is already set
  19876. if (this.rotationQuaternion) {
  19877. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  19878. }
  19879. this._worldMatrix = BABYLON.Matrix.Identity();
  19880. };
  19881. // Cache
  19882. Mesh.prototype._resetPointsArrayCache = function () {
  19883. this._positions = null;
  19884. };
  19885. Mesh.prototype._generatePointsArray = function () {
  19886. if (this._positions)
  19887. return true;
  19888. this._positions = [];
  19889. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19890. if (!data) {
  19891. return false;
  19892. }
  19893. for (var index = 0; index < data.length; index += 3) {
  19894. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  19895. }
  19896. return true;
  19897. };
  19898. /**
  19899. * Returns a new Mesh object generated from the current mesh properties.
  19900. * This method must not get confused with createInstance().
  19901. * The parameter `name` is a string, the name given to the new mesh.
  19902. * The optional parameter `newParent` can be any Node object (default `null`).
  19903. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  19904. * 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.
  19905. */
  19906. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  19907. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19908. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  19909. };
  19910. /**
  19911. * Disposes the mesh.
  19912. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  19913. */
  19914. Mesh.prototype.dispose = function (doNotRecurse) {
  19915. if (this._geometry) {
  19916. this._geometry.releaseForMesh(this, true);
  19917. }
  19918. // Instances
  19919. if (this._instancesBuffer) {
  19920. this._instancesBuffer.dispose();
  19921. this._instancesBuffer = null;
  19922. }
  19923. while (this.instances.length) {
  19924. this.instances[0].dispose();
  19925. }
  19926. _super.prototype.dispose.call(this, doNotRecurse);
  19927. };
  19928. /**
  19929. * Modifies the mesh geometry according to a displacement map.
  19930. * 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.
  19931. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19932. * This method returns nothing.
  19933. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  19934. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19935. * 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.
  19936. */
  19937. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  19938. var _this = this;
  19939. var scene = this.getScene();
  19940. var onload = function (img) {
  19941. // Getting height map data
  19942. var canvas = document.createElement("canvas");
  19943. var context = canvas.getContext("2d");
  19944. var heightMapWidth = img.width;
  19945. var heightMapHeight = img.height;
  19946. canvas.width = heightMapWidth;
  19947. canvas.height = heightMapHeight;
  19948. context.drawImage(img, 0, 0);
  19949. // Create VertexData from map data
  19950. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  19951. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  19952. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  19953. //execute success callback, if set
  19954. if (onSuccess) {
  19955. onSuccess(_this);
  19956. }
  19957. };
  19958. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  19959. };
  19960. /**
  19961. * Modifies the mesh geometry according to a displacementMap buffer.
  19962. * 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.
  19963. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19964. * This method returns nothing.
  19965. * 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.
  19966. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  19967. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19968. */
  19969. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  19970. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  19971. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  19972. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19973. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  19974. return;
  19975. }
  19976. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19977. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19978. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19979. var position = BABYLON.Vector3.Zero();
  19980. var normal = BABYLON.Vector3.Zero();
  19981. var uv = BABYLON.Vector2.Zero();
  19982. for (var index = 0; index < positions.length; index += 3) {
  19983. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  19984. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  19985. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  19986. // Compute height
  19987. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  19988. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  19989. var pos = (u + v * heightMapWidth) * 4;
  19990. var r = buffer[pos] / 255.0;
  19991. var g = buffer[pos + 1] / 255.0;
  19992. var b = buffer[pos + 2] / 255.0;
  19993. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  19994. normal.normalize();
  19995. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  19996. position = position.add(normal);
  19997. position.toArray(positions, index);
  19998. }
  19999. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20000. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20001. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20002. };
  20003. /**
  20004. * Modify the mesh to get a flat shading rendering.
  20005. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20006. * This method returns nothing.
  20007. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20008. */
  20009. Mesh.prototype.convertToFlatShadedMesh = function () {
  20010. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20011. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20012. var kinds = this.getVerticesDataKinds();
  20013. var vbs = [];
  20014. var data = [];
  20015. var newdata = [];
  20016. var updatableNormals = false;
  20017. var kindIndex;
  20018. var kind;
  20019. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20020. kind = kinds[kindIndex];
  20021. var vertexBuffer = this.getVertexBuffer(kind);
  20022. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20023. updatableNormals = vertexBuffer.isUpdatable();
  20024. kinds.splice(kindIndex, 1);
  20025. kindIndex--;
  20026. continue;
  20027. }
  20028. vbs[kind] = vertexBuffer;
  20029. data[kind] = vbs[kind].getData();
  20030. newdata[kind] = [];
  20031. }
  20032. // Save previous submeshes
  20033. var previousSubmeshes = this.subMeshes.slice(0);
  20034. var indices = this.getIndices();
  20035. var totalIndices = this.getTotalIndices();
  20036. // Generating unique vertices per face
  20037. var index;
  20038. for (index = 0; index < totalIndices; index++) {
  20039. var vertexIndex = indices[index];
  20040. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20041. kind = kinds[kindIndex];
  20042. var stride = vbs[kind].getStrideSize();
  20043. for (var offset = 0; offset < stride; offset++) {
  20044. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20045. }
  20046. }
  20047. }
  20048. // Updating faces & normal
  20049. var normals = [];
  20050. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20051. for (index = 0; index < totalIndices; index += 3) {
  20052. indices[index] = index;
  20053. indices[index + 1] = index + 1;
  20054. indices[index + 2] = index + 2;
  20055. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20056. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20057. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20058. var p1p2 = p1.subtract(p2);
  20059. var p3p2 = p3.subtract(p2);
  20060. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20061. // Store same normals for every vertex
  20062. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20063. normals.push(normal.x);
  20064. normals.push(normal.y);
  20065. normals.push(normal.z);
  20066. }
  20067. }
  20068. this.setIndices(indices);
  20069. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  20070. // Updating vertex buffers
  20071. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20072. kind = kinds[kindIndex];
  20073. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20074. }
  20075. // Updating submeshes
  20076. this.releaseSubMeshes();
  20077. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20078. var previousOne = previousSubmeshes[submeshIndex];
  20079. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20080. }
  20081. this.synchronizeInstances();
  20082. };
  20083. /**
  20084. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  20085. * In other words, more vertices, no more indices and a single bigger VBO.
  20086. * This method returns nothing.
  20087. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  20088. *
  20089. */
  20090. Mesh.prototype.convertToUnIndexedMesh = function () {
  20091. /// <summary>Remove indices by unfolding faces into buffers</summary>
  20092. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20093. var kinds = this.getVerticesDataKinds();
  20094. var vbs = [];
  20095. var data = [];
  20096. var newdata = [];
  20097. var updatableNormals = false;
  20098. var kindIndex;
  20099. var kind;
  20100. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20101. kind = kinds[kindIndex];
  20102. var vertexBuffer = this.getVertexBuffer(kind);
  20103. vbs[kind] = vertexBuffer;
  20104. data[kind] = vbs[kind].getData();
  20105. newdata[kind] = [];
  20106. }
  20107. // Save previous submeshes
  20108. var previousSubmeshes = this.subMeshes.slice(0);
  20109. var indices = this.getIndices();
  20110. var totalIndices = this.getTotalIndices();
  20111. // Generating unique vertices per face
  20112. var index;
  20113. for (index = 0; index < totalIndices; index++) {
  20114. var vertexIndex = indices[index];
  20115. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20116. kind = kinds[kindIndex];
  20117. var stride = vbs[kind].getStrideSize();
  20118. for (var offset = 0; offset < stride; offset++) {
  20119. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20120. }
  20121. }
  20122. }
  20123. // Updating indices
  20124. for (index = 0; index < totalIndices; index += 3) {
  20125. indices[index] = index;
  20126. indices[index + 1] = index + 1;
  20127. indices[index + 2] = index + 2;
  20128. }
  20129. this.setIndices(indices);
  20130. // Updating vertex buffers
  20131. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20132. kind = kinds[kindIndex];
  20133. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20134. }
  20135. // Updating submeshes
  20136. this.releaseSubMeshes();
  20137. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20138. var previousOne = previousSubmeshes[submeshIndex];
  20139. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20140. }
  20141. this._unIndexed = true;
  20142. this.synchronizeInstances();
  20143. };
  20144. /**
  20145. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  20146. * This method returns nothing.
  20147. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  20148. */
  20149. Mesh.prototype.flipFaces = function (flipNormals) {
  20150. if (flipNormals === void 0) { flipNormals = false; }
  20151. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  20152. var i;
  20153. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20154. for (i = 0; i < vertex_data.normals.length; i++) {
  20155. vertex_data.normals[i] *= -1;
  20156. }
  20157. }
  20158. var temp;
  20159. for (i = 0; i < vertex_data.indices.length; i += 3) {
  20160. // reassign indices
  20161. temp = vertex_data.indices[i + 1];
  20162. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  20163. vertex_data.indices[i + 2] = temp;
  20164. }
  20165. vertex_data.applyToMesh(this);
  20166. };
  20167. // Instances
  20168. /**
  20169. * Creates a new InstancedMesh object from the mesh model.
  20170. * An instance shares the same properties and the same material than its model.
  20171. * Only these properties of each instance can then be set individually :
  20172. * - position
  20173. * - rotation
  20174. * - rotationQuaternion
  20175. * - setPivotMatrix
  20176. * - scaling
  20177. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  20178. * Warning : this method is not supported for Line mesh and LineSystem
  20179. */
  20180. Mesh.prototype.createInstance = function (name) {
  20181. return new BABYLON.InstancedMesh(name, this);
  20182. };
  20183. /**
  20184. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  20185. * After this call, all the mesh instances have the same submeshes than the current mesh.
  20186. * This method returns nothing.
  20187. */
  20188. Mesh.prototype.synchronizeInstances = function () {
  20189. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  20190. var instance = this.instances[instanceIndex];
  20191. instance._syncSubMeshes();
  20192. }
  20193. };
  20194. /**
  20195. * Simplify the mesh according to the given array of settings.
  20196. * Function will return immediately and will simplify async. It returns nothing.
  20197. * @param settings a collection of simplification settings.
  20198. * @param parallelProcessing should all levels calculate parallel or one after the other.
  20199. * @param type the type of simplification to run.
  20200. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  20201. */
  20202. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  20203. if (parallelProcessing === void 0) { parallelProcessing = true; }
  20204. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  20205. this.getScene().simplificationQueue.addTask({
  20206. settings: settings,
  20207. parallelProcessing: parallelProcessing,
  20208. mesh: this,
  20209. simplificationType: simplificationType,
  20210. successCallback: successCallback
  20211. });
  20212. };
  20213. /**
  20214. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  20215. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  20216. * This should be used together with the simplification to avoid disappearing triangles.
  20217. * @param successCallback an optional success callback to be called after the optimization finished.
  20218. */
  20219. Mesh.prototype.optimizeIndices = function (successCallback) {
  20220. var _this = this;
  20221. var indices = this.getIndices();
  20222. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20223. var vectorPositions = [];
  20224. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  20225. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  20226. }
  20227. var dupes = [];
  20228. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  20229. var realPos = vectorPositions.length - 1 - iteration;
  20230. var testedPosition = vectorPositions[realPos];
  20231. for (var j = 0; j < realPos; ++j) {
  20232. var againstPosition = vectorPositions[j];
  20233. if (testedPosition.equals(againstPosition)) {
  20234. dupes[realPos] = j;
  20235. break;
  20236. }
  20237. }
  20238. }, function () {
  20239. for (var i = 0; i < indices.length; ++i) {
  20240. indices[i] = dupes[indices[i]] || indices[i];
  20241. }
  20242. //indices are now reordered
  20243. var originalSubMeshes = _this.subMeshes.slice(0);
  20244. _this.setIndices(indices);
  20245. _this.subMeshes = originalSubMeshes;
  20246. if (successCallback) {
  20247. successCallback(_this);
  20248. }
  20249. });
  20250. };
  20251. // Statics
  20252. /**
  20253. * Returns a new Mesh object what is a deep copy of the passed mesh.
  20254. * The parameter `parsedMesh` is the mesh to be copied.
  20255. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20256. */
  20257. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  20258. var mesh = new Mesh(parsedMesh.name, scene);
  20259. mesh.id = parsedMesh.id;
  20260. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20261. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20262. if (parsedMesh.rotationQuaternion) {
  20263. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20264. }
  20265. else if (parsedMesh.rotation) {
  20266. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20267. }
  20268. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20269. if (parsedMesh.localMatrix) {
  20270. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20271. }
  20272. else if (parsedMesh.pivotMatrix) {
  20273. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20274. }
  20275. mesh.setEnabled(parsedMesh.isEnabled);
  20276. mesh.isVisible = parsedMesh.isVisible;
  20277. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20278. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20279. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20280. if (parsedMesh.applyFog !== undefined) {
  20281. mesh.applyFog = parsedMesh.applyFog;
  20282. }
  20283. if (parsedMesh.pickable !== undefined) {
  20284. mesh.isPickable = parsedMesh.pickable;
  20285. }
  20286. if (parsedMesh.alphaIndex !== undefined) {
  20287. mesh.alphaIndex = parsedMesh.alphaIndex;
  20288. }
  20289. mesh.receiveShadows = parsedMesh.receiveShadows;
  20290. mesh.billboardMode = parsedMesh.billboardMode;
  20291. if (parsedMesh.visibility !== undefined) {
  20292. mesh.visibility = parsedMesh.visibility;
  20293. }
  20294. mesh.checkCollisions = parsedMesh.checkCollisions;
  20295. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20296. // freezeWorldMatrix
  20297. if (parsedMesh.freezeWorldMatrix) {
  20298. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20299. }
  20300. // Parent
  20301. if (parsedMesh.parentId) {
  20302. mesh._waitingParentId = parsedMesh.parentId;
  20303. }
  20304. // Actions
  20305. if (parsedMesh.actions !== undefined) {
  20306. mesh._waitingActions = parsedMesh.actions;
  20307. }
  20308. // Geometry
  20309. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20310. if (parsedMesh.delayLoadingFile) {
  20311. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20312. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20313. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20314. if (parsedMesh._binaryInfo) {
  20315. mesh._binaryInfo = parsedMesh._binaryInfo;
  20316. }
  20317. mesh._delayInfo = [];
  20318. if (parsedMesh.hasUVs) {
  20319. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20320. }
  20321. if (parsedMesh.hasUVs2) {
  20322. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20323. }
  20324. if (parsedMesh.hasUVs3) {
  20325. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20326. }
  20327. if (parsedMesh.hasUVs4) {
  20328. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20329. }
  20330. if (parsedMesh.hasUVs5) {
  20331. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20332. }
  20333. if (parsedMesh.hasUVs6) {
  20334. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20335. }
  20336. if (parsedMesh.hasColors) {
  20337. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20338. }
  20339. if (parsedMesh.hasMatricesIndices) {
  20340. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20341. }
  20342. if (parsedMesh.hasMatricesWeights) {
  20343. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20344. }
  20345. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  20346. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20347. mesh._checkDelayState();
  20348. }
  20349. }
  20350. else {
  20351. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  20352. }
  20353. // Material
  20354. if (parsedMesh.materialId) {
  20355. mesh.setMaterialByID(parsedMesh.materialId);
  20356. }
  20357. else {
  20358. mesh.material = null;
  20359. }
  20360. // Skeleton
  20361. if (parsedMesh.skeletonId > -1) {
  20362. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20363. if (parsedMesh.numBoneInfluencers) {
  20364. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  20365. }
  20366. }
  20367. // Animations
  20368. if (parsedMesh.animations) {
  20369. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20370. var parsedAnimation = parsedMesh.animations[animationIndex];
  20371. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20372. }
  20373. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  20374. }
  20375. if (parsedMesh.autoAnimate) {
  20376. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  20377. }
  20378. // Layer Mask
  20379. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20380. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20381. }
  20382. else {
  20383. mesh.layerMask = 0x0FFFFFFF;
  20384. }
  20385. //(Deprecated) physics
  20386. if (parsedMesh.physicsImpostor) {
  20387. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  20388. mass: parsedMesh.physicsMass,
  20389. friction: parsedMesh.physicsFriction,
  20390. restitution: parsedMesh.physicsRestitution
  20391. }, scene);
  20392. }
  20393. // Instances
  20394. if (parsedMesh.instances) {
  20395. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20396. var parsedInstance = parsedMesh.instances[index];
  20397. var instance = mesh.createInstance(parsedInstance.name);
  20398. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20399. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20400. if (parsedInstance.parentId) {
  20401. instance._waitingParentId = parsedInstance.parentId;
  20402. }
  20403. if (parsedInstance.rotationQuaternion) {
  20404. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20405. }
  20406. else if (parsedInstance.rotation) {
  20407. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20408. }
  20409. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20410. instance.checkCollisions = mesh.checkCollisions;
  20411. if (parsedMesh.animations) {
  20412. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20413. parsedAnimation = parsedMesh.animations[animationIndex];
  20414. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20415. }
  20416. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  20417. }
  20418. }
  20419. }
  20420. return mesh;
  20421. };
  20422. /**
  20423. * Creates a ribbon mesh.
  20424. * Please consider using the same method from the MeshBuilder class instead.
  20425. * 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.
  20426. *
  20427. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20428. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20429. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20430. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20431. * 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.
  20432. * 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.
  20433. * 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
  20434. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20435. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20436. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20437. */
  20438. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  20439. return BABYLON.MeshBuilder.CreateRibbon(name, {
  20440. pathArray: pathArray,
  20441. closeArray: closeArray,
  20442. closePath: closePath,
  20443. offset: offset,
  20444. updatable: updatable,
  20445. sideOrientation: sideOrientation,
  20446. instance: instance
  20447. }, scene);
  20448. };
  20449. /**
  20450. * Creates a plane polygonal mesh. By default, this is a disc.
  20451. * Please consider using the same method from the MeshBuilder class instead.
  20452. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20453. * 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.
  20454. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20455. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20456. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20457. */
  20458. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  20459. var options = {
  20460. radius: radius,
  20461. tessellation: tessellation,
  20462. sideOrientation: sideOrientation,
  20463. updatable: updatable
  20464. };
  20465. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  20466. };
  20467. /**
  20468. * Creates a box mesh.
  20469. * Please consider using the same method from the MeshBuilder class instead.
  20470. * The parameter `size` sets the size (float) of each box side (default 1).
  20471. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20472. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20473. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20474. */
  20475. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  20476. var options = {
  20477. size: size,
  20478. sideOrientation: sideOrientation,
  20479. updatable: updatable
  20480. };
  20481. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  20482. };
  20483. /**
  20484. * Creates a sphere mesh.
  20485. * Please consider using the same method from the MeshBuilder class instead.
  20486. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20487. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20488. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20489. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20490. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20491. */
  20492. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  20493. var options = {
  20494. segments: segments,
  20495. diameterX: diameter,
  20496. diameterY: diameter,
  20497. diameterZ: diameter,
  20498. sideOrientation: sideOrientation,
  20499. updatable: updatable
  20500. };
  20501. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  20502. };
  20503. /**
  20504. * Creates a cylinder or a cone mesh.
  20505. * Please consider using the same method from the MeshBuilder class instead.
  20506. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20507. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20508. * 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.
  20509. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20510. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20511. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20512. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20513. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20514. */
  20515. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  20516. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  20517. if (scene !== undefined) {
  20518. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  20519. updatable = scene;
  20520. }
  20521. scene = subdivisions;
  20522. subdivisions = 1;
  20523. }
  20524. var options = {
  20525. height: height,
  20526. diameterTop: diameterTop,
  20527. diameterBottom: diameterBottom,
  20528. tessellation: tessellation,
  20529. subdivisions: subdivisions,
  20530. sideOrientation: sideOrientation,
  20531. updatable: updatable
  20532. };
  20533. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  20534. };
  20535. // Torus (Code from SharpDX.org)
  20536. /**
  20537. * Creates a torus mesh.
  20538. * Please consider using the same method from the MeshBuilder class instead.
  20539. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  20540. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  20541. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  20542. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20543. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20544. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20545. */
  20546. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  20547. var options = {
  20548. diameter: diameter,
  20549. thickness: thickness,
  20550. tessellation: tessellation,
  20551. sideOrientation: sideOrientation,
  20552. updatable: updatable
  20553. };
  20554. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  20555. };
  20556. /**
  20557. * Creates a torus knot mesh.
  20558. * Please consider using the same method from the MeshBuilder class instead.
  20559. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  20560. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  20561. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  20562. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  20563. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20564. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20565. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20566. */
  20567. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  20568. var options = {
  20569. radius: radius,
  20570. tube: tube,
  20571. radialSegments: radialSegments,
  20572. tubularSegments: tubularSegments,
  20573. p: p,
  20574. q: q,
  20575. sideOrientation: sideOrientation,
  20576. updatable: updatable
  20577. };
  20578. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  20579. };
  20580. /**
  20581. * Creates a line mesh.
  20582. * Please consider using the same method from the MeshBuilder class instead.
  20583. * 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.
  20584. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20585. * The parameter `points` is an array successive Vector3.
  20586. * 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
  20587. * When updating an instance, remember that only point positions can change, not the number of points.
  20588. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20589. */
  20590. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  20591. var options = {
  20592. points: points,
  20593. updatable: updatable,
  20594. instance: instance
  20595. };
  20596. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  20597. };
  20598. /**
  20599. * Creates a dashed line mesh.
  20600. * Please consider using the same method from the MeshBuilder class instead.
  20601. * 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.
  20602. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20603. * The parameter `points` is an array successive Vector3.
  20604. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  20605. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  20606. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  20607. * 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
  20608. * When updating an instance, remember that only point positions can change, not the number of points.
  20609. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20610. */
  20611. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  20612. var options = {
  20613. points: points,
  20614. dashSize: dashSize,
  20615. gapSize: gapSize,
  20616. dashNb: dashNb,
  20617. updatable: updatable,
  20618. instance: instance
  20619. };
  20620. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  20621. };
  20622. /**
  20623. * Creates an extruded shape mesh.
  20624. * 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.
  20625. * Please consider using the same method from the MeshBuilder class instead.
  20626. *
  20627. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20628. * 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
  20629. * extruded along the Z axis.
  20630. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20631. * 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.
  20632. * The parameter `scale` (float, default 1) is the value to scale the shape.
  20633. * 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
  20634. * 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
  20635. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20636. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20637. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20638. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20639. */
  20640. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  20641. var options = {
  20642. shape: shape,
  20643. path: path,
  20644. scale: scale,
  20645. rotation: rotation,
  20646. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20647. sideOrientation: sideOrientation,
  20648. instance: instance,
  20649. updatable: updatable
  20650. };
  20651. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  20652. };
  20653. /**
  20654. * Creates an custom extruded shape mesh.
  20655. * 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.
  20656. * Please consider using the same method from the MeshBuilder class instead.
  20657. *
  20658. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20659. * 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
  20660. * extruded along the Z axis.
  20661. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20662. * 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
  20663. * and the distance of this point from the begining of the path :
  20664. * ```javascript
  20665. * var rotationFunction = function(i, distance) {
  20666. * // do things
  20667. * return rotationValue; }
  20668. * ```
  20669. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  20670. * 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
  20671. * and the distance of this point from the begining of the path :
  20672. * ```javascript
  20673. * var scaleFunction = function(i, distance) {
  20674. * // do things
  20675. * return scaleValue;}
  20676. * ```
  20677. * It must returns a float value that will be the scale value applied to the shape on each path point.
  20678. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  20679. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  20680. * 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
  20681. * 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
  20682. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20683. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20684. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20685. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20686. */
  20687. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  20688. var options = {
  20689. shape: shape,
  20690. path: path,
  20691. scaleFunction: scaleFunction,
  20692. rotationFunction: rotationFunction,
  20693. ribbonCloseArray: ribbonCloseArray,
  20694. ribbonClosePath: ribbonClosePath,
  20695. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20696. sideOrientation: sideOrientation,
  20697. instance: instance,
  20698. updatable: updatable
  20699. };
  20700. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  20701. };
  20702. /**
  20703. * Creates lathe mesh.
  20704. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  20705. * Please consider using the same method from the MeshBuilder class instead.
  20706. * 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
  20707. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  20708. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  20709. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  20710. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20711. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20712. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20713. */
  20714. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  20715. var options = {
  20716. shape: shape,
  20717. radius: radius,
  20718. tessellation: tessellation,
  20719. sideOrientation: sideOrientation,
  20720. updatable: updatable
  20721. };
  20722. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  20723. };
  20724. /**
  20725. * Creates a plane mesh.
  20726. * Please consider using the same method from the MeshBuilder class instead.
  20727. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  20728. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20729. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20730. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20731. */
  20732. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  20733. var options = {
  20734. size: size,
  20735. width: size,
  20736. height: size,
  20737. sideOrientation: sideOrientation,
  20738. updatable: updatable
  20739. };
  20740. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  20741. };
  20742. /**
  20743. * Creates a ground mesh.
  20744. * Please consider using the same method from the MeshBuilder class instead.
  20745. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  20746. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  20747. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20748. */
  20749. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  20750. var options = {
  20751. width: width,
  20752. height: height,
  20753. subdivisions: subdivisions,
  20754. updatable: updatable
  20755. };
  20756. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  20757. };
  20758. /**
  20759. * Creates a tiled ground mesh.
  20760. * Please consider using the same method from the MeshBuilder class instead.
  20761. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  20762. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  20763. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  20764. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  20765. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  20766. * numbers of subdivisions on the ground width and height of each tile.
  20767. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20768. */
  20769. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  20770. var options = {
  20771. xmin: xmin,
  20772. zmin: zmin,
  20773. xmax: xmax,
  20774. zmax: zmax,
  20775. subdivisions: subdivisions,
  20776. precision: precision,
  20777. updatable: updatable
  20778. };
  20779. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  20780. };
  20781. /**
  20782. * Creates a ground mesh from a height map.
  20783. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  20784. * Please consider using the same method from the MeshBuilder class instead.
  20785. * The parameter `url` sets the URL of the height map image resource.
  20786. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  20787. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  20788. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  20789. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  20790. * 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).
  20791. * This function is passed the newly built mesh :
  20792. * ```javascript
  20793. * function(mesh) { // do things
  20794. * return; }
  20795. * ```
  20796. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20797. */
  20798. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  20799. var options = {
  20800. width: width,
  20801. height: height,
  20802. subdivisions: subdivisions,
  20803. minHeight: minHeight,
  20804. maxHeight: maxHeight,
  20805. updatable: updatable,
  20806. onReady: onReady
  20807. };
  20808. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  20809. };
  20810. /**
  20811. * Creates a tube mesh.
  20812. * 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.
  20813. * Please consider using the same method from the MeshBuilder class instead.
  20814. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  20815. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  20816. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  20817. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  20818. * 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.
  20819. * It must return a radius value (positive float) :
  20820. * ```javascript
  20821. * var radiusFunction = function(i, distance) {
  20822. * // do things
  20823. * return radius; }
  20824. * ```
  20825. * 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
  20826. * 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
  20827. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20828. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20829. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20830. */
  20831. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  20832. var options = {
  20833. path: path,
  20834. radius: radius,
  20835. tessellation: tessellation,
  20836. radiusFunction: radiusFunction,
  20837. arc: 1,
  20838. cap: cap,
  20839. updatable: updatable,
  20840. sideOrientation: sideOrientation,
  20841. instance: instance
  20842. };
  20843. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  20844. };
  20845. /**
  20846. * Creates a polyhedron mesh.
  20847. * Please consider using the same method from the MeshBuilder class instead.
  20848. * 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
  20849. * to choose the wanted type.
  20850. * The parameter `size` (positive float, default 1) sets the polygon size.
  20851. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  20852. * 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`.
  20853. * 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
  20854. * 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)`).
  20855. * 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
  20856. * 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.
  20857. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20858. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20859. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20860. */
  20861. Mesh.CreatePolyhedron = function (name, options, scene) {
  20862. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  20863. };
  20864. /**
  20865. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  20866. * Please consider using the same method from the MeshBuilder class instead.
  20867. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  20868. * 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`).
  20869. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  20870. * 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.
  20871. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20872. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20873. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20874. */
  20875. Mesh.CreateIcoSphere = function (name, options, scene) {
  20876. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  20877. };
  20878. /**
  20879. * Creates a decal mesh.
  20880. * Please consider using the same method from the MeshBuilder class instead.
  20881. * 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.
  20882. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  20883. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  20884. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  20885. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  20886. */
  20887. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  20888. var options = {
  20889. position: position,
  20890. normal: normal,
  20891. size: size,
  20892. angle: angle
  20893. };
  20894. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  20895. };
  20896. // Skeletons
  20897. /**
  20898. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20899. */
  20900. Mesh.prototype.setPositionsForCPUSkinning = function () {
  20901. var source;
  20902. if (!this._sourcePositions) {
  20903. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20904. this._sourcePositions = new Float32Array(source);
  20905. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  20906. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  20907. }
  20908. }
  20909. return this._sourcePositions;
  20910. };
  20911. /**
  20912. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20913. */
  20914. Mesh.prototype.setNormalsForCPUSkinning = function () {
  20915. var source;
  20916. if (!this._sourceNormals) {
  20917. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20918. this._sourceNormals = new Float32Array(source);
  20919. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  20920. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  20921. }
  20922. }
  20923. return this._sourceNormals;
  20924. };
  20925. /**
  20926. * Update the vertex buffers by applying transformation from the bones
  20927. * @param {skeleton} skeleton to apply
  20928. */
  20929. Mesh.prototype.applySkeleton = function (skeleton) {
  20930. if (!this.geometry) {
  20931. return;
  20932. }
  20933. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  20934. return;
  20935. }
  20936. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  20937. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20938. return this;
  20939. }
  20940. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20941. return this;
  20942. }
  20943. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20944. return this;
  20945. }
  20946. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20947. return this;
  20948. }
  20949. if (!this._sourcePositions) {
  20950. this.setPositionsForCPUSkinning();
  20951. }
  20952. if (!this._sourceNormals) {
  20953. this.setNormalsForCPUSkinning();
  20954. }
  20955. // positionsData checks for not being Float32Array will only pass at most once
  20956. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20957. if (!(positionsData instanceof Float32Array)) {
  20958. positionsData = new Float32Array(positionsData);
  20959. }
  20960. // normalsData checks for not being Float32Array will only pass at most once
  20961. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20962. if (!(normalsData instanceof Float32Array)) {
  20963. normalsData = new Float32Array(normalsData);
  20964. }
  20965. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20966. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20967. var needExtras = this.numBoneInfluencers > 4;
  20968. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  20969. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  20970. var skeletonMatrices = skeleton.getTransformMatrices(this);
  20971. var tempVector3 = BABYLON.Vector3.Zero();
  20972. var finalMatrix = new BABYLON.Matrix();
  20973. var tempMatrix = new BABYLON.Matrix();
  20974. var matWeightIdx = 0;
  20975. var inf;
  20976. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  20977. var weight;
  20978. for (inf = 0; inf < 4; inf++) {
  20979. weight = matricesWeightsData[matWeightIdx + inf];
  20980. if (weight > 0) {
  20981. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20982. finalMatrix.addToSelf(tempMatrix);
  20983. }
  20984. else
  20985. break;
  20986. }
  20987. if (needExtras) {
  20988. for (inf = 0; inf < 4; inf++) {
  20989. weight = matricesWeightsExtraData[matWeightIdx + inf];
  20990. if (weight > 0) {
  20991. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20992. finalMatrix.addToSelf(tempMatrix);
  20993. }
  20994. else
  20995. break;
  20996. }
  20997. }
  20998. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  20999. tempVector3.toArray(positionsData, index);
  21000. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  21001. tempVector3.toArray(normalsData, index);
  21002. finalMatrix.reset();
  21003. }
  21004. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  21005. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  21006. return this;
  21007. };
  21008. // Tools
  21009. /**
  21010. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  21011. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  21012. */
  21013. Mesh.MinMax = function (meshes) {
  21014. var minVector = null;
  21015. var maxVector = null;
  21016. for (var i in meshes) {
  21017. var mesh = meshes[i];
  21018. var boundingBox = mesh.getBoundingInfo().boundingBox;
  21019. if (!minVector) {
  21020. minVector = boundingBox.minimumWorld;
  21021. maxVector = boundingBox.maximumWorld;
  21022. continue;
  21023. }
  21024. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  21025. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  21026. }
  21027. return {
  21028. min: minVector,
  21029. max: maxVector
  21030. };
  21031. };
  21032. /**
  21033. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  21034. */
  21035. Mesh.Center = function (meshesOrMinMaxVector) {
  21036. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  21037. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  21038. };
  21039. /**
  21040. * Merge the array of meshes into a single mesh for performance reasons.
  21041. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  21042. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  21043. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  21044. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  21045. */
  21046. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  21047. if (disposeSource === void 0) { disposeSource = true; }
  21048. var index;
  21049. if (!allow32BitsIndices) {
  21050. var totalVertices = 0;
  21051. // Counting vertices
  21052. for (index = 0; index < meshes.length; index++) {
  21053. if (meshes[index]) {
  21054. totalVertices += meshes[index].getTotalVertices();
  21055. if (totalVertices > 65536) {
  21056. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  21057. return null;
  21058. }
  21059. }
  21060. }
  21061. }
  21062. // Merge
  21063. var vertexData;
  21064. var otherVertexData;
  21065. var source;
  21066. for (index = 0; index < meshes.length; index++) {
  21067. if (meshes[index]) {
  21068. meshes[index].computeWorldMatrix(true);
  21069. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  21070. otherVertexData.transform(meshes[index].getWorldMatrix());
  21071. if (vertexData) {
  21072. vertexData.merge(otherVertexData);
  21073. }
  21074. else {
  21075. vertexData = otherVertexData;
  21076. source = meshes[index];
  21077. }
  21078. }
  21079. }
  21080. if (!meshSubclass) {
  21081. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  21082. }
  21083. vertexData.applyToMesh(meshSubclass);
  21084. // Setting properties
  21085. meshSubclass.material = source.material;
  21086. meshSubclass.checkCollisions = source.checkCollisions;
  21087. // Cleaning
  21088. if (disposeSource) {
  21089. for (index = 0; index < meshes.length; index++) {
  21090. if (meshes[index]) {
  21091. meshes[index].dispose();
  21092. }
  21093. }
  21094. }
  21095. return meshSubclass;
  21096. };
  21097. // Consts
  21098. Mesh._FRONTSIDE = 0;
  21099. Mesh._BACKSIDE = 1;
  21100. Mesh._DOUBLESIDE = 2;
  21101. Mesh._DEFAULTSIDE = 0;
  21102. Mesh._NO_CAP = 0;
  21103. Mesh._CAP_START = 1;
  21104. Mesh._CAP_END = 2;
  21105. Mesh._CAP_ALL = 3;
  21106. return Mesh;
  21107. })(BABYLON.AbstractMesh);
  21108. BABYLON.Mesh = Mesh;
  21109. })(BABYLON || (BABYLON = {}));
  21110. var BABYLON;
  21111. (function (BABYLON) {
  21112. var SubMesh = (function () {
  21113. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  21114. if (createBoundingBox === void 0) { createBoundingBox = true; }
  21115. this.materialIndex = materialIndex;
  21116. this.verticesStart = verticesStart;
  21117. this.verticesCount = verticesCount;
  21118. this.indexStart = indexStart;
  21119. this.indexCount = indexCount;
  21120. this._renderId = 0;
  21121. this._mesh = mesh;
  21122. this._renderingMesh = renderingMesh || mesh;
  21123. mesh.subMeshes.push(this);
  21124. this._trianglePlanes = [];
  21125. this._id = mesh.subMeshes.length - 1;
  21126. if (createBoundingBox) {
  21127. this.refreshBoundingInfo();
  21128. mesh.computeWorldMatrix(true);
  21129. }
  21130. }
  21131. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  21132. get: function () {
  21133. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  21134. },
  21135. enumerable: true,
  21136. configurable: true
  21137. });
  21138. SubMesh.prototype.getBoundingInfo = function () {
  21139. if (this.IsGlobal) {
  21140. return this._mesh.getBoundingInfo();
  21141. }
  21142. return this._boundingInfo;
  21143. };
  21144. SubMesh.prototype.getMesh = function () {
  21145. return this._mesh;
  21146. };
  21147. SubMesh.prototype.getRenderingMesh = function () {
  21148. return this._renderingMesh;
  21149. };
  21150. SubMesh.prototype.getMaterial = function () {
  21151. var rootMaterial = this._renderingMesh.material;
  21152. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  21153. var multiMaterial = rootMaterial;
  21154. return multiMaterial.getSubMaterial(this.materialIndex);
  21155. }
  21156. if (!rootMaterial) {
  21157. return this._mesh.getScene().defaultMaterial;
  21158. }
  21159. return rootMaterial;
  21160. };
  21161. // Methods
  21162. SubMesh.prototype.refreshBoundingInfo = function () {
  21163. this._lastColliderWorldVertices = null;
  21164. if (this.IsGlobal) {
  21165. return;
  21166. }
  21167. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21168. if (!data) {
  21169. this._boundingInfo = this._mesh._boundingInfo;
  21170. return;
  21171. }
  21172. var indices = this._renderingMesh.getIndices();
  21173. var extend;
  21174. //is this the only submesh?
  21175. if (this.indexStart === 0 && this.indexCount === indices.length) {
  21176. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  21177. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  21178. }
  21179. else {
  21180. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  21181. }
  21182. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21183. };
  21184. SubMesh.prototype._checkCollision = function (collider) {
  21185. return this.getBoundingInfo()._checkCollision(collider);
  21186. };
  21187. SubMesh.prototype.updateBoundingInfo = function (world) {
  21188. if (!this.getBoundingInfo()) {
  21189. this.refreshBoundingInfo();
  21190. }
  21191. this.getBoundingInfo().update(world);
  21192. };
  21193. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  21194. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  21195. };
  21196. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21197. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  21198. };
  21199. SubMesh.prototype.render = function (enableAlphaMode) {
  21200. this._renderingMesh.render(this, enableAlphaMode);
  21201. };
  21202. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  21203. if (!this._linesIndexBuffer) {
  21204. var linesIndices = [];
  21205. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21206. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  21207. }
  21208. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  21209. this.linesIndexCount = linesIndices.length;
  21210. }
  21211. return this._linesIndexBuffer;
  21212. };
  21213. SubMesh.prototype.canIntersects = function (ray) {
  21214. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  21215. };
  21216. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  21217. var intersectInfo = null;
  21218. // LineMesh first as it's also a Mesh...
  21219. if (this._mesh instanceof BABYLON.LinesMesh) {
  21220. var lineMesh = this._mesh;
  21221. // Line test
  21222. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  21223. var p0 = positions[indices[index]];
  21224. var p1 = positions[indices[index + 1]];
  21225. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  21226. if (length < 0) {
  21227. continue;
  21228. }
  21229. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  21230. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  21231. if (fastCheck) {
  21232. break;
  21233. }
  21234. }
  21235. }
  21236. }
  21237. else {
  21238. // Triangles test
  21239. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21240. var p0 = positions[indices[index]];
  21241. var p1 = positions[indices[index + 1]];
  21242. var p2 = positions[indices[index + 2]];
  21243. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  21244. if (currentIntersectInfo) {
  21245. if (currentIntersectInfo.distance < 0) {
  21246. continue;
  21247. }
  21248. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21249. intersectInfo = currentIntersectInfo;
  21250. intersectInfo.faceId = index / 3;
  21251. if (fastCheck) {
  21252. break;
  21253. }
  21254. }
  21255. }
  21256. }
  21257. }
  21258. return intersectInfo;
  21259. };
  21260. // Clone
  21261. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  21262. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  21263. if (!this.IsGlobal) {
  21264. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  21265. }
  21266. return result;
  21267. };
  21268. // Dispose
  21269. SubMesh.prototype.dispose = function () {
  21270. if (this._linesIndexBuffer) {
  21271. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  21272. this._linesIndexBuffer = null;
  21273. }
  21274. // Remove from mesh
  21275. var index = this._mesh.subMeshes.indexOf(this);
  21276. this._mesh.subMeshes.splice(index, 1);
  21277. };
  21278. // Statics
  21279. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  21280. var minVertexIndex = Number.MAX_VALUE;
  21281. var maxVertexIndex = -Number.MAX_VALUE;
  21282. renderingMesh = renderingMesh || mesh;
  21283. var indices = renderingMesh.getIndices();
  21284. for (var index = startIndex; index < startIndex + indexCount; index++) {
  21285. var vertexIndex = indices[index];
  21286. if (vertexIndex < minVertexIndex)
  21287. minVertexIndex = vertexIndex;
  21288. if (vertexIndex > maxVertexIndex)
  21289. maxVertexIndex = vertexIndex;
  21290. }
  21291. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  21292. };
  21293. return SubMesh;
  21294. })();
  21295. BABYLON.SubMesh = SubMesh;
  21296. })(BABYLON || (BABYLON = {}));
  21297. var BABYLON;
  21298. (function (BABYLON) {
  21299. var MeshBuilder = (function () {
  21300. function MeshBuilder() {
  21301. }
  21302. MeshBuilder.updateSideOrientationForRightHandedSystem = function (orientation, scene) {
  21303. if (!scene.useRightHandedSystem) {
  21304. if (orientation === undefined || orientation === null) {
  21305. return BABYLON.Mesh.FRONTSIDE;
  21306. }
  21307. switch (orientation) {
  21308. case BABYLON.Mesh.FRONTSIDE:
  21309. case BABYLON.Mesh.DEFAULTSIDE:
  21310. return BABYLON.Mesh.FRONTSIDE;
  21311. default:
  21312. return BABYLON.Mesh.BACKSIDE;
  21313. }
  21314. }
  21315. if (orientation === undefined || orientation === null) {
  21316. return BABYLON.Mesh.BACKSIDE;
  21317. }
  21318. switch (orientation) {
  21319. case BABYLON.Mesh.FRONTSIDE:
  21320. case BABYLON.Mesh.DEFAULTSIDE:
  21321. return BABYLON.Mesh.BACKSIDE;
  21322. default:
  21323. return BABYLON.Mesh.FRONTSIDE;
  21324. }
  21325. };
  21326. /**
  21327. * Creates a box mesh.
  21328. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  21329. * The parameter `size` sets the size (float) of each box side (default 1).
  21330. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  21331. * 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).
  21332. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  21333. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21334. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21335. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21336. */
  21337. MeshBuilder.CreateBox = function (name, options, scene) {
  21338. var box = new BABYLON.Mesh(name, scene);
  21339. options.sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21340. var vertexData = BABYLON.VertexData.CreateBox(options);
  21341. vertexData.applyToMesh(box, options.updatable);
  21342. return box;
  21343. };
  21344. /**
  21345. * Creates a sphere mesh.
  21346. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  21347. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21348. * 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`).
  21349. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21350. * 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
  21351. * 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).
  21352. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21353. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21354. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21355. */
  21356. MeshBuilder.CreateSphere = function (name, options, scene) {
  21357. var sphere = new BABYLON.Mesh(name, scene);
  21358. options.sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21359. var vertexData = BABYLON.VertexData.CreateSphere(options);
  21360. vertexData.applyToMesh(sphere, options.updatable);
  21361. return sphere;
  21362. };
  21363. /**
  21364. * Creates a plane polygonal mesh. By default, this is a disc.
  21365. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  21366. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21367. * 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.
  21368. * 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
  21369. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21370. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21371. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21372. */
  21373. MeshBuilder.CreateDisc = function (name, options, scene) {
  21374. var disc = new BABYLON.Mesh(name, scene);
  21375. options.sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21376. var vertexData = BABYLON.VertexData.CreateDisc(options);
  21377. vertexData.applyToMesh(disc, options.updatable);
  21378. return disc;
  21379. };
  21380. /**
  21381. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21382. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  21383. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21384. * 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`).
  21385. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21386. * 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.
  21387. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21388. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21389. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21390. */
  21391. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  21392. var sphere = new BABYLON.Mesh(name, scene);
  21393. options.sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21394. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  21395. vertexData.applyToMesh(sphere, options.updatable);
  21396. return sphere;
  21397. };
  21398. ;
  21399. /**
  21400. * Creates a ribbon mesh.
  21401. * 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.
  21402. *
  21403. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21404. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21405. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21406. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21407. * 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.
  21408. * 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.
  21409. * 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
  21410. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21411. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21412. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21413. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21414. */
  21415. MeshBuilder.CreateRibbon = function (name, options, scene) {
  21416. var pathArray = options.pathArray;
  21417. var closeArray = options.closeArray;
  21418. var closePath = options.closePath;
  21419. var offset = options.offset;
  21420. var sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21421. var instance = options.instance;
  21422. var updatable = options.updatable;
  21423. if (instance) {
  21424. // positionFunction : ribbon case
  21425. // only pathArray and sideOrientation parameters are taken into account for positions update
  21426. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  21427. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  21428. var positionFunction = function (positions) {
  21429. var minlg = pathArray[0].length;
  21430. var i = 0;
  21431. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  21432. for (var si = 1; si <= ns; si++) {
  21433. for (var p = 0; p < pathArray.length; p++) {
  21434. var path = pathArray[p];
  21435. var l = path.length;
  21436. minlg = (minlg < l) ? minlg : l;
  21437. var j = 0;
  21438. while (j < minlg) {
  21439. positions[i] = path[j].x;
  21440. positions[i + 1] = path[j].y;
  21441. positions[i + 2] = path[j].z;
  21442. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  21443. BABYLON.Tmp.Vector3[0].x = path[j].x;
  21444. }
  21445. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  21446. BABYLON.Tmp.Vector3[1].x = path[j].x;
  21447. }
  21448. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  21449. BABYLON.Tmp.Vector3[0].y = path[j].y;
  21450. }
  21451. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  21452. BABYLON.Tmp.Vector3[1].y = path[j].y;
  21453. }
  21454. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  21455. BABYLON.Tmp.Vector3[0].z = path[j].z;
  21456. }
  21457. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  21458. BABYLON.Tmp.Vector3[1].z = path[j].z;
  21459. }
  21460. j++;
  21461. i += 3;
  21462. }
  21463. if (instance._closePath) {
  21464. positions[i] = path[0].x;
  21465. positions[i + 1] = path[0].y;
  21466. positions[i + 2] = path[0].z;
  21467. i += 3;
  21468. }
  21469. }
  21470. }
  21471. };
  21472. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21473. positionFunction(positions);
  21474. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  21475. instance._boundingInfo.update(instance._worldMatrix);
  21476. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21477. if (!(instance.areNormalsFrozen)) {
  21478. var indices = instance.getIndices();
  21479. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21480. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21481. if (instance._closePath) {
  21482. var indexFirst = 0;
  21483. var indexLast = 0;
  21484. for (var p = 0; p < pathArray.length; p++) {
  21485. indexFirst = instance._idx[p] * 3;
  21486. if (p + 1 < pathArray.length) {
  21487. indexLast = (instance._idx[p + 1] - 1) * 3;
  21488. }
  21489. else {
  21490. indexLast = normals.length - 3;
  21491. }
  21492. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  21493. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  21494. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  21495. normals[indexLast] = normals[indexFirst];
  21496. normals[indexLast + 1] = normals[indexFirst + 1];
  21497. normals[indexLast + 2] = normals[indexFirst + 2];
  21498. }
  21499. }
  21500. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21501. }
  21502. return instance;
  21503. }
  21504. else {
  21505. var ribbon = new BABYLON.Mesh(name, scene);
  21506. ribbon.sideOrientation = sideOrientation;
  21507. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  21508. if (closePath) {
  21509. ribbon._idx = vertexData._idx;
  21510. }
  21511. ribbon._closePath = closePath;
  21512. ribbon._closeArray = closeArray;
  21513. vertexData.applyToMesh(ribbon, updatable);
  21514. return ribbon;
  21515. }
  21516. };
  21517. /**
  21518. * Creates a cylinder or a cone mesh.
  21519. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  21520. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21521. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21522. * 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.
  21523. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21524. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21525. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  21526. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  21527. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  21528. * 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).
  21529. * 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
  21530. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  21531. * 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
  21532. * 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.
  21533. * If `enclose` is false, a ring surface is one element.
  21534. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  21535. * 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
  21536. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21537. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21538. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21539. */
  21540. MeshBuilder.CreateCylinder = function (name, options, scene) {
  21541. var cylinder = new BABYLON.Mesh(name, scene);
  21542. options.sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21543. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  21544. vertexData.applyToMesh(cylinder, options.updatable);
  21545. return cylinder;
  21546. };
  21547. /**
  21548. * Creates a torus mesh.
  21549. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  21550. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21551. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21552. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21553. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21554. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21555. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21556. */
  21557. MeshBuilder.CreateTorus = function (name, options, scene) {
  21558. var torus = new BABYLON.Mesh(name, scene);
  21559. options.sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21560. var vertexData = BABYLON.VertexData.CreateTorus(options);
  21561. vertexData.applyToMesh(torus, options.updatable);
  21562. return torus;
  21563. };
  21564. /**
  21565. * Creates a torus knot mesh.
  21566. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  21567. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21568. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21569. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21570. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21571. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21572. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21573. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21574. */
  21575. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  21576. var torusKnot = new BABYLON.Mesh(name, scene);
  21577. options.sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21578. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  21579. vertexData.applyToMesh(torusKnot, options.updatable);
  21580. return torusKnot;
  21581. };
  21582. /**
  21583. * Creates a line system mesh.
  21584. * A line system is a pool of many lines gathered in a single mesh.
  21585. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  21586. * 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.
  21587. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  21588. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  21589. * 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
  21590. * 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
  21591. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  21592. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21593. */
  21594. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  21595. var instance = options.instance;
  21596. var lines = options.lines;
  21597. if (instance) {
  21598. var positionFunction = function (positions) {
  21599. var i = 0;
  21600. for (var l = 0; l < lines.length; l++) {
  21601. var points = lines[l];
  21602. for (var p = 0; p < points.length; p++) {
  21603. positions[i] = points[p].x;
  21604. positions[i + 1] = points[p].y;
  21605. positions[i + 2] = points[p].z;
  21606. i += 3;
  21607. }
  21608. }
  21609. };
  21610. instance.updateMeshPositions(positionFunction, false);
  21611. return instance;
  21612. }
  21613. // line system creation
  21614. var lineSystem = new BABYLON.LinesMesh(name, scene);
  21615. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  21616. vertexData.applyToMesh(lineSystem, options.updatable);
  21617. return lineSystem;
  21618. };
  21619. /**
  21620. * Creates a line mesh.
  21621. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  21622. * 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.
  21623. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21624. * The parameter `points` is an array successive Vector3.
  21625. * 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
  21626. * When updating an instance, remember that only point positions can change, not the number of points.
  21627. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21628. */
  21629. MeshBuilder.CreateLines = function (name, options, scene) {
  21630. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  21631. return lines;
  21632. };
  21633. /**
  21634. * Creates a dashed line mesh.
  21635. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  21636. * 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.
  21637. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21638. * The parameter `points` is an array successive Vector3.
  21639. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21640. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21641. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21642. * 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
  21643. * When updating an instance, remember that only point positions can change, not the number of points.
  21644. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21645. */
  21646. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  21647. var points = options.points;
  21648. var instance = options.instance;
  21649. var gapSize = options.gapSize;
  21650. var dashNb = options.dashNb;
  21651. var dashSize = options.dashSize;
  21652. if (instance) {
  21653. var positionFunction = function (positions) {
  21654. var curvect = BABYLON.Vector3.Zero();
  21655. var nbSeg = positions.length / 6;
  21656. var lg = 0;
  21657. var nb = 0;
  21658. var shft = 0;
  21659. var dashshft = 0;
  21660. var curshft = 0;
  21661. var p = 0;
  21662. var i = 0;
  21663. var j = 0;
  21664. for (i = 0; i < points.length - 1; i++) {
  21665. points[i + 1].subtractToRef(points[i], curvect);
  21666. lg += curvect.length();
  21667. }
  21668. shft = lg / nbSeg;
  21669. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  21670. for (i = 0; i < points.length - 1; i++) {
  21671. points[i + 1].subtractToRef(points[i], curvect);
  21672. nb = Math.floor(curvect.length() / shft);
  21673. curvect.normalize();
  21674. j = 0;
  21675. while (j < nb && p < positions.length) {
  21676. curshft = shft * j;
  21677. positions[p] = points[i].x + curshft * curvect.x;
  21678. positions[p + 1] = points[i].y + curshft * curvect.y;
  21679. positions[p + 2] = points[i].z + curshft * curvect.z;
  21680. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  21681. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  21682. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  21683. p += 6;
  21684. j++;
  21685. }
  21686. }
  21687. while (p < positions.length) {
  21688. positions[p] = points[i].x;
  21689. positions[p + 1] = points[i].y;
  21690. positions[p + 2] = points[i].z;
  21691. p += 3;
  21692. }
  21693. };
  21694. instance.updateMeshPositions(positionFunction, false);
  21695. return instance;
  21696. }
  21697. // dashed lines creation
  21698. var dashedLines = new BABYLON.LinesMesh(name, scene);
  21699. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  21700. vertexData.applyToMesh(dashedLines, options.updatable);
  21701. dashedLines.dashSize = dashSize;
  21702. dashedLines.gapSize = gapSize;
  21703. return dashedLines;
  21704. };
  21705. /**
  21706. * Creates an extruded shape mesh.
  21707. * 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.
  21708. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  21709. *
  21710. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21711. * 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
  21712. * extruded along the Z axis.
  21713. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21714. * 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.
  21715. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21716. * 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
  21717. * 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
  21718. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21719. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21720. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21721. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21722. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21723. */
  21724. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  21725. var path = options.path;
  21726. var shape = options.shape;
  21727. var scale = options.scale || 1;
  21728. var rotation = options.rotation || 0;
  21729. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  21730. var updatable = options.updatable;
  21731. var sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21732. var instance = options.instance;
  21733. var invertUV = options.invertUV || false;
  21734. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  21735. };
  21736. /**
  21737. * Creates an custom extruded shape mesh.
  21738. * 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.
  21739. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  21740. *
  21741. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21742. * 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
  21743. * extruded along the Z axis.
  21744. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21745. * 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
  21746. * and the distance of this point from the begining of the path :
  21747. * ```javascript
  21748. * var rotationFunction = function(i, distance) {
  21749. * // do things
  21750. * return rotationValue; }
  21751. * ```
  21752. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21753. * 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
  21754. * and the distance of this point from the begining of the path :
  21755. * ```javascript
  21756. * var scaleFunction = function(i, distance) {
  21757. * // do things
  21758. * return scaleValue;}
  21759. * ```
  21760. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21761. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21762. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21763. * 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
  21764. * 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
  21765. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21766. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21767. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21768. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21769. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21770. */
  21771. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  21772. var path = options.path;
  21773. var shape = options.shape;
  21774. var scaleFunction = options.scaleFunction || (function () { return 1; });
  21775. var rotationFunction = options.rotationFunction || (function () { return 0; });
  21776. var ribbonCloseArray = options.ribbonCloseArray || false;
  21777. var ribbonClosePath = options.ribbonClosePath || false;
  21778. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  21779. var updatable = options.updatable;
  21780. var sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21781. var instance = options.instance;
  21782. var invertUV = options.invertUV || false;
  21783. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  21784. };
  21785. /**
  21786. * Creates lathe mesh.
  21787. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21788. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  21789. *
  21790. * 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
  21791. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21792. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21793. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21794. * 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.
  21795. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  21796. * 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
  21797. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21798. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21799. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21800. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21801. */
  21802. MeshBuilder.CreateLathe = function (name, options, scene) {
  21803. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  21804. var closed = (options.closed === undefined) ? true : options.closed;
  21805. var shape = options.shape;
  21806. var radius = options.radius || 1;
  21807. var tessellation = options.tessellation || 64;
  21808. var updatable = options.updatable;
  21809. var sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21810. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  21811. var pi2 = Math.PI * 2;
  21812. var paths = new Array();
  21813. var invertUV = options.invertUV || false;
  21814. var i = 0;
  21815. var p = 0;
  21816. var step = pi2 / tessellation * arc;
  21817. var rotated;
  21818. var path = new Array();
  21819. ;
  21820. for (i = 0; i <= tessellation; i++) {
  21821. var path = [];
  21822. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  21823. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  21824. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  21825. }
  21826. for (p = 0; p < shape.length; p++) {
  21827. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  21828. path.push(rotated);
  21829. }
  21830. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  21831. 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));
  21832. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  21833. }
  21834. paths.push(path);
  21835. }
  21836. // lathe ribbon
  21837. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  21838. return lathe;
  21839. };
  21840. /**
  21841. * Creates a plane mesh.
  21842. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  21843. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21844. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  21845. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  21846. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21847. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21848. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21849. */
  21850. MeshBuilder.CreatePlane = function (name, options, scene) {
  21851. var plane = new BABYLON.Mesh(name, scene);
  21852. options.sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21853. var vertexData = BABYLON.VertexData.CreatePlane(options);
  21854. vertexData.applyToMesh(plane, options.updatable);
  21855. if (options.sourcePlane) {
  21856. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  21857. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  21858. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  21859. plane.rotate(vectorProduct, product);
  21860. }
  21861. return plane;
  21862. };
  21863. /**
  21864. * Creates a ground mesh.
  21865. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  21866. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21867. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21868. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21869. */
  21870. MeshBuilder.CreateGround = function (name, options, scene) {
  21871. var ground = new BABYLON.GroundMesh(name, scene);
  21872. ground._setReady(false);
  21873. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  21874. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  21875. ground._width = options.width || 1;
  21876. ground._height = options.height || 1;
  21877. ground._maxX = ground._width / 2;
  21878. ground._maxZ = ground._height / 2;
  21879. ground._minX = -ground._maxX;
  21880. ground._minZ = -ground._maxZ;
  21881. var vertexData = BABYLON.VertexData.CreateGround(options);
  21882. vertexData.applyToMesh(ground, options.updatable);
  21883. ground._setReady(true);
  21884. return ground;
  21885. };
  21886. /**
  21887. * Creates a tiled ground mesh.
  21888. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  21889. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21890. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21891. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21892. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21893. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21894. * numbers of subdivisions on the ground width and height of each tile.
  21895. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21896. */
  21897. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  21898. var tiledGround = new BABYLON.Mesh(name, scene);
  21899. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  21900. vertexData.applyToMesh(tiledGround, options.updatable);
  21901. return tiledGround;
  21902. };
  21903. /**
  21904. * Creates a ground mesh from a height map.
  21905. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21906. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  21907. * The parameter `url` sets the URL of the height map image resource.
  21908. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21909. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21910. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21911. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21912. * 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).
  21913. * This function is passed the newly built mesh :
  21914. * ```javascript
  21915. * function(mesh) { // do things
  21916. * return; }
  21917. * ```
  21918. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21919. */
  21920. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  21921. var width = options.width || 10.0;
  21922. var height = options.height || 10.0;
  21923. var subdivisions = options.subdivisions || 1 | 0;
  21924. var minHeight = options.minHeight || 0.0;
  21925. var maxHeight = options.maxHeight || 10.0;
  21926. var updatable = options.updatable;
  21927. var onReady = options.onReady;
  21928. var ground = new BABYLON.GroundMesh(name, scene);
  21929. ground._subdivisionsX = subdivisions;
  21930. ground._subdivisionsY = subdivisions;
  21931. ground._width = width;
  21932. ground._height = height;
  21933. ground._maxX = ground._width / 2.0;
  21934. ground._maxZ = ground._height / 2.0;
  21935. ground._minX = -ground._maxX;
  21936. ground._minZ = -ground._maxZ;
  21937. ground._setReady(false);
  21938. var onload = function (img) {
  21939. // Getting height map data
  21940. var canvas = document.createElement("canvas");
  21941. var context = canvas.getContext("2d");
  21942. var bufferWidth = img.width;
  21943. var bufferHeight = img.height;
  21944. canvas.width = bufferWidth;
  21945. canvas.height = bufferHeight;
  21946. context.drawImage(img, 0, 0);
  21947. // Create VertexData from map data
  21948. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  21949. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  21950. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  21951. width: width, height: height,
  21952. subdivisions: subdivisions,
  21953. minHeight: minHeight, maxHeight: maxHeight,
  21954. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  21955. });
  21956. vertexData.applyToMesh(ground, updatable);
  21957. ground._setReady(true);
  21958. //execute ready callback, if set
  21959. if (onReady) {
  21960. onReady(ground);
  21961. }
  21962. };
  21963. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  21964. return ground;
  21965. };
  21966. /**
  21967. * Creates a tube mesh.
  21968. * 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.
  21969. *
  21970. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  21971. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21972. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21973. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21974. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21975. * 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.
  21976. * It must return a radius value (positive float) :
  21977. * ```javascript
  21978. * var radiusFunction = function(i, distance) {
  21979. * // do things
  21980. * return radius; }
  21981. * ```
  21982. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  21983. * 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
  21984. * 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
  21985. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21986. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21987. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21988. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21989. */
  21990. MeshBuilder.CreateTube = function (name, options, scene) {
  21991. var path = options.path;
  21992. var radius = options.radius || 1.0;
  21993. var tessellation = options.tessellation || 64 | 0;
  21994. var radiusFunction = options.radiusFunction;
  21995. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  21996. var invertUV = options.invertUV || false;
  21997. var updatable = options.updatable;
  21998. var sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21999. var instance = options.instance;
  22000. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  22001. // tube geometry
  22002. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  22003. var tangents = path3D.getTangents();
  22004. var normals = path3D.getNormals();
  22005. var distances = path3D.getDistances();
  22006. var pi2 = Math.PI * 2;
  22007. var step = pi2 / tessellation * arc;
  22008. var returnRadius = function () { return radius; };
  22009. var radiusFunctionFinal = radiusFunction || returnRadius;
  22010. var circlePath;
  22011. var rad;
  22012. var normal;
  22013. var rotated;
  22014. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  22015. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  22016. for (var i = 0; i < path.length; i++) {
  22017. rad = radiusFunctionFinal(i, distances[i]); // current radius
  22018. circlePath = Array(); // current circle array
  22019. normal = normals[i]; // current normal
  22020. for (var t = 0; t < tessellation; t++) {
  22021. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  22022. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  22023. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  22024. rotated.scaleInPlace(rad).addInPlace(path[i]);
  22025. circlePath[t] = rotated;
  22026. }
  22027. circlePaths[index] = circlePath;
  22028. index++;
  22029. }
  22030. // cap
  22031. var capPath = function (nbPoints, pathIndex) {
  22032. var pointCap = Array();
  22033. for (var i = 0; i < nbPoints; i++) {
  22034. pointCap.push(path[pathIndex]);
  22035. }
  22036. return pointCap;
  22037. };
  22038. switch (cap) {
  22039. case BABYLON.Mesh.NO_CAP:
  22040. break;
  22041. case BABYLON.Mesh.CAP_START:
  22042. circlePaths[0] = capPath(tessellation, 0);
  22043. circlePaths[1] = circlePaths[2].slice(0);
  22044. break;
  22045. case BABYLON.Mesh.CAP_END:
  22046. circlePaths[index] = circlePaths[index - 1].slice(0);
  22047. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22048. break;
  22049. case BABYLON.Mesh.CAP_ALL:
  22050. circlePaths[0] = capPath(tessellation, 0);
  22051. circlePaths[1] = circlePaths[2].slice(0);
  22052. circlePaths[index] = circlePaths[index - 1].slice(0);
  22053. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22054. break;
  22055. default:
  22056. break;
  22057. }
  22058. return circlePaths;
  22059. };
  22060. var path3D;
  22061. var pathArray;
  22062. if (instance) {
  22063. var arc = options.arc || instance.arc;
  22064. path3D = (instance.path3D).update(path);
  22065. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  22066. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  22067. instance.path3D = path3D;
  22068. instance.pathArray = pathArray;
  22069. instance.arc = arc;
  22070. return instance;
  22071. }
  22072. // tube creation
  22073. path3D = new BABYLON.Path3D(path);
  22074. var newPathArray = new Array();
  22075. cap = (cap < 0 || cap > 3) ? 0 : cap;
  22076. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  22077. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  22078. tube.pathArray = pathArray;
  22079. tube.path3D = path3D;
  22080. tube.tessellation = tessellation;
  22081. tube.cap = cap;
  22082. tube.arc = options.arc;
  22083. return tube;
  22084. };
  22085. /**
  22086. * Creates a polyhedron mesh.
  22087. *
  22088. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  22089. * 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
  22090. * to choose the wanted type.
  22091. * The parameter `size` (positive float, default 1) sets the polygon size.
  22092. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22093. * 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`.
  22094. * 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
  22095. * 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)`).
  22096. * 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
  22097. * 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.
  22098. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22099. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22100. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22101. */
  22102. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  22103. var polyhedron = new BABYLON.Mesh(name, scene);
  22104. options.sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  22105. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  22106. vertexData.applyToMesh(polyhedron, options.updatable);
  22107. return polyhedron;
  22108. };
  22109. /**
  22110. * Creates a decal mesh.
  22111. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  22112. * 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.
  22113. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  22114. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  22115. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  22116. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  22117. */
  22118. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  22119. var indices = sourceMesh.getIndices();
  22120. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22121. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22122. var position = options.position || BABYLON.Vector3.Zero();
  22123. var normal = options.normal || BABYLON.Vector3.Up();
  22124. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  22125. var angle = options.angle || 0;
  22126. // Getting correct rotation
  22127. if (!normal) {
  22128. var target = new BABYLON.Vector3(0, 0, 1);
  22129. var camera = sourceMesh.getScene().activeCamera;
  22130. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  22131. normal = camera.globalPosition.subtract(cameraWorldTarget);
  22132. }
  22133. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  22134. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  22135. var pitch = Math.atan2(normal.y, len);
  22136. // Matrix
  22137. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  22138. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  22139. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  22140. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  22141. var vertexData = new BABYLON.VertexData();
  22142. vertexData.indices = [];
  22143. vertexData.positions = [];
  22144. vertexData.normals = [];
  22145. vertexData.uvs = [];
  22146. var currentVertexDataIndex = 0;
  22147. var extractDecalVector3 = function (indexId) {
  22148. var vertexId = indices[indexId];
  22149. var result = new BABYLON.PositionNormalVertex();
  22150. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  22151. // Send vector to decal local world
  22152. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  22153. // Get normal
  22154. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  22155. return result;
  22156. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  22157. var clip = function (vertices, axis) {
  22158. if (vertices.length === 0) {
  22159. return vertices;
  22160. }
  22161. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  22162. var clipVertices = function (v0, v1) {
  22163. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  22164. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  22165. };
  22166. var result = new Array();
  22167. for (var index = 0; index < vertices.length; index += 3) {
  22168. var v1Out;
  22169. var v2Out;
  22170. var v3Out;
  22171. var total = 0;
  22172. var nV1, nV2, nV3, nV4;
  22173. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  22174. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  22175. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  22176. v1Out = d1 > 0;
  22177. v2Out = d2 > 0;
  22178. v3Out = d3 > 0;
  22179. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  22180. switch (total) {
  22181. case 0:
  22182. result.push(vertices[index]);
  22183. result.push(vertices[index + 1]);
  22184. result.push(vertices[index + 2]);
  22185. break;
  22186. case 1:
  22187. if (v1Out) {
  22188. nV1 = vertices[index + 1];
  22189. nV2 = vertices[index + 2];
  22190. nV3 = clipVertices(vertices[index], nV1);
  22191. nV4 = clipVertices(vertices[index], nV2);
  22192. }
  22193. if (v2Out) {
  22194. nV1 = vertices[index];
  22195. nV2 = vertices[index + 2];
  22196. nV3 = clipVertices(vertices[index + 1], nV1);
  22197. nV4 = clipVertices(vertices[index + 1], nV2);
  22198. result.push(nV3);
  22199. result.push(nV2.clone());
  22200. result.push(nV1.clone());
  22201. result.push(nV2.clone());
  22202. result.push(nV3.clone());
  22203. result.push(nV4);
  22204. break;
  22205. }
  22206. if (v3Out) {
  22207. nV1 = vertices[index];
  22208. nV2 = vertices[index + 1];
  22209. nV3 = clipVertices(vertices[index + 2], nV1);
  22210. nV4 = clipVertices(vertices[index + 2], nV2);
  22211. }
  22212. result.push(nV1.clone());
  22213. result.push(nV2.clone());
  22214. result.push(nV3);
  22215. result.push(nV4);
  22216. result.push(nV3.clone());
  22217. result.push(nV2.clone());
  22218. break;
  22219. case 2:
  22220. if (!v1Out) {
  22221. nV1 = vertices[index].clone();
  22222. nV2 = clipVertices(nV1, vertices[index + 1]);
  22223. nV3 = clipVertices(nV1, vertices[index + 2]);
  22224. result.push(nV1);
  22225. result.push(nV2);
  22226. result.push(nV3);
  22227. }
  22228. if (!v2Out) {
  22229. nV1 = vertices[index + 1].clone();
  22230. nV2 = clipVertices(nV1, vertices[index + 2]);
  22231. nV3 = clipVertices(nV1, vertices[index]);
  22232. result.push(nV1);
  22233. result.push(nV2);
  22234. result.push(nV3);
  22235. }
  22236. if (!v3Out) {
  22237. nV1 = vertices[index + 2].clone();
  22238. nV2 = clipVertices(nV1, vertices[index]);
  22239. nV3 = clipVertices(nV1, vertices[index + 1]);
  22240. result.push(nV1);
  22241. result.push(nV2);
  22242. result.push(nV3);
  22243. }
  22244. break;
  22245. case 3:
  22246. break;
  22247. }
  22248. }
  22249. return result;
  22250. };
  22251. for (var index = 0; index < indices.length; index += 3) {
  22252. var faceVertices = new Array();
  22253. faceVertices.push(extractDecalVector3(index));
  22254. faceVertices.push(extractDecalVector3(index + 1));
  22255. faceVertices.push(extractDecalVector3(index + 2));
  22256. // Clip
  22257. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  22258. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  22259. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  22260. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  22261. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  22262. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  22263. if (faceVertices.length === 0) {
  22264. continue;
  22265. }
  22266. // Add UVs and get back to world
  22267. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  22268. var vertex = faceVertices[vIndex];
  22269. //TODO check for Int32Array
  22270. vertexData.indices.push(currentVertexDataIndex);
  22271. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  22272. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  22273. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  22274. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  22275. currentVertexDataIndex++;
  22276. }
  22277. }
  22278. // Return mesh
  22279. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  22280. vertexData.applyToMesh(decal);
  22281. decal.position = position.clone();
  22282. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  22283. return decal;
  22284. };
  22285. // Privates
  22286. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  22287. // extrusion geometry
  22288. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  22289. var tangents = path3D.getTangents();
  22290. var normals = path3D.getNormals();
  22291. var binormals = path3D.getBinormals();
  22292. var distances = path3D.getDistances();
  22293. var angle = 0;
  22294. var returnScale = function () { return scale; };
  22295. var returnRotation = function () { return rotation; };
  22296. var rotate = custom ? rotateFunction : returnRotation;
  22297. var scl = custom ? scaleFunction : returnScale;
  22298. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  22299. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  22300. for (var i = 0; i < curve.length; i++) {
  22301. var shapePath = new Array();
  22302. var angleStep = rotate(i, distances[i]);
  22303. var scaleRatio = scl(i, distances[i]);
  22304. for (var p = 0; p < shape.length; p++) {
  22305. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  22306. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  22307. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  22308. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  22309. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  22310. shapePath[p] = rotated;
  22311. }
  22312. shapePaths[index] = shapePath;
  22313. angle += angleStep;
  22314. index++;
  22315. }
  22316. // cap
  22317. var capPath = function (shapePath) {
  22318. var pointCap = Array();
  22319. var barycenter = BABYLON.Vector3.Zero();
  22320. var i;
  22321. for (i = 0; i < shapePath.length; i++) {
  22322. barycenter.addInPlace(shapePath[i]);
  22323. }
  22324. barycenter.scaleInPlace(1 / shapePath.length);
  22325. for (i = 0; i < shapePath.length; i++) {
  22326. pointCap.push(barycenter);
  22327. }
  22328. return pointCap;
  22329. };
  22330. switch (cap) {
  22331. case BABYLON.Mesh.NO_CAP:
  22332. break;
  22333. case BABYLON.Mesh.CAP_START:
  22334. shapePaths[0] = capPath(shapePaths[2]);
  22335. shapePaths[1] = shapePaths[2].slice(0);
  22336. break;
  22337. case BABYLON.Mesh.CAP_END:
  22338. shapePaths[index] = shapePaths[index - 1];
  22339. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  22340. break;
  22341. case BABYLON.Mesh.CAP_ALL:
  22342. shapePaths[0] = capPath(shapePaths[2]);
  22343. shapePaths[1] = shapePaths[2].slice(0);
  22344. shapePaths[index] = shapePaths[index - 1];
  22345. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  22346. break;
  22347. default:
  22348. break;
  22349. }
  22350. return shapePaths;
  22351. };
  22352. var path3D;
  22353. var pathArray;
  22354. if (instance) {
  22355. path3D = (instance.path3D).update(curve);
  22356. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  22357. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  22358. return instance;
  22359. }
  22360. // extruded shape creation
  22361. path3D = new BABYLON.Path3D(curve);
  22362. var newShapePaths = new Array();
  22363. cap = (cap < 0 || cap > 3) ? 0 : cap;
  22364. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  22365. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  22366. extrudedGeneric.pathArray = pathArray;
  22367. extrudedGeneric.path3D = path3D;
  22368. extrudedGeneric.cap = cap;
  22369. return extrudedGeneric;
  22370. };
  22371. return MeshBuilder;
  22372. })();
  22373. BABYLON.MeshBuilder = MeshBuilder;
  22374. })(BABYLON || (BABYLON = {}));
  22375. var BABYLON;
  22376. (function (BABYLON) {
  22377. var BaseTexture = (function () {
  22378. function BaseTexture(scene) {
  22379. this.hasAlpha = false;
  22380. this.getAlphaFromRGB = false;
  22381. this.level = 1;
  22382. this.coordinatesIndex = 0;
  22383. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  22384. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22385. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22386. this.anisotropicFilteringLevel = 4;
  22387. this.isCube = false;
  22388. this.isRenderTarget = false;
  22389. this.animations = new Array();
  22390. /**
  22391. * An event triggered when the texture is disposed.
  22392. * @type {BABYLON.Observable}
  22393. */
  22394. this.onDisposeObservable = new BABYLON.Observable();
  22395. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22396. this._scene = scene;
  22397. this._scene.textures.push(this);
  22398. }
  22399. BaseTexture.prototype.toString = function () {
  22400. return this.name;
  22401. };
  22402. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  22403. set: function (callback) {
  22404. if (this._onDisposeObserver) {
  22405. this.onDisposeObservable.remove(this._onDisposeObserver);
  22406. }
  22407. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22408. },
  22409. enumerable: true,
  22410. configurable: true
  22411. });
  22412. BaseTexture.prototype.getScene = function () {
  22413. return this._scene;
  22414. };
  22415. BaseTexture.prototype.getTextureMatrix = function () {
  22416. return null;
  22417. };
  22418. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  22419. return null;
  22420. };
  22421. BaseTexture.prototype.getInternalTexture = function () {
  22422. return this._texture;
  22423. };
  22424. BaseTexture.prototype.isReady = function () {
  22425. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22426. return true;
  22427. }
  22428. if (this._texture) {
  22429. return this._texture.isReady;
  22430. }
  22431. return false;
  22432. };
  22433. BaseTexture.prototype.getSize = function () {
  22434. if (this._texture._width) {
  22435. return new BABYLON.Size(this._texture._width, this._texture._height);
  22436. }
  22437. if (this._texture._size) {
  22438. return new BABYLON.Size(this._texture._size, this._texture._size);
  22439. }
  22440. return BABYLON.Size.Zero();
  22441. };
  22442. BaseTexture.prototype.getBaseSize = function () {
  22443. if (!this.isReady() || !this._texture)
  22444. return BABYLON.Size.Zero();
  22445. if (this._texture._size) {
  22446. return new BABYLON.Size(this._texture._size, this._texture._size);
  22447. }
  22448. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  22449. };
  22450. BaseTexture.prototype.scale = function (ratio) {
  22451. };
  22452. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  22453. get: function () {
  22454. return false;
  22455. },
  22456. enumerable: true,
  22457. configurable: true
  22458. });
  22459. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  22460. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22461. for (var index = 0; index < texturesCache.length; index++) {
  22462. var texturesCacheEntry = texturesCache[index];
  22463. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22464. texturesCache.splice(index, 1);
  22465. return;
  22466. }
  22467. }
  22468. };
  22469. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  22470. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22471. for (var index = 0; index < texturesCache.length; index++) {
  22472. var texturesCacheEntry = texturesCache[index];
  22473. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22474. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  22475. texturesCacheEntry.references++;
  22476. return texturesCacheEntry;
  22477. }
  22478. }
  22479. }
  22480. return null;
  22481. };
  22482. BaseTexture.prototype.delayLoad = function () {
  22483. };
  22484. BaseTexture.prototype.clone = function () {
  22485. return null;
  22486. };
  22487. BaseTexture.prototype.releaseInternalTexture = function () {
  22488. if (this._texture) {
  22489. this._scene.getEngine().releaseInternalTexture(this._texture);
  22490. delete this._texture;
  22491. }
  22492. };
  22493. BaseTexture.prototype.dispose = function () {
  22494. // Animations
  22495. this.getScene().stopAnimation(this);
  22496. // Remove from scene
  22497. var index = this._scene.textures.indexOf(this);
  22498. if (index >= 0) {
  22499. this._scene.textures.splice(index, 1);
  22500. }
  22501. if (this._texture === undefined) {
  22502. return;
  22503. }
  22504. // Release
  22505. this.releaseInternalTexture();
  22506. // Callback
  22507. this.onDisposeObservable.notifyObservers(this);
  22508. this.onDisposeObservable.clear();
  22509. };
  22510. BaseTexture.prototype.serialize = function () {
  22511. if (!this.name) {
  22512. return null;
  22513. }
  22514. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22515. // Animations
  22516. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22517. return serializationObject;
  22518. };
  22519. __decorate([
  22520. BABYLON.serialize()
  22521. ], BaseTexture.prototype, "name", void 0);
  22522. __decorate([
  22523. BABYLON.serialize()
  22524. ], BaseTexture.prototype, "hasAlpha", void 0);
  22525. __decorate([
  22526. BABYLON.serialize()
  22527. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  22528. __decorate([
  22529. BABYLON.serialize()
  22530. ], BaseTexture.prototype, "level", void 0);
  22531. __decorate([
  22532. BABYLON.serialize()
  22533. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  22534. __decorate([
  22535. BABYLON.serialize()
  22536. ], BaseTexture.prototype, "coordinatesMode", void 0);
  22537. __decorate([
  22538. BABYLON.serialize()
  22539. ], BaseTexture.prototype, "wrapU", void 0);
  22540. __decorate([
  22541. BABYLON.serialize()
  22542. ], BaseTexture.prototype, "wrapV", void 0);
  22543. __decorate([
  22544. BABYLON.serialize()
  22545. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  22546. __decorate([
  22547. BABYLON.serialize()
  22548. ], BaseTexture.prototype, "isCube", void 0);
  22549. __decorate([
  22550. BABYLON.serialize()
  22551. ], BaseTexture.prototype, "isRenderTarget", void 0);
  22552. return BaseTexture;
  22553. })();
  22554. BABYLON.BaseTexture = BaseTexture;
  22555. })(BABYLON || (BABYLON = {}));
  22556. var BABYLON;
  22557. (function (BABYLON) {
  22558. var Texture = (function (_super) {
  22559. __extends(Texture, _super);
  22560. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  22561. var _this = this;
  22562. if (noMipmap === void 0) { noMipmap = false; }
  22563. if (invertY === void 0) { invertY = true; }
  22564. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22565. if (onLoad === void 0) { onLoad = null; }
  22566. if (onError === void 0) { onError = null; }
  22567. if (buffer === void 0) { buffer = null; }
  22568. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22569. _super.call(this, scene);
  22570. this.uOffset = 0;
  22571. this.vOffset = 0;
  22572. this.uScale = 1.0;
  22573. this.vScale = 1.0;
  22574. this.uAng = 0;
  22575. this.vAng = 0;
  22576. this.wAng = 0;
  22577. this.name = url;
  22578. this.url = url;
  22579. this._noMipmap = noMipmap;
  22580. this._invertY = invertY;
  22581. this._samplingMode = samplingMode;
  22582. this._buffer = buffer;
  22583. this._deleteBuffer = deleteBuffer;
  22584. if (!url) {
  22585. return;
  22586. }
  22587. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  22588. var load = function () {
  22589. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  22590. _this.onLoadObservable.notifyObservers(true);
  22591. }
  22592. if (onLoad) {
  22593. onLoad();
  22594. }
  22595. };
  22596. if (!this._texture) {
  22597. if (!scene.useDelayedTextureLoading) {
  22598. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, load, onError, this._buffer);
  22599. if (deleteBuffer) {
  22600. delete this._buffer;
  22601. }
  22602. }
  22603. else {
  22604. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22605. this._delayedOnLoad = load;
  22606. this._delayedOnError = onError;
  22607. }
  22608. }
  22609. else {
  22610. if (this._texture.isReady) {
  22611. BABYLON.Tools.SetImmediate(function () { return load(); });
  22612. }
  22613. else {
  22614. this._texture.onLoadedCallbacks.push(load);
  22615. }
  22616. }
  22617. }
  22618. Object.defineProperty(Texture.prototype, "noMipmap", {
  22619. get: function () {
  22620. return this._noMipmap;
  22621. },
  22622. enumerable: true,
  22623. configurable: true
  22624. });
  22625. Texture.prototype.delayLoad = function () {
  22626. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22627. return;
  22628. }
  22629. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22630. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  22631. if (!this._texture) {
  22632. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  22633. if (this._deleteBuffer) {
  22634. delete this._buffer;
  22635. }
  22636. }
  22637. };
  22638. Texture.prototype.updateSamplingMode = function (samplingMode) {
  22639. if (!this._texture) {
  22640. return;
  22641. }
  22642. this._samplingMode = samplingMode;
  22643. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  22644. };
  22645. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  22646. x *= this.uScale;
  22647. y *= this.vScale;
  22648. x -= 0.5 * this.uScale;
  22649. y -= 0.5 * this.vScale;
  22650. z -= 0.5;
  22651. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  22652. t.x += 0.5 * this.uScale + this.uOffset;
  22653. t.y += 0.5 * this.vScale + this.vOffset;
  22654. t.z += 0.5;
  22655. };
  22656. Texture.prototype.getTextureMatrix = function () {
  22657. if (this.uOffset === this._cachedUOffset &&
  22658. this.vOffset === this._cachedVOffset &&
  22659. this.uScale === this._cachedUScale &&
  22660. this.vScale === this._cachedVScale &&
  22661. this.uAng === this._cachedUAng &&
  22662. this.vAng === this._cachedVAng &&
  22663. this.wAng === this._cachedWAng) {
  22664. return this._cachedTextureMatrix;
  22665. }
  22666. this._cachedUOffset = this.uOffset;
  22667. this._cachedVOffset = this.vOffset;
  22668. this._cachedUScale = this.uScale;
  22669. this._cachedVScale = this.vScale;
  22670. this._cachedUAng = this.uAng;
  22671. this._cachedVAng = this.vAng;
  22672. this._cachedWAng = this.wAng;
  22673. if (!this._cachedTextureMatrix) {
  22674. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22675. this._rowGenerationMatrix = new BABYLON.Matrix();
  22676. this._t0 = BABYLON.Vector3.Zero();
  22677. this._t1 = BABYLON.Vector3.Zero();
  22678. this._t2 = BABYLON.Vector3.Zero();
  22679. }
  22680. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22681. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22682. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22683. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22684. this._t1.subtractInPlace(this._t0);
  22685. this._t2.subtractInPlace(this._t0);
  22686. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22687. this._cachedTextureMatrix.m[0] = this._t1.x;
  22688. this._cachedTextureMatrix.m[1] = this._t1.y;
  22689. this._cachedTextureMatrix.m[2] = this._t1.z;
  22690. this._cachedTextureMatrix.m[4] = this._t2.x;
  22691. this._cachedTextureMatrix.m[5] = this._t2.y;
  22692. this._cachedTextureMatrix.m[6] = this._t2.z;
  22693. this._cachedTextureMatrix.m[8] = this._t0.x;
  22694. this._cachedTextureMatrix.m[9] = this._t0.y;
  22695. this._cachedTextureMatrix.m[10] = this._t0.z;
  22696. return this._cachedTextureMatrix;
  22697. };
  22698. Texture.prototype.getReflectionTextureMatrix = function () {
  22699. if (this.uOffset === this._cachedUOffset &&
  22700. this.vOffset === this._cachedVOffset &&
  22701. this.uScale === this._cachedUScale &&
  22702. this.vScale === this._cachedVScale &&
  22703. this.coordinatesMode === this._cachedCoordinatesMode) {
  22704. return this._cachedTextureMatrix;
  22705. }
  22706. if (!this._cachedTextureMatrix) {
  22707. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22708. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22709. }
  22710. this._cachedCoordinatesMode = this.coordinatesMode;
  22711. switch (this.coordinatesMode) {
  22712. case Texture.PLANAR_MODE:
  22713. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22714. this._cachedTextureMatrix[0] = this.uScale;
  22715. this._cachedTextureMatrix[5] = this.vScale;
  22716. this._cachedTextureMatrix[12] = this.uOffset;
  22717. this._cachedTextureMatrix[13] = this.vOffset;
  22718. break;
  22719. case Texture.PROJECTION_MODE:
  22720. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22721. this._projectionModeMatrix.m[0] = 0.5;
  22722. this._projectionModeMatrix.m[5] = -0.5;
  22723. this._projectionModeMatrix.m[10] = 0.0;
  22724. this._projectionModeMatrix.m[12] = 0.5;
  22725. this._projectionModeMatrix.m[13] = 0.5;
  22726. this._projectionModeMatrix.m[14] = 1.0;
  22727. this._projectionModeMatrix.m[15] = 1.0;
  22728. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22729. break;
  22730. default:
  22731. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22732. break;
  22733. }
  22734. return this._cachedTextureMatrix;
  22735. };
  22736. Texture.prototype.clone = function () {
  22737. var _this = this;
  22738. return BABYLON.SerializationHelper.Clone(function () {
  22739. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  22740. }, this);
  22741. };
  22742. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  22743. get: function () {
  22744. if (!this._onLoadObservarble) {
  22745. this._onLoadObservarble = new BABYLON.Observable();
  22746. }
  22747. return this._onLoadObservarble;
  22748. },
  22749. enumerable: true,
  22750. configurable: true
  22751. });
  22752. // Statics
  22753. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  22754. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22755. if (onLoad === void 0) { onLoad = null; }
  22756. if (onError === void 0) { onError = null; }
  22757. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  22758. };
  22759. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  22760. if (parsedTexture.isCube) {
  22761. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  22762. }
  22763. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  22764. return null;
  22765. }
  22766. var texture = BABYLON.SerializationHelper.Parse(function () {
  22767. if (parsedTexture.customType) {
  22768. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  22769. return customTexture.Parse(parsedTexture, scene, rootUrl);
  22770. }
  22771. else if (parsedTexture.mirrorPlane) {
  22772. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22773. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  22774. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  22775. return mirrorTexture;
  22776. }
  22777. else if (parsedTexture.isRenderTarget) {
  22778. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22779. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  22780. return renderTargetTexture;
  22781. }
  22782. else {
  22783. var texture;
  22784. if (parsedTexture.base64String) {
  22785. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  22786. }
  22787. else {
  22788. texture = new Texture(rootUrl + parsedTexture.name, scene);
  22789. }
  22790. return texture;
  22791. }
  22792. }, parsedTexture, scene);
  22793. // Animations
  22794. if (parsedTexture.animations) {
  22795. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22796. var parsedAnimation = parsedTexture.animations[animationIndex];
  22797. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22798. }
  22799. }
  22800. return texture;
  22801. };
  22802. // Constants
  22803. Texture.NEAREST_SAMPLINGMODE = 1;
  22804. Texture.BILINEAR_SAMPLINGMODE = 2;
  22805. Texture.TRILINEAR_SAMPLINGMODE = 3;
  22806. Texture.EXPLICIT_MODE = 0;
  22807. Texture.SPHERICAL_MODE = 1;
  22808. Texture.PLANAR_MODE = 2;
  22809. Texture.CUBIC_MODE = 3;
  22810. Texture.PROJECTION_MODE = 4;
  22811. Texture.SKYBOX_MODE = 5;
  22812. Texture.INVCUBIC_MODE = 6;
  22813. Texture.EQUIRECTANGULAR_MODE = 7;
  22814. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  22815. Texture.CLAMP_ADDRESSMODE = 0;
  22816. Texture.WRAP_ADDRESSMODE = 1;
  22817. Texture.MIRROR_ADDRESSMODE = 2;
  22818. __decorate([
  22819. BABYLON.serialize()
  22820. ], Texture.prototype, "url", void 0);
  22821. __decorate([
  22822. BABYLON.serialize()
  22823. ], Texture.prototype, "uOffset", void 0);
  22824. __decorate([
  22825. BABYLON.serialize()
  22826. ], Texture.prototype, "vOffset", void 0);
  22827. __decorate([
  22828. BABYLON.serialize()
  22829. ], Texture.prototype, "uScale", void 0);
  22830. __decorate([
  22831. BABYLON.serialize()
  22832. ], Texture.prototype, "vScale", void 0);
  22833. __decorate([
  22834. BABYLON.serialize()
  22835. ], Texture.prototype, "uAng", void 0);
  22836. __decorate([
  22837. BABYLON.serialize()
  22838. ], Texture.prototype, "vAng", void 0);
  22839. __decorate([
  22840. BABYLON.serialize()
  22841. ], Texture.prototype, "wAng", void 0);
  22842. return Texture;
  22843. })(BABYLON.BaseTexture);
  22844. BABYLON.Texture = Texture;
  22845. })(BABYLON || (BABYLON = {}));
  22846. var BABYLON;
  22847. (function (BABYLON) {
  22848. var CubeTexture = (function (_super) {
  22849. __extends(CubeTexture, _super);
  22850. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  22851. _super.call(this, scene);
  22852. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  22853. this.name = rootUrl;
  22854. this.url = rootUrl;
  22855. this._noMipmap = noMipmap;
  22856. this.hasAlpha = false;
  22857. if (!rootUrl && !files) {
  22858. return;
  22859. }
  22860. this._texture = this._getFromCache(rootUrl, noMipmap);
  22861. if (!files) {
  22862. if (!extensions) {
  22863. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  22864. }
  22865. files = [];
  22866. for (var index = 0; index < extensions.length; index++) {
  22867. files.push(rootUrl + extensions[index]);
  22868. }
  22869. this._extensions = extensions;
  22870. }
  22871. this._files = files;
  22872. if (!this._texture) {
  22873. if (!scene.useDelayedTextureLoading) {
  22874. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  22875. }
  22876. else {
  22877. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22878. }
  22879. }
  22880. this.isCube = true;
  22881. this._textureMatrix = BABYLON.Matrix.Identity();
  22882. }
  22883. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  22884. return new CubeTexture("", scene, null, noMipmap, files);
  22885. };
  22886. // Methods
  22887. CubeTexture.prototype.delayLoad = function () {
  22888. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22889. return;
  22890. }
  22891. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22892. this._texture = this._getFromCache(this.url, this._noMipmap);
  22893. if (!this._texture) {
  22894. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  22895. }
  22896. };
  22897. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  22898. return this._textureMatrix;
  22899. };
  22900. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  22901. var texture = BABYLON.SerializationHelper.Parse(function () {
  22902. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  22903. }, parsedTexture, scene);
  22904. // Animations
  22905. if (parsedTexture.animations) {
  22906. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22907. var parsedAnimation = parsedTexture.animations[animationIndex];
  22908. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22909. }
  22910. }
  22911. return texture;
  22912. };
  22913. CubeTexture.prototype.clone = function () {
  22914. var _this = this;
  22915. return BABYLON.SerializationHelper.Clone(function () {
  22916. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  22917. }, this);
  22918. };
  22919. return CubeTexture;
  22920. })(BABYLON.BaseTexture);
  22921. BABYLON.CubeTexture = CubeTexture;
  22922. })(BABYLON || (BABYLON = {}));
  22923. var BABYLON;
  22924. (function (BABYLON) {
  22925. var RenderTargetTexture = (function (_super) {
  22926. __extends(RenderTargetTexture, _super);
  22927. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  22928. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  22929. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22930. if (isCube === void 0) { isCube = false; }
  22931. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22932. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  22933. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  22934. _super.call(this, null, scene, !generateMipMaps);
  22935. this.isCube = isCube;
  22936. /**
  22937. * Use this list to define the list of mesh you want to render.
  22938. */
  22939. this.renderList = new Array();
  22940. this.renderParticles = true;
  22941. this.renderSprites = false;
  22942. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  22943. // Events
  22944. /**
  22945. * An event triggered when the texture is unbind.
  22946. * @type {BABYLON.Observable}
  22947. */
  22948. this.onAfterUnbindObservable = new BABYLON.Observable();
  22949. /**
  22950. * An event triggered before rendering the texture
  22951. * @type {BABYLON.Observable}
  22952. */
  22953. this.onBeforeRenderObservable = new BABYLON.Observable();
  22954. /**
  22955. * An event triggered after rendering the texture
  22956. * @type {BABYLON.Observable}
  22957. */
  22958. this.onAfterRenderObservable = new BABYLON.Observable();
  22959. /**
  22960. * An event triggered after the texture clear
  22961. * @type {BABYLON.Observable}
  22962. */
  22963. this.onClearObservable = new BABYLON.Observable();
  22964. this._currentRefreshId = -1;
  22965. this._refreshRate = 1;
  22966. this.name = name;
  22967. this.isRenderTarget = true;
  22968. this._size = size;
  22969. this._generateMipMaps = generateMipMaps;
  22970. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  22971. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  22972. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22973. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22974. }
  22975. if (isCube) {
  22976. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, {
  22977. generateMipMaps: generateMipMaps,
  22978. samplingMode: samplingMode,
  22979. generateDepthBuffer: generateDepthBuffer,
  22980. generateStencilBuffer: generateStencilBuffer
  22981. });
  22982. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  22983. this._textureMatrix = BABYLON.Matrix.Identity();
  22984. }
  22985. else {
  22986. this._texture = scene.getEngine().createRenderTargetTexture(size, {
  22987. generateMipMaps: generateMipMaps,
  22988. type: type,
  22989. samplingMode: samplingMode,
  22990. generateDepthBuffer: generateDepthBuffer,
  22991. generateStencilBuffer: generateStencilBuffer
  22992. });
  22993. }
  22994. // Rendering groups
  22995. this._renderingManager = new BABYLON.RenderingManager(scene);
  22996. }
  22997. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  22998. get: function () {
  22999. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  23000. },
  23001. enumerable: true,
  23002. configurable: true
  23003. });
  23004. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  23005. get: function () {
  23006. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  23007. },
  23008. enumerable: true,
  23009. configurable: true
  23010. });
  23011. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  23012. get: function () {
  23013. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  23014. },
  23015. enumerable: true,
  23016. configurable: true
  23017. });
  23018. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  23019. set: function (callback) {
  23020. if (this._onAfterUnbindObserver) {
  23021. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  23022. }
  23023. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  23024. },
  23025. enumerable: true,
  23026. configurable: true
  23027. });
  23028. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  23029. set: function (callback) {
  23030. if (this._onBeforeRenderObserver) {
  23031. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23032. }
  23033. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23034. },
  23035. enumerable: true,
  23036. configurable: true
  23037. });
  23038. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  23039. set: function (callback) {
  23040. if (this._onAfterRenderObserver) {
  23041. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  23042. }
  23043. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  23044. },
  23045. enumerable: true,
  23046. configurable: true
  23047. });
  23048. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  23049. set: function (callback) {
  23050. if (this._onClearObserver) {
  23051. this.onClearObservable.remove(this._onClearObserver);
  23052. }
  23053. this._onClearObserver = this.onClearObservable.add(callback);
  23054. },
  23055. enumerable: true,
  23056. configurable: true
  23057. });
  23058. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  23059. this._currentRefreshId = -1;
  23060. };
  23061. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  23062. get: function () {
  23063. return this._refreshRate;
  23064. },
  23065. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  23066. set: function (value) {
  23067. this._refreshRate = value;
  23068. this.resetRefreshCounter();
  23069. },
  23070. enumerable: true,
  23071. configurable: true
  23072. });
  23073. RenderTargetTexture.prototype._shouldRender = function () {
  23074. if (this._currentRefreshId === -1) {
  23075. this._currentRefreshId = 1;
  23076. return true;
  23077. }
  23078. if (this.refreshRate === this._currentRefreshId) {
  23079. this._currentRefreshId = 1;
  23080. return true;
  23081. }
  23082. this._currentRefreshId++;
  23083. return false;
  23084. };
  23085. RenderTargetTexture.prototype.isReady = function () {
  23086. if (!this.getScene().renderTargetsEnabled) {
  23087. return false;
  23088. }
  23089. return _super.prototype.isReady.call(this);
  23090. };
  23091. RenderTargetTexture.prototype.getRenderSize = function () {
  23092. return this._size;
  23093. };
  23094. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  23095. get: function () {
  23096. return true;
  23097. },
  23098. enumerable: true,
  23099. configurable: true
  23100. });
  23101. RenderTargetTexture.prototype.scale = function (ratio) {
  23102. var newSize = this._size * ratio;
  23103. this.resize(newSize, this._generateMipMaps);
  23104. };
  23105. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  23106. if (this.isCube) {
  23107. return this._textureMatrix;
  23108. }
  23109. return _super.prototype.getReflectionTextureMatrix.call(this);
  23110. };
  23111. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  23112. this.releaseInternalTexture();
  23113. if (this.isCube) {
  23114. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  23115. }
  23116. else {
  23117. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  23118. }
  23119. };
  23120. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  23121. var scene = this.getScene();
  23122. if (this.useCameraPostProcesses !== undefined) {
  23123. useCameraPostProcess = this.useCameraPostProcesses;
  23124. }
  23125. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  23126. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  23127. }
  23128. if (this._waitingRenderList) {
  23129. this.renderList = [];
  23130. for (var index = 0; index < this._waitingRenderList.length; index++) {
  23131. var id = this._waitingRenderList[index];
  23132. this.renderList.push(scene.getMeshByID(id));
  23133. }
  23134. delete this._waitingRenderList;
  23135. }
  23136. // Is predicate defined?
  23137. if (this.renderListPredicate) {
  23138. this.renderList.splice(0); // Clear previous renderList
  23139. var sceneMeshes = this.getScene().meshes;
  23140. for (var index = 0; index < sceneMeshes.length; index++) {
  23141. var mesh = sceneMeshes[index];
  23142. if (this.renderListPredicate(mesh)) {
  23143. this.renderList.push(mesh);
  23144. }
  23145. }
  23146. }
  23147. if (this.renderList && this.renderList.length === 0) {
  23148. return;
  23149. }
  23150. // Prepare renderingManager
  23151. this._renderingManager.reset();
  23152. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  23153. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  23154. var sceneRenderId = scene.getRenderId();
  23155. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  23156. var mesh = currentRenderList[meshIndex];
  23157. if (mesh) {
  23158. if (!mesh.isReady()) {
  23159. // Reset _currentRefreshId
  23160. this.resetRefreshCounter();
  23161. continue;
  23162. }
  23163. mesh._preActivateForIntermediateRendering(sceneRenderId);
  23164. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  23165. mesh._activate(sceneRenderId);
  23166. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  23167. var subMesh = mesh.subMeshes[subIndex];
  23168. scene._activeIndices.addCount(subMesh.indexCount, false);
  23169. this._renderingManager.dispatch(subMesh);
  23170. }
  23171. }
  23172. }
  23173. }
  23174. if (this.isCube) {
  23175. for (var face = 0; face < 6; face++) {
  23176. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  23177. scene.incrementRenderId();
  23178. scene.resetCachedMaterial();
  23179. }
  23180. }
  23181. else {
  23182. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  23183. }
  23184. this.onAfterUnbindObservable.notifyObservers(this);
  23185. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  23186. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  23187. }
  23188. scene.resetCachedMaterial();
  23189. };
  23190. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  23191. var scene = this.getScene();
  23192. var engine = scene.getEngine();
  23193. // Bind
  23194. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  23195. if (this.isCube) {
  23196. engine.bindFramebuffer(this._texture, faceIndex);
  23197. }
  23198. else {
  23199. engine.bindFramebuffer(this._texture);
  23200. }
  23201. }
  23202. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  23203. // Clear
  23204. if (this.onClearObservable.hasObservers()) {
  23205. this.onClearObservable.notifyObservers(engine);
  23206. }
  23207. else {
  23208. engine.clear(scene.clearColor, true, true, true);
  23209. }
  23210. if (!this._doNotChangeAspectRatio) {
  23211. scene.updateTransformMatrix(true);
  23212. }
  23213. // Render
  23214. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  23215. if (useCameraPostProcess) {
  23216. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  23217. }
  23218. if (!this._doNotChangeAspectRatio) {
  23219. scene.updateTransformMatrix(true);
  23220. }
  23221. this.onAfterRenderObservable.notifyObservers(faceIndex);
  23222. // Dump ?
  23223. if (dumpForDebug) {
  23224. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  23225. }
  23226. // Unbind
  23227. if (!this.isCube || faceIndex === 5) {
  23228. if (this.isCube) {
  23229. if (faceIndex === 5) {
  23230. engine.generateMipMapsForCubemap(this._texture);
  23231. }
  23232. }
  23233. engine.unBindFramebuffer(this._texture, this.isCube);
  23234. }
  23235. };
  23236. /**
  23237. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23238. * This allowed control for front to back rendering or reversly depending of the special needs.
  23239. *
  23240. * @param renderingGroupId The rendering group id corresponding to its index
  23241. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23242. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23243. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23244. */
  23245. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23246. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23247. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23248. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23249. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23250. };
  23251. /**
  23252. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23253. *
  23254. * @param renderingGroupId The rendering group id corresponding to its index
  23255. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23256. */
  23257. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  23258. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  23259. };
  23260. RenderTargetTexture.prototype.clone = function () {
  23261. var textureSize = this.getSize();
  23262. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23263. // Base texture
  23264. newTexture.hasAlpha = this.hasAlpha;
  23265. newTexture.level = this.level;
  23266. // RenderTarget Texture
  23267. newTexture.coordinatesMode = this.coordinatesMode;
  23268. newTexture.renderList = this.renderList.slice(0);
  23269. return newTexture;
  23270. };
  23271. RenderTargetTexture.prototype.serialize = function () {
  23272. if (!this.name) {
  23273. return null;
  23274. }
  23275. var serializationObject = _super.prototype.serialize.call(this);
  23276. serializationObject.renderTargetSize = this.getRenderSize();
  23277. serializationObject.renderList = [];
  23278. for (var index = 0; index < this.renderList.length; index++) {
  23279. serializationObject.renderList.push(this.renderList[index].id);
  23280. }
  23281. return serializationObject;
  23282. };
  23283. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  23284. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  23285. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  23286. return RenderTargetTexture;
  23287. })(BABYLON.Texture);
  23288. BABYLON.RenderTargetTexture = RenderTargetTexture;
  23289. })(BABYLON || (BABYLON = {}));
  23290. var BABYLON;
  23291. (function (BABYLON) {
  23292. var ProceduralTexture = (function (_super) {
  23293. __extends(ProceduralTexture, _super);
  23294. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  23295. if (generateMipMaps === void 0) { generateMipMaps = true; }
  23296. if (isCube === void 0) { isCube = false; }
  23297. _super.call(this, null, scene, !generateMipMaps);
  23298. this.isCube = isCube;
  23299. this.isEnabled = true;
  23300. this._currentRefreshId = -1;
  23301. this._refreshRate = 1;
  23302. this._vertexBuffers = {};
  23303. this._uniforms = new Array();
  23304. this._samplers = new Array();
  23305. this._textures = new Array();
  23306. this._floats = new Array();
  23307. this._floatsArrays = {};
  23308. this._colors3 = new Array();
  23309. this._colors4 = new Array();
  23310. this._vectors2 = new Array();
  23311. this._vectors3 = new Array();
  23312. this._matrices = new Array();
  23313. this._fallbackTextureUsed = false;
  23314. scene._proceduralTextures.push(this);
  23315. this.name = name;
  23316. this.isRenderTarget = true;
  23317. this._size = size;
  23318. this._generateMipMaps = generateMipMaps;
  23319. this.setFragment(fragment);
  23320. this._fallbackTexture = fallbackTexture;
  23321. var engine = scene.getEngine();
  23322. if (isCube) {
  23323. this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  23324. this.setFloat("face", 0);
  23325. }
  23326. else {
  23327. this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  23328. }
  23329. // VBO
  23330. var vertices = [];
  23331. vertices.push(1, 1);
  23332. vertices.push(-1, 1);
  23333. vertices.push(-1, -1);
  23334. vertices.push(1, -1);
  23335. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  23336. // Indices
  23337. var indices = [];
  23338. indices.push(0);
  23339. indices.push(1);
  23340. indices.push(2);
  23341. indices.push(0);
  23342. indices.push(2);
  23343. indices.push(3);
  23344. this._indexBuffer = engine.createIndexBuffer(indices);
  23345. }
  23346. ProceduralTexture.prototype.reset = function () {
  23347. if (this._effect === undefined) {
  23348. return;
  23349. }
  23350. var engine = this.getScene().getEngine();
  23351. engine._releaseEffect(this._effect);
  23352. };
  23353. ProceduralTexture.prototype.isReady = function () {
  23354. var _this = this;
  23355. var engine = this.getScene().getEngine();
  23356. var shaders;
  23357. if (!this._fragment) {
  23358. return false;
  23359. }
  23360. if (this._fallbackTextureUsed) {
  23361. return true;
  23362. }
  23363. if (this._fragment.fragmentElement !== undefined) {
  23364. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  23365. }
  23366. else {
  23367. shaders = { vertex: "procedural", fragment: this._fragment };
  23368. }
  23369. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  23370. _this.releaseInternalTexture();
  23371. if (_this._fallbackTexture) {
  23372. _this._texture = _this._fallbackTexture._texture;
  23373. _this._texture.references++;
  23374. }
  23375. _this._fallbackTextureUsed = true;
  23376. });
  23377. return this._effect.isReady();
  23378. };
  23379. ProceduralTexture.prototype.resetRefreshCounter = function () {
  23380. this._currentRefreshId = -1;
  23381. };
  23382. ProceduralTexture.prototype.setFragment = function (fragment) {
  23383. this._fragment = fragment;
  23384. };
  23385. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  23386. get: function () {
  23387. return this._refreshRate;
  23388. },
  23389. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  23390. set: function (value) {
  23391. this._refreshRate = value;
  23392. this.resetRefreshCounter();
  23393. },
  23394. enumerable: true,
  23395. configurable: true
  23396. });
  23397. ProceduralTexture.prototype._shouldRender = function () {
  23398. if (!this.isEnabled || !this.isReady() || !this._texture) {
  23399. return false;
  23400. }
  23401. if (this._fallbackTextureUsed) {
  23402. return false;
  23403. }
  23404. if (this._currentRefreshId === -1) {
  23405. this._currentRefreshId = 1;
  23406. return true;
  23407. }
  23408. if (this.refreshRate === this._currentRefreshId) {
  23409. this._currentRefreshId = 1;
  23410. return true;
  23411. }
  23412. this._currentRefreshId++;
  23413. return false;
  23414. };
  23415. ProceduralTexture.prototype.getRenderSize = function () {
  23416. return this._size;
  23417. };
  23418. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  23419. if (this._fallbackTextureUsed) {
  23420. return;
  23421. }
  23422. this.releaseInternalTexture();
  23423. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  23424. };
  23425. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  23426. if (this._uniforms.indexOf(uniformName) === -1) {
  23427. this._uniforms.push(uniformName);
  23428. }
  23429. };
  23430. ProceduralTexture.prototype.setTexture = function (name, texture) {
  23431. if (this._samplers.indexOf(name) === -1) {
  23432. this._samplers.push(name);
  23433. }
  23434. this._textures[name] = texture;
  23435. return this;
  23436. };
  23437. ProceduralTexture.prototype.setFloat = function (name, value) {
  23438. this._checkUniform(name);
  23439. this._floats[name] = value;
  23440. return this;
  23441. };
  23442. ProceduralTexture.prototype.setFloats = function (name, value) {
  23443. this._checkUniform(name);
  23444. this._floatsArrays[name] = value;
  23445. return this;
  23446. };
  23447. ProceduralTexture.prototype.setColor3 = function (name, value) {
  23448. this._checkUniform(name);
  23449. this._colors3[name] = value;
  23450. return this;
  23451. };
  23452. ProceduralTexture.prototype.setColor4 = function (name, value) {
  23453. this._checkUniform(name);
  23454. this._colors4[name] = value;
  23455. return this;
  23456. };
  23457. ProceduralTexture.prototype.setVector2 = function (name, value) {
  23458. this._checkUniform(name);
  23459. this._vectors2[name] = value;
  23460. return this;
  23461. };
  23462. ProceduralTexture.prototype.setVector3 = function (name, value) {
  23463. this._checkUniform(name);
  23464. this._vectors3[name] = value;
  23465. return this;
  23466. };
  23467. ProceduralTexture.prototype.setMatrix = function (name, value) {
  23468. this._checkUniform(name);
  23469. this._matrices[name] = value;
  23470. return this;
  23471. };
  23472. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  23473. var scene = this.getScene();
  23474. var engine = scene.getEngine();
  23475. // Render
  23476. engine.enableEffect(this._effect);
  23477. engine.setState(false);
  23478. // Texture
  23479. for (var name in this._textures) {
  23480. this._effect.setTexture(name, this._textures[name]);
  23481. }
  23482. // Float
  23483. for (name in this._floats) {
  23484. this._effect.setFloat(name, this._floats[name]);
  23485. }
  23486. // Floats
  23487. for (name in this._floatsArrays) {
  23488. this._effect.setArray(name, this._floatsArrays[name]);
  23489. }
  23490. // Color3
  23491. for (name in this._colors3) {
  23492. this._effect.setColor3(name, this._colors3[name]);
  23493. }
  23494. // Color4
  23495. for (name in this._colors4) {
  23496. var color = this._colors4[name];
  23497. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  23498. }
  23499. // Vector2
  23500. for (name in this._vectors2) {
  23501. this._effect.setVector2(name, this._vectors2[name]);
  23502. }
  23503. // Vector3
  23504. for (name in this._vectors3) {
  23505. this._effect.setVector3(name, this._vectors3[name]);
  23506. }
  23507. // Matrix
  23508. for (name in this._matrices) {
  23509. this._effect.setMatrix(name, this._matrices[name]);
  23510. }
  23511. // VBOs
  23512. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  23513. if (this.isCube) {
  23514. for (var face = 0; face < 6; face++) {
  23515. engine.bindFramebuffer(this._texture, face);
  23516. this._effect.setFloat("face", face);
  23517. // Clear
  23518. engine.clear(scene.clearColor, true, true, true);
  23519. // Draw order
  23520. engine.draw(true, 0, 6);
  23521. // Mipmaps
  23522. if (face === 5) {
  23523. engine.generateMipMapsForCubemap(this._texture);
  23524. }
  23525. }
  23526. }
  23527. else {
  23528. engine.bindFramebuffer(this._texture);
  23529. // Clear
  23530. engine.clear(scene.clearColor, true, true, true);
  23531. // Draw order
  23532. engine.draw(true, 0, 6);
  23533. }
  23534. // Unbind
  23535. engine.unBindFramebuffer(this._texture, this.isCube);
  23536. if (this.onGenerated) {
  23537. this.onGenerated();
  23538. }
  23539. };
  23540. ProceduralTexture.prototype.clone = function () {
  23541. var textureSize = this.getSize();
  23542. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  23543. // Base texture
  23544. newTexture.hasAlpha = this.hasAlpha;
  23545. newTexture.level = this.level;
  23546. // RenderTarget Texture
  23547. newTexture.coordinatesMode = this.coordinatesMode;
  23548. return newTexture;
  23549. };
  23550. ProceduralTexture.prototype.dispose = function () {
  23551. var index = this.getScene()._proceduralTextures.indexOf(this);
  23552. if (index >= 0) {
  23553. this.getScene()._proceduralTextures.splice(index, 1);
  23554. }
  23555. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  23556. if (vertexBuffer) {
  23557. vertexBuffer.dispose();
  23558. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  23559. }
  23560. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  23561. this._indexBuffer = null;
  23562. }
  23563. _super.prototype.dispose.call(this);
  23564. };
  23565. return ProceduralTexture;
  23566. })(BABYLON.Texture);
  23567. BABYLON.ProceduralTexture = ProceduralTexture;
  23568. })(BABYLON || (BABYLON = {}));
  23569. var BABYLON;
  23570. (function (BABYLON) {
  23571. var MirrorTexture = (function (_super) {
  23572. __extends(MirrorTexture, _super);
  23573. function MirrorTexture(name, size, scene, generateMipMaps) {
  23574. var _this = this;
  23575. _super.call(this, name, size, scene, generateMipMaps, true);
  23576. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  23577. this._transformMatrix = BABYLON.Matrix.Zero();
  23578. this._mirrorMatrix = BABYLON.Matrix.Zero();
  23579. this.onBeforeRenderObservable.add(function () {
  23580. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  23581. _this._savedViewMatrix = scene.getViewMatrix();
  23582. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  23583. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  23584. scene.clipPlane = _this.mirrorPlane;
  23585. scene.getEngine().cullBackFaces = false;
  23586. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  23587. });
  23588. this.onAfterRenderObservable.add(function () {
  23589. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  23590. scene.getEngine().cullBackFaces = true;
  23591. scene._mirroredCameraPosition = null;
  23592. delete scene.clipPlane;
  23593. });
  23594. }
  23595. MirrorTexture.prototype.clone = function () {
  23596. var textureSize = this.getSize();
  23597. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23598. // Base texture
  23599. newTexture.hasAlpha = this.hasAlpha;
  23600. newTexture.level = this.level;
  23601. // Mirror Texture
  23602. newTexture.mirrorPlane = this.mirrorPlane.clone();
  23603. newTexture.renderList = this.renderList.slice(0);
  23604. return newTexture;
  23605. };
  23606. MirrorTexture.prototype.serialize = function () {
  23607. if (!this.name) {
  23608. return null;
  23609. }
  23610. var serializationObject = _super.prototype.serialize.call(this);
  23611. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  23612. return serializationObject;
  23613. };
  23614. return MirrorTexture;
  23615. })(BABYLON.RenderTargetTexture);
  23616. BABYLON.MirrorTexture = MirrorTexture;
  23617. })(BABYLON || (BABYLON = {}));
  23618. var BABYLON;
  23619. (function (BABYLON) {
  23620. /**
  23621. * Creates a refraction texture used by refraction channel of the standard material.
  23622. * @param name the texture name
  23623. * @param size size of the underlying texture
  23624. * @param scene root scene
  23625. */
  23626. var RefractionTexture = (function (_super) {
  23627. __extends(RefractionTexture, _super);
  23628. function RefractionTexture(name, size, scene, generateMipMaps) {
  23629. var _this = this;
  23630. _super.call(this, name, size, scene, generateMipMaps, true);
  23631. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  23632. this.depth = 2.0;
  23633. this.onBeforeRenderObservable.add(function () {
  23634. scene.clipPlane = _this.refractionPlane;
  23635. });
  23636. this.onAfterRenderObservable.add(function () {
  23637. delete scene.clipPlane;
  23638. });
  23639. }
  23640. RefractionTexture.prototype.clone = function () {
  23641. var textureSize = this.getSize();
  23642. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23643. // Base texture
  23644. newTexture.hasAlpha = this.hasAlpha;
  23645. newTexture.level = this.level;
  23646. // Refraction Texture
  23647. newTexture.refractionPlane = this.refractionPlane.clone();
  23648. newTexture.renderList = this.renderList.slice(0);
  23649. newTexture.depth = this.depth;
  23650. return newTexture;
  23651. };
  23652. RefractionTexture.prototype.serialize = function () {
  23653. if (!this.name) {
  23654. return null;
  23655. }
  23656. var serializationObject = _super.prototype.serialize.call(this);
  23657. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  23658. serializationObject.depth = this.depth;
  23659. return serializationObject;
  23660. };
  23661. return RefractionTexture;
  23662. })(BABYLON.RenderTargetTexture);
  23663. BABYLON.RefractionTexture = RefractionTexture;
  23664. })(BABYLON || (BABYLON = {}));
  23665. var BABYLON;
  23666. (function (BABYLON) {
  23667. var DynamicTexture = (function (_super) {
  23668. __extends(DynamicTexture, _super);
  23669. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  23670. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23671. _super.call(this, null, scene, !generateMipMaps);
  23672. this.name = name;
  23673. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23674. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23675. this._generateMipMaps = generateMipMaps;
  23676. if (options.getContext) {
  23677. this._canvas = options;
  23678. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  23679. }
  23680. else {
  23681. this._canvas = document.createElement("canvas");
  23682. if (options.width) {
  23683. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  23684. }
  23685. else {
  23686. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  23687. }
  23688. }
  23689. var textureSize = this.getSize();
  23690. this._canvas.width = textureSize.width;
  23691. this._canvas.height = textureSize.height;
  23692. this._context = this._canvas.getContext("2d");
  23693. }
  23694. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  23695. get: function () {
  23696. return true;
  23697. },
  23698. enumerable: true,
  23699. configurable: true
  23700. });
  23701. DynamicTexture.prototype.scale = function (ratio) {
  23702. var textureSize = this.getSize();
  23703. textureSize.width *= ratio;
  23704. textureSize.height *= ratio;
  23705. this._canvas.width = textureSize.width;
  23706. this._canvas.height = textureSize.height;
  23707. this.releaseInternalTexture();
  23708. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  23709. };
  23710. DynamicTexture.prototype.getContext = function () {
  23711. return this._context;
  23712. };
  23713. DynamicTexture.prototype.clear = function () {
  23714. var size = this.getSize();
  23715. this._context.fillRect(0, 0, size.width, size.height);
  23716. };
  23717. DynamicTexture.prototype.update = function (invertY) {
  23718. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  23719. };
  23720. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  23721. if (update === void 0) { update = true; }
  23722. var size = this.getSize();
  23723. if (clearColor) {
  23724. this._context.fillStyle = clearColor;
  23725. this._context.fillRect(0, 0, size.width, size.height);
  23726. }
  23727. this._context.font = font;
  23728. if (x === null) {
  23729. var textSize = this._context.measureText(text);
  23730. x = (size.width - textSize.width) / 2;
  23731. }
  23732. this._context.fillStyle = color;
  23733. this._context.fillText(text, x, y);
  23734. if (update) {
  23735. this.update(invertY);
  23736. }
  23737. };
  23738. DynamicTexture.prototype.clone = function () {
  23739. var textureSize = this.getSize();
  23740. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  23741. // Base texture
  23742. newTexture.hasAlpha = this.hasAlpha;
  23743. newTexture.level = this.level;
  23744. // Dynamic Texture
  23745. newTexture.wrapU = this.wrapU;
  23746. newTexture.wrapV = this.wrapV;
  23747. return newTexture;
  23748. };
  23749. return DynamicTexture;
  23750. })(BABYLON.Texture);
  23751. BABYLON.DynamicTexture = DynamicTexture;
  23752. })(BABYLON || (BABYLON = {}));
  23753. var BABYLON;
  23754. (function (BABYLON) {
  23755. var VideoTexture = (function (_super) {
  23756. __extends(VideoTexture, _super);
  23757. /**
  23758. * Creates a video texture.
  23759. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  23760. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  23761. * @param {BABYLON.Scene} scene is obviously the current scene.
  23762. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  23763. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  23764. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  23765. */
  23766. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  23767. var _this = this;
  23768. if (generateMipMaps === void 0) { generateMipMaps = false; }
  23769. if (invertY === void 0) { invertY = false; }
  23770. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23771. _super.call(this, null, scene, !generateMipMaps, invertY);
  23772. this._autoLaunch = true;
  23773. var urls;
  23774. this.name = name;
  23775. if (urlsOrVideo instanceof HTMLVideoElement) {
  23776. this.video = urlsOrVideo;
  23777. }
  23778. else {
  23779. urls = urlsOrVideo;
  23780. this.video = document.createElement("video");
  23781. this.video.autoplay = false;
  23782. this.video.loop = true;
  23783. }
  23784. this._generateMipMaps = generateMipMaps;
  23785. this._samplingMode = samplingMode;
  23786. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  23787. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23788. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23789. }
  23790. else {
  23791. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23792. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23793. this._generateMipMaps = false;
  23794. }
  23795. if (urls) {
  23796. this.video.addEventListener("canplaythrough", function () {
  23797. _this._createTexture();
  23798. });
  23799. urls.forEach(function (url) {
  23800. var source = document.createElement("source");
  23801. source.src = url;
  23802. _this.video.appendChild(source);
  23803. });
  23804. }
  23805. else {
  23806. this._createTexture();
  23807. }
  23808. this._lastUpdate = BABYLON.Tools.Now;
  23809. }
  23810. VideoTexture.prototype._createTexture = function () {
  23811. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  23812. this._texture.isReady = true;
  23813. };
  23814. VideoTexture.prototype.update = function () {
  23815. if (this._autoLaunch) {
  23816. this._autoLaunch = false;
  23817. this.video.play();
  23818. }
  23819. var now = BABYLON.Tools.Now;
  23820. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  23821. return false;
  23822. }
  23823. this._lastUpdate = now;
  23824. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  23825. return true;
  23826. };
  23827. return VideoTexture;
  23828. })(BABYLON.Texture);
  23829. BABYLON.VideoTexture = VideoTexture;
  23830. })(BABYLON || (BABYLON = {}));
  23831. var BABYLON;
  23832. (function (BABYLON) {
  23833. var CustomProceduralTexture = (function (_super) {
  23834. __extends(CustomProceduralTexture, _super);
  23835. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  23836. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  23837. this._animate = true;
  23838. this._time = 0;
  23839. this._texturePath = texturePath;
  23840. //Try to load json
  23841. this.loadJson(texturePath);
  23842. this.refreshRate = 1;
  23843. }
  23844. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  23845. var _this = this;
  23846. var that = this;
  23847. function noConfigFile() {
  23848. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  23849. try {
  23850. that.setFragment(that._texturePath);
  23851. }
  23852. catch (ex) {
  23853. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  23854. }
  23855. }
  23856. var configFileUrl = jsonUrl + "/config.json";
  23857. var xhr = new XMLHttpRequest();
  23858. xhr.open("GET", configFileUrl, true);
  23859. xhr.addEventListener("load", function () {
  23860. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  23861. try {
  23862. _this._config = JSON.parse(xhr.response);
  23863. _this.updateShaderUniforms();
  23864. _this.updateTextures();
  23865. _this.setFragment(_this._texturePath + "/custom");
  23866. _this._animate = _this._config.animate;
  23867. _this.refreshRate = _this._config.refreshrate;
  23868. }
  23869. catch (ex) {
  23870. noConfigFile();
  23871. }
  23872. }
  23873. else {
  23874. noConfigFile();
  23875. }
  23876. }, false);
  23877. xhr.addEventListener("error", function () {
  23878. noConfigFile();
  23879. }, false);
  23880. try {
  23881. xhr.send();
  23882. }
  23883. catch (ex) {
  23884. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  23885. }
  23886. };
  23887. CustomProceduralTexture.prototype.isReady = function () {
  23888. if (!_super.prototype.isReady.call(this)) {
  23889. return false;
  23890. }
  23891. for (var name in this._textures) {
  23892. var texture = this._textures[name];
  23893. if (!texture.isReady()) {
  23894. return false;
  23895. }
  23896. }
  23897. return true;
  23898. };
  23899. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  23900. if (this._animate) {
  23901. this._time += this.getScene().getAnimationRatio() * 0.03;
  23902. this.updateShaderUniforms();
  23903. }
  23904. _super.prototype.render.call(this, useCameraPostProcess);
  23905. };
  23906. CustomProceduralTexture.prototype.updateTextures = function () {
  23907. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  23908. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  23909. }
  23910. };
  23911. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  23912. if (this._config) {
  23913. for (var j = 0; j < this._config.uniforms.length; j++) {
  23914. var uniform = this._config.uniforms[j];
  23915. switch (uniform.type) {
  23916. case "float":
  23917. this.setFloat(uniform.name, uniform.value);
  23918. break;
  23919. case "color3":
  23920. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  23921. break;
  23922. case "color4":
  23923. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  23924. break;
  23925. case "vector2":
  23926. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  23927. break;
  23928. case "vector3":
  23929. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  23930. break;
  23931. }
  23932. }
  23933. }
  23934. this.setFloat("time", this._time);
  23935. };
  23936. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  23937. get: function () {
  23938. return this._animate;
  23939. },
  23940. set: function (value) {
  23941. this._animate = value;
  23942. },
  23943. enumerable: true,
  23944. configurable: true
  23945. });
  23946. return CustomProceduralTexture;
  23947. })(BABYLON.ProceduralTexture);
  23948. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  23949. })(BABYLON || (BABYLON = {}));
  23950. var BABYLON;
  23951. (function (BABYLON) {
  23952. var EffectFallbacks = (function () {
  23953. function EffectFallbacks() {
  23954. this._defines = {};
  23955. this._currentRank = 32;
  23956. this._maxRank = -1;
  23957. }
  23958. EffectFallbacks.prototype.addFallback = function (rank, define) {
  23959. if (!this._defines[rank]) {
  23960. if (rank < this._currentRank) {
  23961. this._currentRank = rank;
  23962. }
  23963. if (rank > this._maxRank) {
  23964. this._maxRank = rank;
  23965. }
  23966. this._defines[rank] = new Array();
  23967. }
  23968. this._defines[rank].push(define);
  23969. };
  23970. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  23971. this._meshRank = rank;
  23972. this._mesh = mesh;
  23973. if (rank > this._maxRank) {
  23974. this._maxRank = rank;
  23975. }
  23976. };
  23977. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  23978. get: function () {
  23979. return this._currentRank <= this._maxRank;
  23980. },
  23981. enumerable: true,
  23982. configurable: true
  23983. });
  23984. EffectFallbacks.prototype.reduce = function (currentDefines) {
  23985. var currentFallbacks = this._defines[this._currentRank];
  23986. for (var index = 0; index < currentFallbacks.length; index++) {
  23987. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  23988. }
  23989. if (this._mesh && this._currentRank === this._meshRank) {
  23990. this._mesh.computeBonesUsingShaders = false;
  23991. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  23992. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  23993. }
  23994. this._currentRank++;
  23995. return currentDefines;
  23996. };
  23997. return EffectFallbacks;
  23998. })();
  23999. BABYLON.EffectFallbacks = EffectFallbacks;
  24000. var Effect = (function () {
  24001. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24002. var _this = this;
  24003. this._isReady = false;
  24004. this._compilationError = "";
  24005. this._valueCache = {};
  24006. this._engine = engine;
  24007. this.name = baseName;
  24008. this.defines = defines;
  24009. this._uniformsNames = uniformsNames.concat(samplers);
  24010. this._samplers = samplers;
  24011. this._attributesNames = attributesNames;
  24012. this.onError = onError;
  24013. this.onCompiled = onCompiled;
  24014. this._indexParameters = indexParameters;
  24015. var vertexSource;
  24016. var fragmentSource;
  24017. if (baseName.vertexElement) {
  24018. vertexSource = document.getElementById(baseName.vertexElement);
  24019. if (!vertexSource) {
  24020. vertexSource = baseName.vertexElement;
  24021. }
  24022. }
  24023. else {
  24024. vertexSource = baseName.vertex || baseName;
  24025. }
  24026. if (baseName.fragmentElement) {
  24027. fragmentSource = document.getElementById(baseName.fragmentElement);
  24028. if (!fragmentSource) {
  24029. fragmentSource = baseName.fragmentElement;
  24030. }
  24031. }
  24032. else {
  24033. fragmentSource = baseName.fragment || baseName;
  24034. }
  24035. this._loadVertexShader(vertexSource, function (vertexCode) {
  24036. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24037. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24038. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24039. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  24040. });
  24041. });
  24042. });
  24043. });
  24044. }
  24045. // Properties
  24046. Effect.prototype.isReady = function () {
  24047. return this._isReady;
  24048. };
  24049. Effect.prototype.getProgram = function () {
  24050. return this._program;
  24051. };
  24052. Effect.prototype.getAttributesNames = function () {
  24053. return this._attributesNames;
  24054. };
  24055. Effect.prototype.getAttributeLocation = function (index) {
  24056. return this._attributes[index];
  24057. };
  24058. Effect.prototype.getAttributeLocationByName = function (name) {
  24059. var index = this._attributesNames.indexOf(name);
  24060. return this._attributes[index];
  24061. };
  24062. Effect.prototype.getAttributesCount = function () {
  24063. return this._attributes.length;
  24064. };
  24065. Effect.prototype.getUniformIndex = function (uniformName) {
  24066. return this._uniformsNames.indexOf(uniformName);
  24067. };
  24068. Effect.prototype.getUniform = function (uniformName) {
  24069. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24070. };
  24071. Effect.prototype.getSamplers = function () {
  24072. return this._samplers;
  24073. };
  24074. Effect.prototype.getCompilationError = function () {
  24075. return this._compilationError;
  24076. };
  24077. // Methods
  24078. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24079. // DOM element ?
  24080. if (vertex instanceof HTMLElement) {
  24081. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24082. callback(vertexCode);
  24083. return;
  24084. }
  24085. // Is in local store ?
  24086. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24087. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24088. return;
  24089. }
  24090. var vertexShaderUrl;
  24091. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24092. vertexShaderUrl = vertex;
  24093. }
  24094. else {
  24095. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24096. }
  24097. // Vertex shader
  24098. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24099. };
  24100. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24101. // DOM element ?
  24102. if (fragment instanceof HTMLElement) {
  24103. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24104. callback(fragmentCode);
  24105. return;
  24106. }
  24107. // Is in local store ?
  24108. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24109. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24110. return;
  24111. }
  24112. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24113. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24114. return;
  24115. }
  24116. var fragmentShaderUrl;
  24117. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24118. fragmentShaderUrl = fragment;
  24119. }
  24120. else {
  24121. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24122. }
  24123. // Fragment shader
  24124. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24125. };
  24126. Effect.prototype._dumpShadersName = function () {
  24127. if (this.name.vertexElement) {
  24128. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  24129. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  24130. }
  24131. else if (this.name.vertex) {
  24132. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  24133. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  24134. }
  24135. else {
  24136. BABYLON.Tools.Error("Vertex shader:" + this.name);
  24137. BABYLON.Tools.Error("Fragment shader:" + this.name);
  24138. }
  24139. };
  24140. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24141. var _this = this;
  24142. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24143. var match = regex.exec(sourceCode);
  24144. var returnValue = new String(sourceCode);
  24145. while (match != null) {
  24146. var includeFile = match[1];
  24147. if (Effect.IncludesShadersStore[includeFile]) {
  24148. // Substitution
  24149. var includeContent = Effect.IncludesShadersStore[includeFile];
  24150. if (match[2]) {
  24151. var splits = match[3].split(",");
  24152. for (var index = 0; index < splits.length; index += 2) {
  24153. var source = new RegExp(splits[index], "g");
  24154. var dest = splits[index + 1];
  24155. includeContent = includeContent.replace(source, dest);
  24156. }
  24157. }
  24158. if (match[4]) {
  24159. var indexString = match[5];
  24160. if (indexString.indexOf("..") !== -1) {
  24161. var indexSplits = indexString.split("..");
  24162. var minIndex = parseInt(indexSplits[0]);
  24163. var maxIndex = parseInt(indexSplits[1]);
  24164. var sourceIncludeContent = includeContent.slice(0);
  24165. includeContent = "";
  24166. if (isNaN(maxIndex)) {
  24167. maxIndex = this._indexParameters[indexSplits[1]];
  24168. }
  24169. for (var i = minIndex; i <= maxIndex; i++) {
  24170. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  24171. }
  24172. }
  24173. else {
  24174. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24175. }
  24176. }
  24177. // Replace
  24178. returnValue = returnValue.replace(match[0], includeContent);
  24179. }
  24180. else {
  24181. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24182. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24183. Effect.IncludesShadersStore[includeFile] = fileContent;
  24184. _this._processIncludes(returnValue, callback);
  24185. });
  24186. return;
  24187. }
  24188. match = regex.exec(sourceCode);
  24189. }
  24190. callback(returnValue);
  24191. };
  24192. Effect.prototype._processPrecision = function (source) {
  24193. if (source.indexOf("precision highp float") === -1) {
  24194. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24195. source = "precision mediump float;\n" + source;
  24196. }
  24197. else {
  24198. source = "precision highp float;\n" + source;
  24199. }
  24200. }
  24201. else {
  24202. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24203. source = source.replace("precision highp float", "precision mediump float");
  24204. }
  24205. }
  24206. return source;
  24207. };
  24208. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  24209. try {
  24210. var engine = this._engine;
  24211. // Precision
  24212. vertexSourceCode = this._processPrecision(vertexSourceCode);
  24213. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  24214. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  24215. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24216. this._attributes = engine.getAttributes(this._program, attributesNames);
  24217. var index;
  24218. for (index = 0; index < this._samplers.length; index++) {
  24219. var sampler = this.getUniform(this._samplers[index]);
  24220. if (sampler == null) {
  24221. this._samplers.splice(index, 1);
  24222. index--;
  24223. }
  24224. }
  24225. engine.bindSamplers(this);
  24226. this._isReady = true;
  24227. if (this.onCompiled) {
  24228. this.onCompiled(this);
  24229. }
  24230. }
  24231. catch (e) {
  24232. // Let's go through fallbacks then
  24233. if (fallbacks && fallbacks.isMoreFallbacks) {
  24234. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  24235. this._dumpShadersName();
  24236. defines = fallbacks.reduce(defines);
  24237. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  24238. }
  24239. else {
  24240. BABYLON.Tools.Error("Unable to compile effect: ");
  24241. this._dumpShadersName();
  24242. BABYLON.Tools.Error("Defines: " + defines);
  24243. BABYLON.Tools.Error("Error: " + e.message);
  24244. this._compilationError = e.message;
  24245. if (this.onError) {
  24246. this.onError(this, this._compilationError);
  24247. }
  24248. }
  24249. }
  24250. };
  24251. Object.defineProperty(Effect.prototype, "isSupported", {
  24252. get: function () {
  24253. return this._compilationError === "";
  24254. },
  24255. enumerable: true,
  24256. configurable: true
  24257. });
  24258. Effect.prototype._bindTexture = function (channel, texture) {
  24259. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  24260. };
  24261. Effect.prototype.setTexture = function (channel, texture) {
  24262. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  24263. };
  24264. Effect.prototype.setTextureArray = function (channel, textures) {
  24265. if (this._samplers.indexOf(channel + "Ex") === -1) {
  24266. var initialPos = this._samplers.indexOf(channel);
  24267. for (var index = 1; index < textures.length; index++) {
  24268. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  24269. }
  24270. }
  24271. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  24272. };
  24273. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  24274. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  24275. };
  24276. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  24277. var changed = false;
  24278. var cache = this._valueCache[uniformName];
  24279. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  24280. changed = true;
  24281. cache = new BABYLON.Matrix();
  24282. }
  24283. var tm = cache.m;
  24284. var om = matrix.m;
  24285. for (var index = 0; index < 16; index++) {
  24286. if (tm[index] !== om[index]) {
  24287. tm[index] = om[index];
  24288. changed = true;
  24289. }
  24290. }
  24291. this._valueCache[uniformName] = cache;
  24292. return changed;
  24293. };
  24294. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  24295. var cache = this._valueCache[uniformName];
  24296. if (!cache) {
  24297. cache = [x, y];
  24298. this._valueCache[uniformName] = cache;
  24299. return true;
  24300. }
  24301. var changed = false;
  24302. if (cache[0] !== x) {
  24303. cache[0] = x;
  24304. changed = true;
  24305. }
  24306. if (cache[1] !== y) {
  24307. cache[1] = y;
  24308. changed = true;
  24309. }
  24310. return changed;
  24311. };
  24312. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24313. var cache = this._valueCache[uniformName];
  24314. if (!cache) {
  24315. cache = [x, y, z];
  24316. this._valueCache[uniformName] = cache;
  24317. return true;
  24318. }
  24319. var changed = false;
  24320. if (cache[0] !== x) {
  24321. cache[0] = x;
  24322. changed = true;
  24323. }
  24324. if (cache[1] !== y) {
  24325. cache[1] = y;
  24326. changed = true;
  24327. }
  24328. if (cache[2] !== z) {
  24329. cache[2] = z;
  24330. changed = true;
  24331. }
  24332. return changed;
  24333. };
  24334. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24335. var cache = this._valueCache[uniformName];
  24336. if (!cache) {
  24337. cache = [x, y, z, w];
  24338. this._valueCache[uniformName] = cache;
  24339. return true;
  24340. }
  24341. var changed = false;
  24342. if (cache[0] !== x) {
  24343. cache[0] = x;
  24344. changed = true;
  24345. }
  24346. if (cache[1] !== y) {
  24347. cache[1] = y;
  24348. changed = true;
  24349. }
  24350. if (cache[2] !== z) {
  24351. cache[2] = z;
  24352. changed = true;
  24353. }
  24354. if (cache[3] !== w) {
  24355. cache[3] = w;
  24356. changed = true;
  24357. }
  24358. return changed;
  24359. };
  24360. Effect.prototype.setIntArray = function (uniformName, array) {
  24361. this._valueCache[uniformName] = null;
  24362. this._engine.setIntArray(this.getUniform(uniformName), array);
  24363. return this;
  24364. };
  24365. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24366. this._valueCache[uniformName] = null;
  24367. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24368. return this;
  24369. };
  24370. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24371. this._valueCache[uniformName] = null;
  24372. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24373. return this;
  24374. };
  24375. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24376. this._valueCache[uniformName] = null;
  24377. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24378. return this;
  24379. };
  24380. Effect.prototype.setFloatArray = function (uniformName, array) {
  24381. this._valueCache[uniformName] = null;
  24382. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24383. return this;
  24384. };
  24385. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24386. this._valueCache[uniformName] = null;
  24387. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24388. return this;
  24389. };
  24390. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24391. this._valueCache[uniformName] = null;
  24392. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24393. return this;
  24394. };
  24395. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24396. this._valueCache[uniformName] = null;
  24397. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24398. return this;
  24399. };
  24400. Effect.prototype.setArray = function (uniformName, array) {
  24401. this._valueCache[uniformName] = null;
  24402. this._engine.setArray(this.getUniform(uniformName), array);
  24403. return this;
  24404. };
  24405. Effect.prototype.setArray2 = function (uniformName, array) {
  24406. this._valueCache[uniformName] = null;
  24407. this._engine.setArray2(this.getUniform(uniformName), array);
  24408. return this;
  24409. };
  24410. Effect.prototype.setArray3 = function (uniformName, array) {
  24411. this._valueCache[uniformName] = null;
  24412. this._engine.setArray3(this.getUniform(uniformName), array);
  24413. return this;
  24414. };
  24415. Effect.prototype.setArray4 = function (uniformName, array) {
  24416. this._valueCache[uniformName] = null;
  24417. this._engine.setArray4(this.getUniform(uniformName), array);
  24418. return this;
  24419. };
  24420. Effect.prototype.setMatrices = function (uniformName, matrices) {
  24421. this._valueCache[uniformName] = null;
  24422. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  24423. return this;
  24424. };
  24425. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24426. if (this._cacheMatrix(uniformName, matrix)) {
  24427. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24428. }
  24429. return this;
  24430. };
  24431. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24432. this._valueCache[uniformName] = null;
  24433. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24434. return this;
  24435. };
  24436. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  24437. this._valueCache[uniformName] = null;
  24438. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  24439. return this;
  24440. };
  24441. Effect.prototype.setFloat = function (uniformName, value) {
  24442. var cache = this._valueCache[uniformName];
  24443. if (cache !== undefined && cache === value)
  24444. return this;
  24445. this._valueCache[uniformName] = value;
  24446. this._engine.setFloat(this.getUniform(uniformName), value);
  24447. return this;
  24448. };
  24449. Effect.prototype.setBool = function (uniformName, bool) {
  24450. var cache = this._valueCache[uniformName];
  24451. if (cache !== undefined && cache === bool)
  24452. return this;
  24453. this._valueCache[uniformName] = bool;
  24454. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24455. return this;
  24456. };
  24457. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24458. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24459. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24460. }
  24461. return this;
  24462. };
  24463. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24464. if (this._cacheFloat2(uniformName, x, y)) {
  24465. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24466. }
  24467. return this;
  24468. };
  24469. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24470. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24471. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24472. }
  24473. return this;
  24474. };
  24475. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24476. if (this._cacheFloat3(uniformName, x, y, z)) {
  24477. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24478. }
  24479. return this;
  24480. };
  24481. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24482. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24483. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24484. }
  24485. return this;
  24486. };
  24487. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24488. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24489. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24490. }
  24491. return this;
  24492. };
  24493. Effect.prototype.setColor3 = function (uniformName, color3) {
  24494. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24495. this._engine.setColor3(this.getUniform(uniformName), color3);
  24496. }
  24497. return this;
  24498. };
  24499. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24500. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24501. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  24502. }
  24503. return this;
  24504. };
  24505. // Statics
  24506. Effect.ShadersStore = {};
  24507. Effect.IncludesShadersStore = {};
  24508. return Effect;
  24509. })();
  24510. BABYLON.Effect = Effect;
  24511. })(BABYLON || (BABYLON = {}));
  24512. var BABYLON;
  24513. (function (BABYLON) {
  24514. var MaterialHelper = (function () {
  24515. function MaterialHelper() {
  24516. }
  24517. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  24518. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24519. var lightIndex = 0;
  24520. var needNormals = false;
  24521. var needRebuild = false;
  24522. var needShadows = false;
  24523. var lightmapMode = false;
  24524. for (var index = 0; index < scene.lights.length; index++) {
  24525. var light = scene.lights[index];
  24526. if (!light.isEnabled()) {
  24527. continue;
  24528. }
  24529. // Excluded check
  24530. if (light._excludedMeshesIds.length > 0) {
  24531. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  24532. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  24533. if (excludedMesh) {
  24534. light.excludedMeshes.push(excludedMesh);
  24535. }
  24536. }
  24537. light._excludedMeshesIds = [];
  24538. }
  24539. // Included check
  24540. if (light._includedOnlyMeshesIds.length > 0) {
  24541. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  24542. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  24543. if (includedOnlyMesh) {
  24544. light.includedOnlyMeshes.push(includedOnlyMesh);
  24545. }
  24546. }
  24547. light._includedOnlyMeshesIds = [];
  24548. }
  24549. if (!light.canAffectMesh(mesh)) {
  24550. continue;
  24551. }
  24552. needNormals = true;
  24553. if (defines["LIGHT" + lightIndex] === undefined) {
  24554. needRebuild = true;
  24555. }
  24556. defines["LIGHT" + lightIndex] = true;
  24557. var type;
  24558. if (light instanceof BABYLON.SpotLight) {
  24559. type = "SPOTLIGHT" + lightIndex;
  24560. }
  24561. else if (light instanceof BABYLON.HemisphericLight) {
  24562. type = "HEMILIGHT" + lightIndex;
  24563. }
  24564. else if (light instanceof BABYLON.PointLight) {
  24565. type = "POINTLIGHT" + lightIndex;
  24566. }
  24567. else {
  24568. type = "DIRLIGHT" + lightIndex;
  24569. }
  24570. if (defines[type] === undefined) {
  24571. needRebuild = true;
  24572. }
  24573. defines[type] = true;
  24574. // Specular
  24575. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  24576. defines["SPECULARTERM"] = true;
  24577. }
  24578. // Shadows
  24579. if (scene.shadowsEnabled) {
  24580. var shadowGenerator = light.getShadowGenerator();
  24581. if (mesh && mesh.receiveShadows && shadowGenerator) {
  24582. if (defines["SHADOW" + lightIndex] === undefined) {
  24583. needRebuild = true;
  24584. }
  24585. defines["SHADOW" + lightIndex] = true;
  24586. defines["SHADOWS"] = true;
  24587. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  24588. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  24589. needRebuild = true;
  24590. }
  24591. defines["SHADOWVSM" + lightIndex] = true;
  24592. }
  24593. if (shadowGenerator.usePoissonSampling) {
  24594. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  24595. needRebuild = true;
  24596. }
  24597. defines["SHADOWPCF" + lightIndex] = true;
  24598. }
  24599. needShadows = true;
  24600. }
  24601. }
  24602. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  24603. lightmapMode = true;
  24604. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  24605. needRebuild = true;
  24606. }
  24607. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  24608. needRebuild = true;
  24609. }
  24610. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  24611. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  24612. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  24613. }
  24614. }
  24615. lightIndex++;
  24616. if (lightIndex === maxSimultaneousLights)
  24617. break;
  24618. }
  24619. var caps = scene.getEngine().getCaps();
  24620. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  24621. if (defines["SHADOWFULLFLOAT"] === undefined) {
  24622. needRebuild = true;
  24623. }
  24624. defines["SHADOWFULLFLOAT"] = true;
  24625. }
  24626. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  24627. needRebuild = true;
  24628. }
  24629. if (lightmapMode) {
  24630. defines["LIGHTMAPEXCLUDED"] = true;
  24631. }
  24632. if (needRebuild) {
  24633. defines.rebuild();
  24634. }
  24635. return needNormals;
  24636. };
  24637. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  24638. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24639. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24640. if (!defines["LIGHT" + lightIndex]) {
  24641. break;
  24642. }
  24643. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  24644. samplersList.push("shadowSampler" + lightIndex);
  24645. }
  24646. };
  24647. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  24648. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24649. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24650. if (!defines["LIGHT" + lightIndex]) {
  24651. break;
  24652. }
  24653. if (lightIndex > 0) {
  24654. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  24655. }
  24656. if (defines["SHADOW" + lightIndex]) {
  24657. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  24658. }
  24659. if (defines["SHADOWPCF" + lightIndex]) {
  24660. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  24661. }
  24662. if (defines["SHADOWVSM" + lightIndex]) {
  24663. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  24664. }
  24665. }
  24666. };
  24667. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  24668. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  24669. fallbacks.addCPUSkinningFallback(0, mesh);
  24670. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24671. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24672. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  24673. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  24674. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  24675. }
  24676. }
  24677. };
  24678. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  24679. if (defines["INSTANCES"]) {
  24680. attribs.push("world0");
  24681. attribs.push("world1");
  24682. attribs.push("world2");
  24683. attribs.push("world3");
  24684. }
  24685. };
  24686. // Bindings
  24687. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  24688. var shadowGenerator = light.getShadowGenerator();
  24689. if (mesh.receiveShadows && shadowGenerator) {
  24690. if (!light.needCube()) {
  24691. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  24692. }
  24693. else {
  24694. if (!depthValuesAlreadySet) {
  24695. depthValuesAlreadySet = true;
  24696. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  24697. }
  24698. }
  24699. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  24700. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  24701. }
  24702. return depthValuesAlreadySet;
  24703. };
  24704. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  24705. if (light instanceof BABYLON.PointLight) {
  24706. // Point Light
  24707. light.transferToEffect(effect, "vLightData" + lightIndex);
  24708. }
  24709. else if (light instanceof BABYLON.DirectionalLight) {
  24710. // Directional Light
  24711. light.transferToEffect(effect, "vLightData" + lightIndex);
  24712. }
  24713. else if (light instanceof BABYLON.SpotLight) {
  24714. // Spot Light
  24715. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  24716. }
  24717. else if (light instanceof BABYLON.HemisphericLight) {
  24718. // Hemispheric Light
  24719. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  24720. }
  24721. };
  24722. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  24723. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24724. var lightIndex = 0;
  24725. var depthValuesAlreadySet = false;
  24726. for (var index = 0; index < scene.lights.length; index++) {
  24727. var light = scene.lights[index];
  24728. if (!light.isEnabled()) {
  24729. continue;
  24730. }
  24731. if (!light.canAffectMesh(mesh)) {
  24732. continue;
  24733. }
  24734. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  24735. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  24736. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  24737. if (defines["SPECULARTERM"]) {
  24738. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  24739. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  24740. }
  24741. // Shadows
  24742. if (scene.shadowsEnabled) {
  24743. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  24744. }
  24745. lightIndex++;
  24746. if (lightIndex === maxSimultaneousLights)
  24747. break;
  24748. }
  24749. };
  24750. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  24751. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  24752. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  24753. effect.setColor3("vFogColor", scene.fogColor);
  24754. }
  24755. };
  24756. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  24757. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  24758. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  24759. }
  24760. };
  24761. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  24762. if (defines["LOGARITHMICDEPTH"]) {
  24763. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  24764. }
  24765. };
  24766. MaterialHelper.BindClipPlane = function (effect, scene) {
  24767. if (scene.clipPlane) {
  24768. var clipPlane = scene.clipPlane;
  24769. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  24770. }
  24771. };
  24772. return MaterialHelper;
  24773. })();
  24774. BABYLON.MaterialHelper = MaterialHelper;
  24775. })(BABYLON || (BABYLON = {}));
  24776. var BABYLON;
  24777. (function (BABYLON) {
  24778. var FresnelParameters = (function () {
  24779. function FresnelParameters() {
  24780. this.isEnabled = true;
  24781. this.leftColor = BABYLON.Color3.White();
  24782. this.rightColor = BABYLON.Color3.Black();
  24783. this.bias = 0;
  24784. this.power = 1;
  24785. }
  24786. FresnelParameters.prototype.clone = function () {
  24787. var newFresnelParameters = new FresnelParameters();
  24788. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  24789. return new FresnelParameters;
  24790. };
  24791. FresnelParameters.prototype.serialize = function () {
  24792. var serializationObject = {};
  24793. serializationObject.isEnabled = this.isEnabled;
  24794. serializationObject.leftColor = this.leftColor;
  24795. serializationObject.rightColor = this.rightColor;
  24796. serializationObject.bias = this.bias;
  24797. serializationObject.power = this.power;
  24798. return serializationObject;
  24799. };
  24800. FresnelParameters.Parse = function (parsedFresnelParameters) {
  24801. var fresnelParameters = new FresnelParameters();
  24802. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  24803. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  24804. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  24805. fresnelParameters.bias = parsedFresnelParameters.bias;
  24806. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  24807. return fresnelParameters;
  24808. };
  24809. return FresnelParameters;
  24810. })();
  24811. BABYLON.FresnelParameters = FresnelParameters;
  24812. })(BABYLON || (BABYLON = {}));
  24813. var BABYLON;
  24814. (function (BABYLON) {
  24815. var MaterialDefines = (function () {
  24816. function MaterialDefines() {
  24817. }
  24818. MaterialDefines.prototype.rebuild = function () {
  24819. if (this._keys) {
  24820. delete this._keys;
  24821. }
  24822. this._keys = Object.keys(this);
  24823. };
  24824. MaterialDefines.prototype.isEqual = function (other) {
  24825. if (this._keys.length !== other._keys.length) {
  24826. return false;
  24827. }
  24828. for (var index = 0; index < this._keys.length; index++) {
  24829. var prop = this._keys[index];
  24830. if (this[prop] !== other[prop]) {
  24831. return false;
  24832. }
  24833. }
  24834. return true;
  24835. };
  24836. MaterialDefines.prototype.cloneTo = function (other) {
  24837. if (this._keys.length !== other._keys.length) {
  24838. other._keys = this._keys.slice(0);
  24839. }
  24840. for (var index = 0; index < this._keys.length; index++) {
  24841. var prop = this._keys[index];
  24842. other[prop] = this[prop];
  24843. }
  24844. };
  24845. MaterialDefines.prototype.reset = function () {
  24846. for (var index = 0; index < this._keys.length; index++) {
  24847. var prop = this._keys[index];
  24848. if (typeof (this[prop]) === "number") {
  24849. this[prop] = 0;
  24850. }
  24851. else {
  24852. this[prop] = false;
  24853. }
  24854. }
  24855. };
  24856. MaterialDefines.prototype.toString = function () {
  24857. var result = "";
  24858. for (var index = 0; index < this._keys.length; index++) {
  24859. var prop = this._keys[index];
  24860. if (typeof (this[prop]) === "number") {
  24861. result += "#define " + prop + " " + this[prop] + "\n";
  24862. }
  24863. else if (this[prop]) {
  24864. result += "#define " + prop + "\n";
  24865. }
  24866. }
  24867. return result;
  24868. };
  24869. return MaterialDefines;
  24870. })();
  24871. BABYLON.MaterialDefines = MaterialDefines;
  24872. var Material = (function () {
  24873. function Material(name, scene, doNotAdd) {
  24874. this.name = name;
  24875. this.checkReadyOnEveryCall = false;
  24876. this.checkReadyOnlyOnce = false;
  24877. this.state = "";
  24878. this.alpha = 1.0;
  24879. this.backFaceCulling = true;
  24880. /**
  24881. * An event triggered when the material is disposed.
  24882. * @type {BABYLON.Observable}
  24883. */
  24884. this.onDisposeObservable = new BABYLON.Observable();
  24885. /**
  24886. * An event triggered when the material is bound.
  24887. * @type {BABYLON.Observable}
  24888. */
  24889. this.onBindObservable = new BABYLON.Observable();
  24890. /**
  24891. * An event triggered when the material is unbound.
  24892. * @type {BABYLON.Observable}
  24893. */
  24894. this.onUnBindObservable = new BABYLON.Observable();
  24895. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  24896. this.disableDepthWrite = false;
  24897. this.fogEnabled = true;
  24898. this.pointSize = 1.0;
  24899. this.zOffset = 0;
  24900. this._wasPreviouslyReady = false;
  24901. this._fillMode = Material.TriangleFillMode;
  24902. this.id = name;
  24903. this._scene = scene;
  24904. if (scene.useRightHandedSystem) {
  24905. this.sideOrientation = Material.ClockWiseSideOrientation;
  24906. }
  24907. else {
  24908. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  24909. }
  24910. if (!doNotAdd) {
  24911. scene.materials.push(this);
  24912. }
  24913. }
  24914. Object.defineProperty(Material, "TriangleFillMode", {
  24915. get: function () {
  24916. return Material._TriangleFillMode;
  24917. },
  24918. enumerable: true,
  24919. configurable: true
  24920. });
  24921. Object.defineProperty(Material, "WireFrameFillMode", {
  24922. get: function () {
  24923. return Material._WireFrameFillMode;
  24924. },
  24925. enumerable: true,
  24926. configurable: true
  24927. });
  24928. Object.defineProperty(Material, "PointFillMode", {
  24929. get: function () {
  24930. return Material._PointFillMode;
  24931. },
  24932. enumerable: true,
  24933. configurable: true
  24934. });
  24935. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  24936. get: function () {
  24937. return Material._ClockWiseSideOrientation;
  24938. },
  24939. enumerable: true,
  24940. configurable: true
  24941. });
  24942. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  24943. get: function () {
  24944. return Material._CounterClockWiseSideOrientation;
  24945. },
  24946. enumerable: true,
  24947. configurable: true
  24948. });
  24949. Object.defineProperty(Material.prototype, "onDispose", {
  24950. set: function (callback) {
  24951. if (this._onDisposeObserver) {
  24952. this.onDisposeObservable.remove(this._onDisposeObserver);
  24953. }
  24954. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24955. },
  24956. enumerable: true,
  24957. configurable: true
  24958. });
  24959. Object.defineProperty(Material.prototype, "onBind", {
  24960. set: function (callback) {
  24961. if (this._onBindObserver) {
  24962. this.onBindObservable.remove(this._onBindObserver);
  24963. }
  24964. this._onBindObserver = this.onBindObservable.add(callback);
  24965. },
  24966. enumerable: true,
  24967. configurable: true
  24968. });
  24969. Object.defineProperty(Material.prototype, "wireframe", {
  24970. get: function () {
  24971. return this._fillMode === Material.WireFrameFillMode;
  24972. },
  24973. set: function (value) {
  24974. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  24975. },
  24976. enumerable: true,
  24977. configurable: true
  24978. });
  24979. Object.defineProperty(Material.prototype, "pointsCloud", {
  24980. get: function () {
  24981. return this._fillMode === Material.PointFillMode;
  24982. },
  24983. set: function (value) {
  24984. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  24985. },
  24986. enumerable: true,
  24987. configurable: true
  24988. });
  24989. Object.defineProperty(Material.prototype, "fillMode", {
  24990. get: function () {
  24991. return this._fillMode;
  24992. },
  24993. set: function (value) {
  24994. this._fillMode = value;
  24995. },
  24996. enumerable: true,
  24997. configurable: true
  24998. });
  24999. /**
  25000. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25001. * subclasses should override adding information pertainent to themselves
  25002. */
  25003. Material.prototype.toString = function (fullDetails) {
  25004. var ret = "Name: " + this.name;
  25005. if (fullDetails) {
  25006. }
  25007. return ret;
  25008. };
  25009. Object.defineProperty(Material.prototype, "isFrozen", {
  25010. get: function () {
  25011. return this.checkReadyOnlyOnce;
  25012. },
  25013. enumerable: true,
  25014. configurable: true
  25015. });
  25016. Material.prototype.freeze = function () {
  25017. this.checkReadyOnlyOnce = true;
  25018. };
  25019. Material.prototype.unfreeze = function () {
  25020. this.checkReadyOnlyOnce = false;
  25021. };
  25022. Material.prototype.isReady = function (mesh, useInstances) {
  25023. return true;
  25024. };
  25025. Material.prototype.getEffect = function () {
  25026. return this._effect;
  25027. };
  25028. Material.prototype.getScene = function () {
  25029. return this._scene;
  25030. };
  25031. Material.prototype.needAlphaBlending = function () {
  25032. return (this.alpha < 1.0);
  25033. };
  25034. Material.prototype.needAlphaTesting = function () {
  25035. return false;
  25036. };
  25037. Material.prototype.getAlphaTestTexture = function () {
  25038. return null;
  25039. };
  25040. Material.prototype.markDirty = function () {
  25041. this._wasPreviouslyReady = false;
  25042. };
  25043. Material.prototype._preBind = function () {
  25044. var engine = this._scene.getEngine();
  25045. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  25046. engine.enableEffect(this._effect);
  25047. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25048. };
  25049. Material.prototype.bind = function (world, mesh) {
  25050. this._scene._cachedMaterial = this;
  25051. this.onBindObservable.notifyObservers(mesh);
  25052. if (this.disableDepthWrite) {
  25053. var engine = this._scene.getEngine();
  25054. this._cachedDepthWriteState = engine.getDepthWrite();
  25055. engine.setDepthWrite(false);
  25056. }
  25057. };
  25058. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25059. };
  25060. Material.prototype.unbind = function () {
  25061. this.onUnBindObservable.notifyObservers(this);
  25062. if (this.disableDepthWrite) {
  25063. var engine = this._scene.getEngine();
  25064. engine.setDepthWrite(this._cachedDepthWriteState);
  25065. }
  25066. };
  25067. Material.prototype.clone = function (name) {
  25068. return null;
  25069. };
  25070. Material.prototype.getBindedMeshes = function () {
  25071. var result = new Array();
  25072. for (var index = 0; index < this._scene.meshes.length; index++) {
  25073. var mesh = this._scene.meshes[index];
  25074. if (mesh.material === this) {
  25075. result.push(mesh);
  25076. }
  25077. }
  25078. return result;
  25079. };
  25080. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25081. // Animations
  25082. this.getScene().stopAnimation(this);
  25083. // Remove from scene
  25084. var index = this._scene.materials.indexOf(this);
  25085. if (index >= 0) {
  25086. this._scene.materials.splice(index, 1);
  25087. }
  25088. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  25089. if (forceDisposeEffect && this._effect) {
  25090. this._scene.getEngine()._releaseEffect(this._effect);
  25091. this._effect = null;
  25092. }
  25093. // Remove from meshes
  25094. for (index = 0; index < this._scene.meshes.length; index++) {
  25095. var mesh = this._scene.meshes[index];
  25096. if (mesh.material === this) {
  25097. mesh.material = null;
  25098. }
  25099. }
  25100. // Callback
  25101. this.onDisposeObservable.notifyObservers(this);
  25102. this.onDisposeObservable.clear();
  25103. this.onBindObservable.clear();
  25104. };
  25105. Material.prototype.serialize = function () {
  25106. return BABYLON.SerializationHelper.Serialize(this);
  25107. };
  25108. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  25109. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  25110. multiMaterial.id = parsedMultiMaterial.id;
  25111. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  25112. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  25113. var subMatId = parsedMultiMaterial.materials[matIndex];
  25114. if (subMatId) {
  25115. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  25116. }
  25117. else {
  25118. multiMaterial.subMaterials.push(null);
  25119. }
  25120. }
  25121. return multiMaterial;
  25122. };
  25123. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  25124. if (!parsedMaterial.customType) {
  25125. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  25126. }
  25127. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  25128. return materialType.Parse(parsedMaterial, scene, rootUrl);
  25129. ;
  25130. };
  25131. Material._TriangleFillMode = 0;
  25132. Material._WireFrameFillMode = 1;
  25133. Material._PointFillMode = 2;
  25134. Material._ClockWiseSideOrientation = 0;
  25135. Material._CounterClockWiseSideOrientation = 1;
  25136. __decorate([
  25137. BABYLON.serialize()
  25138. ], Material.prototype, "id", void 0);
  25139. __decorate([
  25140. BABYLON.serialize()
  25141. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  25142. __decorate([
  25143. BABYLON.serialize()
  25144. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  25145. __decorate([
  25146. BABYLON.serialize()
  25147. ], Material.prototype, "state", void 0);
  25148. __decorate([
  25149. BABYLON.serialize()
  25150. ], Material.prototype, "alpha", void 0);
  25151. __decorate([
  25152. BABYLON.serialize()
  25153. ], Material.prototype, "backFaceCulling", void 0);
  25154. __decorate([
  25155. BABYLON.serialize()
  25156. ], Material.prototype, "sideOrientation", void 0);
  25157. __decorate([
  25158. BABYLON.serialize()
  25159. ], Material.prototype, "alphaMode", void 0);
  25160. __decorate([
  25161. BABYLON.serialize()
  25162. ], Material.prototype, "disableDepthWrite", void 0);
  25163. __decorate([
  25164. BABYLON.serialize()
  25165. ], Material.prototype, "fogEnabled", void 0);
  25166. __decorate([
  25167. BABYLON.serialize()
  25168. ], Material.prototype, "pointSize", void 0);
  25169. __decorate([
  25170. BABYLON.serialize()
  25171. ], Material.prototype, "zOffset", void 0);
  25172. __decorate([
  25173. BABYLON.serialize()
  25174. ], Material.prototype, "wireframe", null);
  25175. __decorate([
  25176. BABYLON.serialize()
  25177. ], Material.prototype, "pointsCloud", null);
  25178. __decorate([
  25179. BABYLON.serialize()
  25180. ], Material.prototype, "fillMode", null);
  25181. return Material;
  25182. })();
  25183. BABYLON.Material = Material;
  25184. })(BABYLON || (BABYLON = {}));
  25185. var BABYLON;
  25186. (function (BABYLON) {
  25187. var StandardMaterialDefines = (function (_super) {
  25188. __extends(StandardMaterialDefines, _super);
  25189. function StandardMaterialDefines() {
  25190. _super.call(this);
  25191. this.DIFFUSE = false;
  25192. this.AMBIENT = false;
  25193. this.OPACITY = false;
  25194. this.OPACITYRGB = false;
  25195. this.REFLECTION = false;
  25196. this.EMISSIVE = false;
  25197. this.SPECULAR = false;
  25198. this.BUMP = false;
  25199. this.PARALLAX = false;
  25200. this.PARALLAXOCCLUSION = false;
  25201. this.SPECULAROVERALPHA = false;
  25202. this.CLIPPLANE = false;
  25203. this.ALPHATEST = false;
  25204. this.ALPHAFROMDIFFUSE = false;
  25205. this.POINTSIZE = false;
  25206. this.FOG = false;
  25207. this.SPECULARTERM = false;
  25208. this.DIFFUSEFRESNEL = false;
  25209. this.OPACITYFRESNEL = false;
  25210. this.REFLECTIONFRESNEL = false;
  25211. this.REFRACTIONFRESNEL = false;
  25212. this.EMISSIVEFRESNEL = false;
  25213. this.FRESNEL = false;
  25214. this.NORMAL = false;
  25215. this.UV1 = false;
  25216. this.UV2 = false;
  25217. this.VERTEXCOLOR = false;
  25218. this.VERTEXALPHA = false;
  25219. this.NUM_BONE_INFLUENCERS = 0;
  25220. this.BonesPerMesh = 0;
  25221. this.INSTANCES = false;
  25222. this.GLOSSINESS = false;
  25223. this.ROUGHNESS = false;
  25224. this.EMISSIVEASILLUMINATION = false;
  25225. this.LINKEMISSIVEWITHDIFFUSE = false;
  25226. this.REFLECTIONFRESNELFROMSPECULAR = false;
  25227. this.LIGHTMAP = false;
  25228. this.USELIGHTMAPASSHADOWMAP = false;
  25229. this.REFLECTIONMAP_3D = false;
  25230. this.REFLECTIONMAP_SPHERICAL = false;
  25231. this.REFLECTIONMAP_PLANAR = false;
  25232. this.REFLECTIONMAP_CUBIC = false;
  25233. this.REFLECTIONMAP_PROJECTION = false;
  25234. this.REFLECTIONMAP_SKYBOX = false;
  25235. this.REFLECTIONMAP_EXPLICIT = false;
  25236. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  25237. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  25238. this.INVERTCUBICMAP = false;
  25239. this.LOGARITHMICDEPTH = false;
  25240. this.REFRACTION = false;
  25241. this.REFRACTIONMAP_3D = false;
  25242. this.REFLECTIONOVERALPHA = false;
  25243. this.INVERTNORMALMAPX = false;
  25244. this.INVERTNORMALMAPY = false;
  25245. this.SHADOWFULLFLOAT = false;
  25246. this.CAMERACOLORGRADING = false;
  25247. this.CAMERACOLORCURVES = false;
  25248. this.rebuild();
  25249. }
  25250. return StandardMaterialDefines;
  25251. })(BABYLON.MaterialDefines);
  25252. var StandardMaterial = (function (_super) {
  25253. __extends(StandardMaterial, _super);
  25254. function StandardMaterial(name, scene) {
  25255. var _this = this;
  25256. _super.call(this, name, scene);
  25257. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  25258. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  25259. this.specularColor = new BABYLON.Color3(1, 1, 1);
  25260. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  25261. this.specularPower = 64;
  25262. this.useAlphaFromDiffuseTexture = false;
  25263. this.useEmissiveAsIllumination = false;
  25264. this.linkEmissiveWithDiffuse = false;
  25265. this.useReflectionFresnelFromSpecular = false;
  25266. this.useSpecularOverAlpha = false;
  25267. this.useReflectionOverAlpha = false;
  25268. this.disableLighting = false;
  25269. this.useParallax = false;
  25270. this.useParallaxOcclusion = false;
  25271. this.parallaxScaleBias = 0.05;
  25272. this.roughness = 0;
  25273. this.indexOfRefraction = 0.98;
  25274. this.invertRefractionY = true;
  25275. this.useLightmapAsShadowmap = false;
  25276. this.useGlossinessFromSpecularMapAlpha = false;
  25277. this.maxSimultaneousLights = 4;
  25278. /**
  25279. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  25280. */
  25281. this.invertNormalMapX = false;
  25282. /**
  25283. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  25284. */
  25285. this.invertNormalMapY = false;
  25286. /**
  25287. * Color Grading 2D Lookup Texture.
  25288. * This allows special effects like sepia, black and white to sixties rendering style.
  25289. */
  25290. this.cameraColorGradingTexture = null;
  25291. /**
  25292. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  25293. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  25294. * 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;
  25295. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  25296. */
  25297. this.cameraColorCurves = null;
  25298. this._renderTargets = new BABYLON.SmartArray(16);
  25299. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  25300. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  25301. this._defines = new StandardMaterialDefines();
  25302. this._cachedDefines = new StandardMaterialDefines();
  25303. this._cachedDefines.BonesPerMesh = -1;
  25304. this.getRenderTargetTextures = function () {
  25305. _this._renderTargets.reset();
  25306. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  25307. _this._renderTargets.push(_this.reflectionTexture);
  25308. }
  25309. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  25310. _this._renderTargets.push(_this.refractionTexture);
  25311. }
  25312. return _this._renderTargets;
  25313. };
  25314. }
  25315. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  25316. get: function () {
  25317. return this._useLogarithmicDepth;
  25318. },
  25319. set: function (value) {
  25320. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  25321. },
  25322. enumerable: true,
  25323. configurable: true
  25324. });
  25325. StandardMaterial.prototype.needAlphaBlending = function () {
  25326. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  25327. };
  25328. StandardMaterial.prototype.needAlphaTesting = function () {
  25329. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  25330. };
  25331. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  25332. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  25333. };
  25334. StandardMaterial.prototype.getAlphaTestTexture = function () {
  25335. return this.diffuseTexture;
  25336. };
  25337. // Methods
  25338. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  25339. if (!mesh) {
  25340. return true;
  25341. }
  25342. if (this._defines.INSTANCES !== useInstances) {
  25343. return false;
  25344. }
  25345. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  25346. return true;
  25347. }
  25348. return false;
  25349. };
  25350. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  25351. if (this.isFrozen) {
  25352. if (this._wasPreviouslyReady) {
  25353. return true;
  25354. }
  25355. }
  25356. var scene = this.getScene();
  25357. if (!this.checkReadyOnEveryCall) {
  25358. if (this._renderId === scene.getRenderId()) {
  25359. if (this._checkCache(scene, mesh, useInstances)) {
  25360. return true;
  25361. }
  25362. }
  25363. }
  25364. var engine = scene.getEngine();
  25365. var needNormals = false;
  25366. var needUVs = false;
  25367. this._defines.reset();
  25368. // Textures
  25369. if (scene.texturesEnabled) {
  25370. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  25371. if (!this.diffuseTexture.isReady()) {
  25372. return false;
  25373. }
  25374. else {
  25375. needUVs = true;
  25376. this._defines.DIFFUSE = true;
  25377. }
  25378. }
  25379. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  25380. if (!this.ambientTexture.isReady()) {
  25381. return false;
  25382. }
  25383. else {
  25384. needUVs = true;
  25385. this._defines.AMBIENT = true;
  25386. }
  25387. }
  25388. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  25389. if (!this.opacityTexture.isReady()) {
  25390. return false;
  25391. }
  25392. else {
  25393. needUVs = true;
  25394. this._defines.OPACITY = true;
  25395. if (this.opacityTexture.getAlphaFromRGB) {
  25396. this._defines.OPACITYRGB = true;
  25397. }
  25398. }
  25399. }
  25400. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  25401. if (!this.reflectionTexture.isReady()) {
  25402. return false;
  25403. }
  25404. else {
  25405. needNormals = true;
  25406. this._defines.REFLECTION = true;
  25407. if (this.roughness > 0) {
  25408. this._defines.ROUGHNESS = true;
  25409. }
  25410. if (this.useReflectionOverAlpha) {
  25411. this._defines.REFLECTIONOVERALPHA = true;
  25412. }
  25413. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  25414. this._defines.INVERTCUBICMAP = true;
  25415. }
  25416. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  25417. switch (this.reflectionTexture.coordinatesMode) {
  25418. case BABYLON.Texture.CUBIC_MODE:
  25419. case BABYLON.Texture.INVCUBIC_MODE:
  25420. this._defines.REFLECTIONMAP_CUBIC = true;
  25421. break;
  25422. case BABYLON.Texture.EXPLICIT_MODE:
  25423. this._defines.REFLECTIONMAP_EXPLICIT = true;
  25424. break;
  25425. case BABYLON.Texture.PLANAR_MODE:
  25426. this._defines.REFLECTIONMAP_PLANAR = true;
  25427. break;
  25428. case BABYLON.Texture.PROJECTION_MODE:
  25429. this._defines.REFLECTIONMAP_PROJECTION = true;
  25430. break;
  25431. case BABYLON.Texture.SKYBOX_MODE:
  25432. this._defines.REFLECTIONMAP_SKYBOX = true;
  25433. break;
  25434. case BABYLON.Texture.SPHERICAL_MODE:
  25435. this._defines.REFLECTIONMAP_SPHERICAL = true;
  25436. break;
  25437. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  25438. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  25439. break;
  25440. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  25441. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  25442. break;
  25443. }
  25444. }
  25445. }
  25446. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  25447. if (!this.emissiveTexture.isReady()) {
  25448. return false;
  25449. }
  25450. else {
  25451. needUVs = true;
  25452. this._defines.EMISSIVE = true;
  25453. }
  25454. }
  25455. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  25456. if (!this.lightmapTexture.isReady()) {
  25457. return false;
  25458. }
  25459. else {
  25460. needUVs = true;
  25461. this._defines.LIGHTMAP = true;
  25462. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  25463. }
  25464. }
  25465. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  25466. if (!this.specularTexture.isReady()) {
  25467. return false;
  25468. }
  25469. else {
  25470. needUVs = true;
  25471. this._defines.SPECULAR = true;
  25472. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  25473. }
  25474. }
  25475. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  25476. if (!this.bumpTexture.isReady()) {
  25477. return false;
  25478. }
  25479. else {
  25480. needUVs = true;
  25481. this._defines.BUMP = true;
  25482. if (this.useParallax) {
  25483. this._defines.PARALLAX = true;
  25484. if (this.useParallaxOcclusion) {
  25485. this._defines.PARALLAXOCCLUSION = true;
  25486. }
  25487. }
  25488. if (this.invertNormalMapX) {
  25489. this._defines.INVERTNORMALMAPX = true;
  25490. }
  25491. if (this.invertNormalMapY) {
  25492. this._defines.INVERTNORMALMAPY = true;
  25493. }
  25494. }
  25495. }
  25496. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  25497. if (!this.refractionTexture.isReady()) {
  25498. return false;
  25499. }
  25500. else {
  25501. needUVs = true;
  25502. this._defines.REFRACTION = true;
  25503. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  25504. }
  25505. }
  25506. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  25507. if (!this.cameraColorGradingTexture.isReady()) {
  25508. return false;
  25509. }
  25510. else {
  25511. this._defines.CAMERACOLORGRADING = true;
  25512. }
  25513. }
  25514. }
  25515. // Effect
  25516. if (scene.clipPlane) {
  25517. this._defines.CLIPPLANE = true;
  25518. }
  25519. if (engine.getAlphaTesting()) {
  25520. this._defines.ALPHATEST = true;
  25521. }
  25522. if (this._shouldUseAlphaFromDiffuseTexture()) {
  25523. this._defines.ALPHAFROMDIFFUSE = true;
  25524. }
  25525. if (this.useEmissiveAsIllumination) {
  25526. this._defines.EMISSIVEASILLUMINATION = true;
  25527. }
  25528. if (this.linkEmissiveWithDiffuse) {
  25529. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  25530. }
  25531. if (this.useLogarithmicDepth) {
  25532. this._defines.LOGARITHMICDEPTH = true;
  25533. }
  25534. if (this.cameraColorCurves) {
  25535. this._defines.CAMERACOLORCURVES = true;
  25536. }
  25537. // Point size
  25538. if (this.pointsCloud || scene.forcePointsCloud) {
  25539. this._defines.POINTSIZE = true;
  25540. }
  25541. // Fog
  25542. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  25543. this._defines.FOG = true;
  25544. }
  25545. if (scene.lightsEnabled && !this.disableLighting) {
  25546. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  25547. }
  25548. if (StandardMaterial.FresnelEnabled) {
  25549. // Fresnel
  25550. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  25551. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  25552. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  25553. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  25554. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25555. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  25556. this._defines.DIFFUSEFRESNEL = true;
  25557. }
  25558. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  25559. this._defines.OPACITYFRESNEL = true;
  25560. }
  25561. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25562. this._defines.REFLECTIONFRESNEL = true;
  25563. if (this.useReflectionFresnelFromSpecular) {
  25564. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  25565. }
  25566. }
  25567. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  25568. this._defines.REFRACTIONFRESNEL = true;
  25569. }
  25570. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  25571. this._defines.EMISSIVEFRESNEL = true;
  25572. }
  25573. needNormals = true;
  25574. this._defines.FRESNEL = true;
  25575. }
  25576. }
  25577. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  25578. this._defines.SPECULAROVERALPHA = true;
  25579. }
  25580. // Attribs
  25581. if (mesh) {
  25582. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25583. this._defines.NORMAL = true;
  25584. }
  25585. if (needUVs) {
  25586. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25587. this._defines.UV1 = true;
  25588. }
  25589. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25590. this._defines.UV2 = true;
  25591. }
  25592. }
  25593. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25594. this._defines.VERTEXCOLOR = true;
  25595. if (mesh.hasVertexAlpha) {
  25596. this._defines.VERTEXALPHA = true;
  25597. }
  25598. }
  25599. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  25600. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  25601. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  25602. }
  25603. // Instances
  25604. if (useInstances) {
  25605. this._defines.INSTANCES = true;
  25606. }
  25607. }
  25608. // Get correct effect
  25609. if (!this._defines.isEqual(this._cachedDefines)) {
  25610. this._defines.cloneTo(this._cachedDefines);
  25611. scene.resetCachedMaterial();
  25612. // Fallbacks
  25613. var fallbacks = new BABYLON.EffectFallbacks();
  25614. if (this._defines.REFLECTION) {
  25615. fallbacks.addFallback(0, "REFLECTION");
  25616. }
  25617. if (this._defines.SPECULAR) {
  25618. fallbacks.addFallback(0, "SPECULAR");
  25619. }
  25620. if (this._defines.BUMP) {
  25621. fallbacks.addFallback(0, "BUMP");
  25622. }
  25623. if (this._defines.PARALLAX) {
  25624. fallbacks.addFallback(1, "PARALLAX");
  25625. }
  25626. if (this._defines.PARALLAXOCCLUSION) {
  25627. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  25628. }
  25629. if (this._defines.SPECULAROVERALPHA) {
  25630. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  25631. }
  25632. if (this._defines.FOG) {
  25633. fallbacks.addFallback(1, "FOG");
  25634. }
  25635. if (this._defines.POINTSIZE) {
  25636. fallbacks.addFallback(0, "POINTSIZE");
  25637. }
  25638. if (this._defines.LOGARITHMICDEPTH) {
  25639. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  25640. }
  25641. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  25642. if (this._defines.SPECULARTERM) {
  25643. fallbacks.addFallback(0, "SPECULARTERM");
  25644. }
  25645. if (this._defines.DIFFUSEFRESNEL) {
  25646. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  25647. }
  25648. if (this._defines.OPACITYFRESNEL) {
  25649. fallbacks.addFallback(2, "OPACITYFRESNEL");
  25650. }
  25651. if (this._defines.REFLECTIONFRESNEL) {
  25652. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  25653. }
  25654. if (this._defines.EMISSIVEFRESNEL) {
  25655. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  25656. }
  25657. if (this._defines.FRESNEL) {
  25658. fallbacks.addFallback(4, "FRESNEL");
  25659. }
  25660. //Attributes
  25661. var attribs = [BABYLON.VertexBuffer.PositionKind];
  25662. if (this._defines.NORMAL) {
  25663. attribs.push(BABYLON.VertexBuffer.NormalKind);
  25664. }
  25665. if (this._defines.UV1) {
  25666. attribs.push(BABYLON.VertexBuffer.UVKind);
  25667. }
  25668. if (this._defines.UV2) {
  25669. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  25670. }
  25671. if (this._defines.VERTEXCOLOR) {
  25672. attribs.push(BABYLON.VertexBuffer.ColorKind);
  25673. }
  25674. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  25675. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  25676. var shaderName = "default";
  25677. var join = this._defines.toString();
  25678. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  25679. "vFogInfos", "vFogColor", "pointSize",
  25680. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  25681. "mBones",
  25682. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  25683. "depthValues",
  25684. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  25685. "logarithmicDepthConstant"
  25686. ];
  25687. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  25688. if (this._defines.CAMERACOLORCURVES) {
  25689. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  25690. }
  25691. if (this._defines.CAMERACOLORGRADING) {
  25692. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  25693. }
  25694. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  25695. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  25696. }
  25697. if (!this._effect.isReady()) {
  25698. return false;
  25699. }
  25700. this._renderId = scene.getRenderId();
  25701. this._wasPreviouslyReady = true;
  25702. if (mesh) {
  25703. if (!mesh._materialDefines) {
  25704. mesh._materialDefines = new StandardMaterialDefines();
  25705. }
  25706. this._defines.cloneTo(mesh._materialDefines);
  25707. }
  25708. return true;
  25709. };
  25710. StandardMaterial.prototype.unbind = function () {
  25711. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  25712. this._effect.setTexture("reflection2DSampler", null);
  25713. }
  25714. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  25715. this._effect.setTexture("refraction2DSampler", null);
  25716. }
  25717. _super.prototype.unbind.call(this);
  25718. };
  25719. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  25720. this._effect.setMatrix("world", world);
  25721. };
  25722. StandardMaterial.prototype.bind = function (world, mesh) {
  25723. var scene = this.getScene();
  25724. // Matrices
  25725. this.bindOnlyWorldMatrix(world);
  25726. // Bones
  25727. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  25728. if (scene.getCachedMaterial() !== this) {
  25729. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  25730. if (StandardMaterial.FresnelEnabled) {
  25731. // Fresnel
  25732. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  25733. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  25734. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  25735. }
  25736. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  25737. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  25738. }
  25739. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25740. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  25741. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  25742. }
  25743. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  25744. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  25745. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  25746. }
  25747. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  25748. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  25749. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  25750. }
  25751. }
  25752. // Textures
  25753. if (scene.texturesEnabled) {
  25754. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  25755. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  25756. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  25757. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  25758. }
  25759. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  25760. this._effect.setTexture("ambientSampler", this.ambientTexture);
  25761. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  25762. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  25763. }
  25764. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  25765. this._effect.setTexture("opacitySampler", this.opacityTexture);
  25766. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  25767. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  25768. }
  25769. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  25770. if (this.reflectionTexture.isCube) {
  25771. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  25772. }
  25773. else {
  25774. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  25775. }
  25776. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  25777. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  25778. }
  25779. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  25780. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  25781. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  25782. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  25783. }
  25784. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  25785. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  25786. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  25787. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  25788. }
  25789. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  25790. this._effect.setTexture("specularSampler", this.specularTexture);
  25791. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  25792. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  25793. }
  25794. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  25795. this._effect.setTexture("bumpSampler", this.bumpTexture);
  25796. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  25797. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  25798. }
  25799. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  25800. var depth = 1.0;
  25801. if (this.refractionTexture.isCube) {
  25802. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  25803. }
  25804. else {
  25805. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  25806. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  25807. if (this.refractionTexture.depth) {
  25808. depth = this.refractionTexture.depth;
  25809. }
  25810. }
  25811. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  25812. }
  25813. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  25814. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  25815. }
  25816. }
  25817. // Clip plane
  25818. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  25819. // Point size
  25820. if (this.pointsCloud) {
  25821. this._effect.setFloat("pointSize", this.pointSize);
  25822. }
  25823. // Colors
  25824. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  25825. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  25826. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  25827. if (this._defines.SPECULARTERM) {
  25828. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  25829. }
  25830. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  25831. }
  25832. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  25833. // Diffuse
  25834. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  25835. // Lights
  25836. if (scene.lightsEnabled && !this.disableLighting) {
  25837. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  25838. }
  25839. // View
  25840. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  25841. this._effect.setMatrix("view", scene.getViewMatrix());
  25842. }
  25843. // Fog
  25844. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  25845. // Log. depth
  25846. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  25847. // Color Curves
  25848. if (this.cameraColorCurves) {
  25849. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  25850. }
  25851. }
  25852. _super.prototype.bind.call(this, world, mesh);
  25853. };
  25854. StandardMaterial.prototype.getAnimatables = function () {
  25855. var results = [];
  25856. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  25857. results.push(this.diffuseTexture);
  25858. }
  25859. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  25860. results.push(this.ambientTexture);
  25861. }
  25862. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  25863. results.push(this.opacityTexture);
  25864. }
  25865. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  25866. results.push(this.reflectionTexture);
  25867. }
  25868. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  25869. results.push(this.emissiveTexture);
  25870. }
  25871. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  25872. results.push(this.specularTexture);
  25873. }
  25874. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  25875. results.push(this.bumpTexture);
  25876. }
  25877. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  25878. results.push(this.lightmapTexture);
  25879. }
  25880. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  25881. results.push(this.refractionTexture);
  25882. }
  25883. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  25884. results.push(this.cameraColorGradingTexture);
  25885. }
  25886. return results;
  25887. };
  25888. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25889. if (forceDisposeTextures) {
  25890. if (this.diffuseTexture) {
  25891. this.diffuseTexture.dispose();
  25892. }
  25893. if (this.ambientTexture) {
  25894. this.ambientTexture.dispose();
  25895. }
  25896. if (this.opacityTexture) {
  25897. this.opacityTexture.dispose();
  25898. }
  25899. if (this.reflectionTexture) {
  25900. this.reflectionTexture.dispose();
  25901. }
  25902. if (this.emissiveTexture) {
  25903. this.emissiveTexture.dispose();
  25904. }
  25905. if (this.specularTexture) {
  25906. this.specularTexture.dispose();
  25907. }
  25908. if (this.bumpTexture) {
  25909. this.bumpTexture.dispose();
  25910. }
  25911. if (this.lightmapTexture) {
  25912. this.lightmapTexture.dispose();
  25913. }
  25914. if (this.refractionTexture) {
  25915. this.refractionTexture.dispose();
  25916. }
  25917. if (this.cameraColorGradingTexture) {
  25918. this.cameraColorGradingTexture.dispose();
  25919. }
  25920. }
  25921. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  25922. };
  25923. StandardMaterial.prototype.clone = function (name) {
  25924. var _this = this;
  25925. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  25926. };
  25927. StandardMaterial.prototype.serialize = function () {
  25928. return BABYLON.SerializationHelper.Serialize(this);
  25929. };
  25930. // Statics
  25931. StandardMaterial.Parse = function (source, scene, rootUrl) {
  25932. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  25933. };
  25934. // Flags used to enable or disable a type of texture for all Standard Materials
  25935. StandardMaterial.DiffuseTextureEnabled = true;
  25936. StandardMaterial.AmbientTextureEnabled = true;
  25937. StandardMaterial.OpacityTextureEnabled = true;
  25938. StandardMaterial.ReflectionTextureEnabled = true;
  25939. StandardMaterial.EmissiveTextureEnabled = true;
  25940. StandardMaterial.SpecularTextureEnabled = true;
  25941. StandardMaterial.BumpTextureEnabled = true;
  25942. StandardMaterial.FresnelEnabled = true;
  25943. StandardMaterial.LightmapTextureEnabled = true;
  25944. StandardMaterial.RefractionTextureEnabled = true;
  25945. StandardMaterial.ColorGradingTextureEnabled = true;
  25946. __decorate([
  25947. BABYLON.serializeAsTexture()
  25948. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  25949. __decorate([
  25950. BABYLON.serializeAsTexture()
  25951. ], StandardMaterial.prototype, "ambientTexture", void 0);
  25952. __decorate([
  25953. BABYLON.serializeAsTexture()
  25954. ], StandardMaterial.prototype, "opacityTexture", void 0);
  25955. __decorate([
  25956. BABYLON.serializeAsTexture()
  25957. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  25958. __decorate([
  25959. BABYLON.serializeAsTexture()
  25960. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  25961. __decorate([
  25962. BABYLON.serializeAsTexture()
  25963. ], StandardMaterial.prototype, "specularTexture", void 0);
  25964. __decorate([
  25965. BABYLON.serializeAsTexture()
  25966. ], StandardMaterial.prototype, "bumpTexture", void 0);
  25967. __decorate([
  25968. BABYLON.serializeAsTexture()
  25969. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  25970. __decorate([
  25971. BABYLON.serializeAsTexture()
  25972. ], StandardMaterial.prototype, "refractionTexture", void 0);
  25973. __decorate([
  25974. BABYLON.serializeAsColor3("ambient")
  25975. ], StandardMaterial.prototype, "ambientColor", void 0);
  25976. __decorate([
  25977. BABYLON.serializeAsColor3("diffuse")
  25978. ], StandardMaterial.prototype, "diffuseColor", void 0);
  25979. __decorate([
  25980. BABYLON.serializeAsColor3("specular")
  25981. ], StandardMaterial.prototype, "specularColor", void 0);
  25982. __decorate([
  25983. BABYLON.serializeAsColor3("emissive")
  25984. ], StandardMaterial.prototype, "emissiveColor", void 0);
  25985. __decorate([
  25986. BABYLON.serialize()
  25987. ], StandardMaterial.prototype, "specularPower", void 0);
  25988. __decorate([
  25989. BABYLON.serialize()
  25990. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  25991. __decorate([
  25992. BABYLON.serialize()
  25993. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  25994. __decorate([
  25995. BABYLON.serialize()
  25996. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  25997. __decorate([
  25998. BABYLON.serialize()
  25999. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  26000. __decorate([
  26001. BABYLON.serialize()
  26002. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  26003. __decorate([
  26004. BABYLON.serialize()
  26005. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  26006. __decorate([
  26007. BABYLON.serialize()
  26008. ], StandardMaterial.prototype, "disableLighting", void 0);
  26009. __decorate([
  26010. BABYLON.serialize()
  26011. ], StandardMaterial.prototype, "useParallax", void 0);
  26012. __decorate([
  26013. BABYLON.serialize()
  26014. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  26015. __decorate([
  26016. BABYLON.serialize()
  26017. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  26018. __decorate([
  26019. BABYLON.serialize()
  26020. ], StandardMaterial.prototype, "roughness", void 0);
  26021. __decorate([
  26022. BABYLON.serialize()
  26023. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  26024. __decorate([
  26025. BABYLON.serialize()
  26026. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  26027. __decorate([
  26028. BABYLON.serialize()
  26029. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  26030. __decorate([
  26031. BABYLON.serializeAsFresnelParameters()
  26032. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  26033. __decorate([
  26034. BABYLON.serializeAsFresnelParameters()
  26035. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  26036. __decorate([
  26037. BABYLON.serializeAsFresnelParameters()
  26038. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  26039. __decorate([
  26040. BABYLON.serializeAsFresnelParameters()
  26041. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  26042. __decorate([
  26043. BABYLON.serializeAsFresnelParameters()
  26044. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  26045. __decorate([
  26046. BABYLON.serialize()
  26047. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  26048. __decorate([
  26049. BABYLON.serialize()
  26050. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  26051. __decorate([
  26052. BABYLON.serialize()
  26053. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  26054. __decorate([
  26055. BABYLON.serialize()
  26056. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  26057. __decorate([
  26058. BABYLON.serializeAsTexture()
  26059. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  26060. __decorate([
  26061. BABYLON.serializeAsColorCurves()
  26062. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  26063. __decorate([
  26064. BABYLON.serialize()
  26065. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  26066. return StandardMaterial;
  26067. })(BABYLON.Material);
  26068. BABYLON.StandardMaterial = StandardMaterial;
  26069. })(BABYLON || (BABYLON = {}));
  26070. var BABYLON;
  26071. (function (BABYLON) {
  26072. var MultiMaterial = (function (_super) {
  26073. __extends(MultiMaterial, _super);
  26074. function MultiMaterial(name, scene) {
  26075. _super.call(this, name, scene, true);
  26076. this.subMaterials = new Array();
  26077. scene.multiMaterials.push(this);
  26078. }
  26079. // Properties
  26080. MultiMaterial.prototype.getSubMaterial = function (index) {
  26081. if (index < 0 || index >= this.subMaterials.length) {
  26082. return this.getScene().defaultMaterial;
  26083. }
  26084. return this.subMaterials[index];
  26085. };
  26086. // Methods
  26087. MultiMaterial.prototype.isReady = function (mesh) {
  26088. for (var index = 0; index < this.subMaterials.length; index++) {
  26089. var subMaterial = this.subMaterials[index];
  26090. if (subMaterial) {
  26091. if (!this.subMaterials[index].isReady(mesh)) {
  26092. return false;
  26093. }
  26094. }
  26095. }
  26096. return true;
  26097. };
  26098. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  26099. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  26100. for (var index = 0; index < this.subMaterials.length; index++) {
  26101. var subMaterial = null;
  26102. if (cloneChildren) {
  26103. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  26104. }
  26105. else {
  26106. subMaterial = this.subMaterials[index];
  26107. }
  26108. newMultiMaterial.subMaterials.push(subMaterial);
  26109. }
  26110. return newMultiMaterial;
  26111. };
  26112. MultiMaterial.prototype.serialize = function () {
  26113. var serializationObject = {};
  26114. serializationObject.name = this.name;
  26115. serializationObject.id = this.id;
  26116. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26117. serializationObject.materials = [];
  26118. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  26119. var subMat = this.subMaterials[matIndex];
  26120. if (subMat) {
  26121. serializationObject.materials.push(subMat.id);
  26122. }
  26123. else {
  26124. serializationObject.materials.push(null);
  26125. }
  26126. }
  26127. return serializationObject;
  26128. };
  26129. return MultiMaterial;
  26130. })(BABYLON.Material);
  26131. BABYLON.MultiMaterial = MultiMaterial;
  26132. })(BABYLON || (BABYLON = {}));
  26133. var BABYLON;
  26134. (function (BABYLON) {
  26135. var SceneLoader = (function () {
  26136. function SceneLoader() {
  26137. }
  26138. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  26139. get: function () {
  26140. return 0;
  26141. },
  26142. enumerable: true,
  26143. configurable: true
  26144. });
  26145. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  26146. get: function () {
  26147. return 1;
  26148. },
  26149. enumerable: true,
  26150. configurable: true
  26151. });
  26152. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  26153. get: function () {
  26154. return 2;
  26155. },
  26156. enumerable: true,
  26157. configurable: true
  26158. });
  26159. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  26160. get: function () {
  26161. return 3;
  26162. },
  26163. enumerable: true,
  26164. configurable: true
  26165. });
  26166. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  26167. get: function () {
  26168. return SceneLoader._ForceFullSceneLoadingForIncremental;
  26169. },
  26170. set: function (value) {
  26171. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  26172. },
  26173. enumerable: true,
  26174. configurable: true
  26175. });
  26176. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  26177. get: function () {
  26178. return SceneLoader._ShowLoadingScreen;
  26179. },
  26180. set: function (value) {
  26181. SceneLoader._ShowLoadingScreen = value;
  26182. },
  26183. enumerable: true,
  26184. configurable: true
  26185. });
  26186. Object.defineProperty(SceneLoader, "loggingLevel", {
  26187. get: function () {
  26188. return SceneLoader._loggingLevel;
  26189. },
  26190. set: function (value) {
  26191. SceneLoader._loggingLevel = value;
  26192. },
  26193. enumerable: true,
  26194. configurable: true
  26195. });
  26196. SceneLoader._getDefaultPlugin = function () {
  26197. return SceneLoader._registeredPlugins[".babylon"];
  26198. };
  26199. SceneLoader._getPluginForExtension = function (extension) {
  26200. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  26201. if (registeredPlugin) {
  26202. return registeredPlugin;
  26203. }
  26204. return SceneLoader._getDefaultPlugin();
  26205. };
  26206. SceneLoader._getPluginForFilename = function (sceneFilename) {
  26207. if (sceneFilename.name) {
  26208. sceneFilename = sceneFilename.name;
  26209. }
  26210. var dotPosition = sceneFilename.lastIndexOf(".");
  26211. var queryStringPosition = sceneFilename.indexOf("?");
  26212. if (queryStringPosition === -1) {
  26213. queryStringPosition = sceneFilename.length;
  26214. }
  26215. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  26216. return SceneLoader._getPluginForExtension(extension);
  26217. };
  26218. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  26219. SceneLoader._getDirectLoad = function (sceneFilename) {
  26220. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  26221. return sceneFilename.substr(5);
  26222. }
  26223. return null;
  26224. };
  26225. // Public functions
  26226. SceneLoader.GetPluginForExtension = function (extension) {
  26227. return SceneLoader._getPluginForExtension(extension).plugin;
  26228. };
  26229. SceneLoader.RegisterPlugin = function (plugin) {
  26230. if (typeof plugin.extensions === "string") {
  26231. var extension = plugin.extensions;
  26232. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  26233. plugin: plugin,
  26234. isBinary: false
  26235. };
  26236. }
  26237. else {
  26238. var extensions = plugin.extensions;
  26239. Object.keys(extensions).forEach(function (extension) {
  26240. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  26241. plugin: plugin,
  26242. isBinary: extensions[extension].isBinary
  26243. };
  26244. });
  26245. }
  26246. };
  26247. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  26248. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26249. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26250. return;
  26251. }
  26252. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26253. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26254. return;
  26255. }
  26256. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  26257. var loadingToken = {};
  26258. scene._addPendingData(loadingToken);
  26259. var manifestChecked = function (success) {
  26260. scene.database = database;
  26261. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  26262. var plugin = registeredPlugin.plugin;
  26263. var useArrayBuffer = registeredPlugin.isBinary;
  26264. var importMeshFromData = function (data) {
  26265. var meshes = [];
  26266. var particleSystems = [];
  26267. var skeletons = [];
  26268. try {
  26269. if (plugin.importMesh) {
  26270. var syncedPlugin = plugin;
  26271. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  26272. if (onerror) {
  26273. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  26274. }
  26275. scene._removePendingData(loadingToken);
  26276. return;
  26277. }
  26278. if (onsuccess) {
  26279. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  26280. onsuccess(meshes, particleSystems, skeletons);
  26281. scene._removePendingData(loadingToken);
  26282. }
  26283. }
  26284. else {
  26285. var asyncedPlugin = plugin;
  26286. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  26287. if (onsuccess) {
  26288. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  26289. onsuccess(meshes, particleSystems, skeletons);
  26290. scene._removePendingData(loadingToken);
  26291. }
  26292. }, function () {
  26293. if (onerror) {
  26294. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  26295. }
  26296. scene._removePendingData(loadingToken);
  26297. });
  26298. }
  26299. }
  26300. catch (e) {
  26301. if (onerror) {
  26302. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  26303. }
  26304. scene._removePendingData(loadingToken);
  26305. }
  26306. };
  26307. if (directLoad) {
  26308. importMeshFromData(directLoad);
  26309. return;
  26310. }
  26311. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  26312. importMeshFromData(data);
  26313. }, progressCallBack, database, useArrayBuffer);
  26314. };
  26315. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  26316. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  26317. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  26318. }
  26319. else {
  26320. // If the scene is a data stream or offline support is not enabled, it's a direct load
  26321. manifestChecked(true);
  26322. }
  26323. };
  26324. /**
  26325. * Load a scene
  26326. * @param rootUrl a string that defines the root url for scene and resources
  26327. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  26328. * @param engine is the instance of BABYLON.Engine to use to create the scene
  26329. */
  26330. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  26331. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  26332. };
  26333. /**
  26334. * Append a scene
  26335. * @param rootUrl a string that defines the root url for scene and resources
  26336. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  26337. * @param scene is the instance of BABYLON.Scene to append to
  26338. */
  26339. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  26340. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26341. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26342. return;
  26343. }
  26344. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  26345. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  26346. var plugin = registeredPlugin.plugin;
  26347. var useArrayBuffer = registeredPlugin.isBinary;
  26348. var database;
  26349. var loadingToken = {};
  26350. scene._addPendingData(loadingToken);
  26351. if (SceneLoader.ShowLoadingScreen) {
  26352. scene.getEngine().displayLoadingUI();
  26353. }
  26354. var loadSceneFromData = function (data) {
  26355. scene.database = database;
  26356. if (plugin.load) {
  26357. var syncedPlugin = plugin;
  26358. if (!syncedPlugin.load(scene, data, rootUrl)) {
  26359. if (onerror) {
  26360. onerror(scene);
  26361. }
  26362. scene._removePendingData(loadingToken);
  26363. scene.getEngine().hideLoadingUI();
  26364. return;
  26365. }
  26366. if (onsuccess) {
  26367. onsuccess(scene);
  26368. }
  26369. scene._removePendingData(loadingToken);
  26370. }
  26371. else {
  26372. var asyncedPlugin = plugin;
  26373. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  26374. if (onsuccess) {
  26375. onsuccess(scene);
  26376. }
  26377. }, function () {
  26378. if (onerror) {
  26379. onerror(scene);
  26380. }
  26381. scene._removePendingData(loadingToken);
  26382. scene.getEngine().hideLoadingUI();
  26383. });
  26384. }
  26385. if (SceneLoader.ShowLoadingScreen) {
  26386. scene.executeWhenReady(function () {
  26387. scene.getEngine().hideLoadingUI();
  26388. });
  26389. }
  26390. };
  26391. var manifestChecked = function (success) {
  26392. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  26393. };
  26394. if (directLoad) {
  26395. loadSceneFromData(directLoad);
  26396. return;
  26397. }
  26398. if (rootUrl.indexOf("file:") === -1) {
  26399. if (scene.getEngine().enableOfflineSupport) {
  26400. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  26401. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  26402. }
  26403. else {
  26404. manifestChecked(true);
  26405. }
  26406. }
  26407. else {
  26408. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  26409. }
  26410. };
  26411. // Flags
  26412. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  26413. SceneLoader._ShowLoadingScreen = true;
  26414. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  26415. // Members
  26416. SceneLoader._registeredPlugins = {};
  26417. return SceneLoader;
  26418. })();
  26419. BABYLON.SceneLoader = SceneLoader;
  26420. ;
  26421. })(BABYLON || (BABYLON = {}));
  26422. var BABYLON;
  26423. (function (BABYLON) {
  26424. var Internals;
  26425. (function (Internals) {
  26426. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  26427. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  26428. var parsedMaterial = parsedData.materials[index];
  26429. if (parsedMaterial.id === id) {
  26430. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  26431. }
  26432. }
  26433. return null;
  26434. };
  26435. var isDescendantOf = function (mesh, names, hierarchyIds) {
  26436. names = (names instanceof Array) ? names : [names];
  26437. for (var i in names) {
  26438. if (mesh.name === names[i]) {
  26439. hierarchyIds.push(mesh.id);
  26440. return true;
  26441. }
  26442. }
  26443. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  26444. hierarchyIds.push(mesh.id);
  26445. return true;
  26446. }
  26447. return false;
  26448. };
  26449. var logOperation = function (operation, producer) {
  26450. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  26451. };
  26452. BABYLON.SceneLoader.RegisterPlugin({
  26453. extensions: ".babylon",
  26454. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  26455. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  26456. // when SceneLoader.debugLogging = true (default), or exception encountered.
  26457. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  26458. // and avoid problems with multiple concurrent .babylon loads.
  26459. var log = "importMesh has failed JSON parse";
  26460. try {
  26461. var parsedData = JSON.parse(data);
  26462. log = "";
  26463. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  26464. var loadedSkeletonsIds = [];
  26465. var loadedMaterialsIds = [];
  26466. var hierarchyIds = [];
  26467. var index;
  26468. var cache;
  26469. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  26470. var parsedMesh = parsedData.meshes[index];
  26471. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  26472. if (meshesNames instanceof Array) {
  26473. // Remove found mesh name from list.
  26474. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  26475. }
  26476. //Geometry?
  26477. if (parsedMesh.geometryId) {
  26478. //does the file contain geometries?
  26479. if (parsedData.geometries) {
  26480. //find the correct geometry and add it to the scene
  26481. var found = false;
  26482. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  26483. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  26484. return;
  26485. }
  26486. else {
  26487. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  26488. if (parsedGeometryData.id === parsedMesh.geometryId) {
  26489. switch (geometryType) {
  26490. case "boxes":
  26491. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  26492. break;
  26493. case "spheres":
  26494. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  26495. break;
  26496. case "cylinders":
  26497. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  26498. break;
  26499. case "toruses":
  26500. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  26501. break;
  26502. case "grounds":
  26503. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  26504. break;
  26505. case "planes":
  26506. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  26507. break;
  26508. case "torusKnots":
  26509. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  26510. break;
  26511. case "vertexData":
  26512. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  26513. break;
  26514. }
  26515. found = true;
  26516. }
  26517. });
  26518. }
  26519. });
  26520. if (!found) {
  26521. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  26522. }
  26523. }
  26524. }
  26525. // Material ?
  26526. if (parsedMesh.materialId) {
  26527. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  26528. if (!materialFound && parsedData.multiMaterials) {
  26529. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  26530. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  26531. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  26532. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  26533. var subMatId = parsedMultiMaterial.materials[matIndex];
  26534. loadedMaterialsIds.push(subMatId);
  26535. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  26536. log += "\n\tMaterial " + mat.toString(fullDetails);
  26537. }
  26538. loadedMaterialsIds.push(parsedMultiMaterial.id);
  26539. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  26540. materialFound = true;
  26541. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  26542. break;
  26543. }
  26544. }
  26545. }
  26546. if (!materialFound) {
  26547. loadedMaterialsIds.push(parsedMesh.materialId);
  26548. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  26549. if (!mat) {
  26550. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  26551. }
  26552. else {
  26553. log += "\n\tMaterial " + mat.toString(fullDetails);
  26554. }
  26555. }
  26556. }
  26557. // Skeleton ?
  26558. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  26559. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  26560. if (!skeletonAlreadyLoaded) {
  26561. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  26562. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  26563. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  26564. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  26565. skeletons.push(skeleton);
  26566. loadedSkeletonsIds.push(parsedSkeleton.id);
  26567. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  26568. }
  26569. }
  26570. }
  26571. }
  26572. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  26573. meshes.push(mesh);
  26574. log += "\n\tMesh " + mesh.toString(fullDetails);
  26575. }
  26576. }
  26577. // Connecting parents
  26578. var currentMesh;
  26579. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26580. currentMesh = scene.meshes[index];
  26581. if (currentMesh._waitingParentId) {
  26582. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  26583. currentMesh._waitingParentId = undefined;
  26584. }
  26585. }
  26586. // freeze and compute world matrix application
  26587. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26588. currentMesh = scene.meshes[index];
  26589. if (currentMesh._waitingFreezeWorldMatrix) {
  26590. currentMesh.freezeWorldMatrix();
  26591. currentMesh._waitingFreezeWorldMatrix = undefined;
  26592. }
  26593. else {
  26594. currentMesh.computeWorldMatrix(true);
  26595. }
  26596. }
  26597. // Particles
  26598. if (parsedData.particleSystems) {
  26599. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  26600. var parsedParticleSystem = parsedData.particleSystems[index];
  26601. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  26602. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  26603. }
  26604. }
  26605. }
  26606. return true;
  26607. }
  26608. catch (err) {
  26609. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  26610. log = null;
  26611. throw err;
  26612. }
  26613. finally {
  26614. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  26615. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  26616. }
  26617. }
  26618. },
  26619. load: function (scene, data, rootUrl) {
  26620. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  26621. // when SceneLoader.debugLogging = true (default), or exception encountered.
  26622. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  26623. // and avoid problems with multiple concurrent .babylon loads.
  26624. var log = "importScene has failed JSON parse";
  26625. try {
  26626. var parsedData = JSON.parse(data);
  26627. log = "";
  26628. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  26629. // Scene
  26630. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  26631. scene.autoClear = parsedData.autoClear;
  26632. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  26633. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  26634. if (parsedData.gravity) {
  26635. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  26636. }
  26637. // Fog
  26638. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  26639. scene.fogMode = parsedData.fogMode;
  26640. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  26641. scene.fogStart = parsedData.fogStart;
  26642. scene.fogEnd = parsedData.fogEnd;
  26643. scene.fogDensity = parsedData.fogDensity;
  26644. log += "\tFog mode for scene: ";
  26645. switch (scene.fogMode) {
  26646. // getters not compiling, so using hardcoded
  26647. case 1:
  26648. log += "exp\n";
  26649. break;
  26650. case 2:
  26651. log += "exp2\n";
  26652. break;
  26653. case 3:
  26654. log += "linear\n";
  26655. break;
  26656. }
  26657. }
  26658. //Physics
  26659. if (parsedData.physicsEnabled) {
  26660. var physicsPlugin;
  26661. if (parsedData.physicsEngine === "cannon") {
  26662. physicsPlugin = new BABYLON.CannonJSPlugin();
  26663. }
  26664. else if (parsedData.physicsEngine === "oimo") {
  26665. physicsPlugin = new BABYLON.OimoJSPlugin();
  26666. }
  26667. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  26668. //else - default engine, which is currently oimo
  26669. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  26670. scene.enablePhysics(physicsGravity, physicsPlugin);
  26671. }
  26672. //collisions, if defined. otherwise, default is true
  26673. if (parsedData.collisionsEnabled != undefined) {
  26674. scene.collisionsEnabled = parsedData.collisionsEnabled;
  26675. }
  26676. scene.workerCollisions = !!parsedData.workerCollisions;
  26677. var index;
  26678. var cache;
  26679. // Lights
  26680. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  26681. var parsedLight = parsedData.lights[index];
  26682. var light = BABYLON.Light.Parse(parsedLight, scene);
  26683. log += (index === 0 ? "\n\tLights:" : "");
  26684. log += "\n\t\t" + light.toString(fullDetails);
  26685. }
  26686. // Animations
  26687. if (parsedData.animations) {
  26688. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  26689. var parsedAnimation = parsedData.animations[index];
  26690. var animation = BABYLON.Animation.Parse(parsedAnimation);
  26691. scene.animations.push(animation);
  26692. log += (index === 0 ? "\n\tAnimations:" : "");
  26693. log += "\n\t\t" + animation.toString(fullDetails);
  26694. }
  26695. }
  26696. if (parsedData.autoAnimate) {
  26697. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  26698. }
  26699. // Materials
  26700. if (parsedData.materials) {
  26701. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  26702. var parsedMaterial = parsedData.materials[index];
  26703. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  26704. log += (index === 0 ? "\n\tMaterials:" : "");
  26705. log += "\n\t\t" + mat.toString(fullDetails);
  26706. }
  26707. }
  26708. if (parsedData.multiMaterials) {
  26709. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  26710. var parsedMultiMaterial = parsedData.multiMaterials[index];
  26711. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  26712. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  26713. log += "\n\t\t" + mmat.toString(fullDetails);
  26714. }
  26715. }
  26716. // Skeletons
  26717. if (parsedData.skeletons) {
  26718. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  26719. var parsedSkeleton = parsedData.skeletons[index];
  26720. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  26721. log += (index === 0 ? "\n\tSkeletons:" : "");
  26722. log += "\n\t\t" + skeleton.toString(fullDetails);
  26723. }
  26724. }
  26725. // Geometries
  26726. var geometries = parsedData.geometries;
  26727. if (geometries) {
  26728. // Boxes
  26729. var boxes = geometries.boxes;
  26730. if (boxes) {
  26731. for (index = 0, cache = boxes.length; index < cache; index++) {
  26732. var parsedBox = boxes[index];
  26733. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  26734. }
  26735. }
  26736. // Spheres
  26737. var spheres = geometries.spheres;
  26738. if (spheres) {
  26739. for (index = 0, cache = spheres.length; index < cache; index++) {
  26740. var parsedSphere = spheres[index];
  26741. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  26742. }
  26743. }
  26744. // Cylinders
  26745. var cylinders = geometries.cylinders;
  26746. if (cylinders) {
  26747. for (index = 0, cache = cylinders.length; index < cache; index++) {
  26748. var parsedCylinder = cylinders[index];
  26749. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  26750. }
  26751. }
  26752. // Toruses
  26753. var toruses = geometries.toruses;
  26754. if (toruses) {
  26755. for (index = 0, cache = toruses.length; index < cache; index++) {
  26756. var parsedTorus = toruses[index];
  26757. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  26758. }
  26759. }
  26760. // Grounds
  26761. var grounds = geometries.grounds;
  26762. if (grounds) {
  26763. for (index = 0, cache = grounds.length; index < cache; index++) {
  26764. var parsedGround = grounds[index];
  26765. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  26766. }
  26767. }
  26768. // Planes
  26769. var planes = geometries.planes;
  26770. if (planes) {
  26771. for (index = 0, cache = planes.length; index < cache; index++) {
  26772. var parsedPlane = planes[index];
  26773. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  26774. }
  26775. }
  26776. // TorusKnots
  26777. var torusKnots = geometries.torusKnots;
  26778. if (torusKnots) {
  26779. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  26780. var parsedTorusKnot = torusKnots[index];
  26781. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  26782. }
  26783. }
  26784. // VertexData
  26785. var vertexData = geometries.vertexData;
  26786. if (vertexData) {
  26787. for (index = 0, cache = vertexData.length; index < cache; index++) {
  26788. var parsedVertexData = vertexData[index];
  26789. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  26790. }
  26791. }
  26792. }
  26793. // Meshes
  26794. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  26795. var parsedMesh = parsedData.meshes[index];
  26796. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  26797. log += (index === 0 ? "\n\tMeshes:" : "");
  26798. log += "\n\t\t" + mesh.toString(fullDetails);
  26799. }
  26800. // Cameras
  26801. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  26802. var parsedCamera = parsedData.cameras[index];
  26803. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  26804. log += (index === 0 ? "\n\tCameras:" : "");
  26805. log += "\n\t\t" + camera.toString(fullDetails);
  26806. }
  26807. if (parsedData.activeCameraID) {
  26808. scene.setActiveCameraByID(parsedData.activeCameraID);
  26809. }
  26810. // Browsing all the graph to connect the dots
  26811. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  26812. var camera = scene.cameras[index];
  26813. if (camera._waitingParentId) {
  26814. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  26815. camera._waitingParentId = undefined;
  26816. }
  26817. }
  26818. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  26819. var light = scene.lights[index];
  26820. if (light._waitingParentId) {
  26821. light.parent = scene.getLastEntryByID(light._waitingParentId);
  26822. light._waitingParentId = undefined;
  26823. }
  26824. }
  26825. // Sounds
  26826. var loadedSounds = [];
  26827. var loadedSound;
  26828. if (BABYLON.AudioEngine && parsedData.sounds) {
  26829. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  26830. var parsedSound = parsedData.sounds[index];
  26831. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26832. if (!parsedSound.url)
  26833. parsedSound.url = parsedSound.name;
  26834. if (!loadedSounds[parsedSound.url]) {
  26835. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  26836. loadedSounds[parsedSound.url] = loadedSound;
  26837. }
  26838. else {
  26839. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  26840. }
  26841. }
  26842. else {
  26843. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  26844. }
  26845. }
  26846. }
  26847. loadedSounds = [];
  26848. // Connect parents & children and parse actions
  26849. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26850. var mesh = scene.meshes[index];
  26851. if (mesh._waitingParentId) {
  26852. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  26853. mesh._waitingParentId = undefined;
  26854. }
  26855. if (mesh._waitingActions) {
  26856. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  26857. mesh._waitingActions = undefined;
  26858. }
  26859. }
  26860. // freeze world matrix application
  26861. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26862. var currentMesh = scene.meshes[index];
  26863. if (currentMesh._waitingFreezeWorldMatrix) {
  26864. currentMesh.freezeWorldMatrix();
  26865. currentMesh._waitingFreezeWorldMatrix = undefined;
  26866. }
  26867. else {
  26868. currentMesh.computeWorldMatrix(true);
  26869. }
  26870. }
  26871. // Particles Systems
  26872. if (parsedData.particleSystems) {
  26873. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  26874. var parsedParticleSystem = parsedData.particleSystems[index];
  26875. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  26876. }
  26877. }
  26878. // Lens flares
  26879. if (parsedData.lensFlareSystems) {
  26880. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  26881. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  26882. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  26883. }
  26884. }
  26885. // Shadows
  26886. if (parsedData.shadowGenerators) {
  26887. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  26888. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  26889. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  26890. }
  26891. }
  26892. // Actions (scene)
  26893. if (parsedData.actions) {
  26894. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  26895. }
  26896. // Finish
  26897. return true;
  26898. }
  26899. catch (err) {
  26900. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  26901. log = null;
  26902. throw err;
  26903. }
  26904. finally {
  26905. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  26906. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  26907. }
  26908. }
  26909. }
  26910. });
  26911. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26912. })(BABYLON || (BABYLON = {}));
  26913. var BABYLON;
  26914. (function (BABYLON) {
  26915. var SpriteManager = (function () {
  26916. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  26917. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26918. this.name = name;
  26919. this.sprites = new Array();
  26920. this.renderingGroupId = 0;
  26921. this.layerMask = 0x0FFFFFFF;
  26922. this.fogEnabled = true;
  26923. this.isPickable = false;
  26924. /**
  26925. * An event triggered when the manager is disposed.
  26926. * @type {BABYLON.Observable}
  26927. */
  26928. this.onDisposeObservable = new BABYLON.Observable();
  26929. this._vertexBuffers = {};
  26930. this._capacity = capacity;
  26931. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  26932. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26933. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26934. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  26935. if (cellSize.width) {
  26936. this.cellWidth = cellSize.width;
  26937. this.cellHeight = cellSize.height;
  26938. }
  26939. else {
  26940. this.cellWidth = cellSize;
  26941. this.cellHeight = cellSize;
  26942. }
  26943. this._scene = scene;
  26944. this._scene.spriteManagers.push(this);
  26945. var indices = [];
  26946. var index = 0;
  26947. for (var count = 0; count < capacity; count++) {
  26948. indices.push(index);
  26949. indices.push(index + 1);
  26950. indices.push(index + 2);
  26951. indices.push(index);
  26952. indices.push(index + 2);
  26953. indices.push(index + 3);
  26954. index += 4;
  26955. }
  26956. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  26957. // VBO
  26958. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  26959. this._vertexData = new Float32Array(capacity * 16 * 4);
  26960. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  26961. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  26962. var options = this._buffer.createVertexBuffer("options", 4, 4);
  26963. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  26964. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  26965. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  26966. this._vertexBuffers["options"] = options;
  26967. this._vertexBuffers["cellInfo"] = cellInfo;
  26968. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  26969. // Effects
  26970. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  26971. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  26972. }
  26973. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  26974. set: function (callback) {
  26975. if (this._onDisposeObserver) {
  26976. this.onDisposeObservable.remove(this._onDisposeObserver);
  26977. }
  26978. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26979. },
  26980. enumerable: true,
  26981. configurable: true
  26982. });
  26983. Object.defineProperty(SpriteManager.prototype, "texture", {
  26984. get: function () {
  26985. return this._spriteTexture;
  26986. },
  26987. set: function (value) {
  26988. this._spriteTexture = value;
  26989. },
  26990. enumerable: true,
  26991. configurable: true
  26992. });
  26993. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  26994. var arrayOffset = index * 16;
  26995. if (offsetX === 0)
  26996. offsetX = this._epsilon;
  26997. else if (offsetX === 1)
  26998. offsetX = 1 - this._epsilon;
  26999. if (offsetY === 0)
  27000. offsetY = this._epsilon;
  27001. else if (offsetY === 1)
  27002. offsetY = 1 - this._epsilon;
  27003. this._vertexData[arrayOffset] = sprite.position.x;
  27004. this._vertexData[arrayOffset + 1] = sprite.position.y;
  27005. this._vertexData[arrayOffset + 2] = sprite.position.z;
  27006. this._vertexData[arrayOffset + 3] = sprite.angle;
  27007. this._vertexData[arrayOffset + 4] = sprite.width;
  27008. this._vertexData[arrayOffset + 5] = sprite.height;
  27009. this._vertexData[arrayOffset + 6] = offsetX;
  27010. this._vertexData[arrayOffset + 7] = offsetY;
  27011. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  27012. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  27013. var offset = (sprite.cellIndex / rowSize) >> 0;
  27014. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  27015. this._vertexData[arrayOffset + 11] = offset;
  27016. // Color
  27017. this._vertexData[arrayOffset + 12] = sprite.color.r;
  27018. this._vertexData[arrayOffset + 13] = sprite.color.g;
  27019. this._vertexData[arrayOffset + 14] = sprite.color.b;
  27020. this._vertexData[arrayOffset + 15] = sprite.color.a;
  27021. };
  27022. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  27023. var count = Math.min(this._capacity, this.sprites.length);
  27024. var min = BABYLON.Vector3.Zero();
  27025. var max = BABYLON.Vector3.Zero();
  27026. var distance = Number.MAX_VALUE;
  27027. var currentSprite;
  27028. var cameraSpacePosition = BABYLON.Vector3.Zero();
  27029. var cameraView = camera.getViewMatrix();
  27030. for (var index = 0; index < count; index++) {
  27031. var sprite = this.sprites[index];
  27032. if (!sprite) {
  27033. continue;
  27034. }
  27035. if (predicate) {
  27036. if (!predicate(sprite)) {
  27037. continue;
  27038. }
  27039. }
  27040. else if (!sprite.isPickable) {
  27041. continue;
  27042. }
  27043. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  27044. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  27045. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  27046. if (ray.intersectsBoxMinMax(min, max)) {
  27047. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  27048. if (distance > currentDistance) {
  27049. distance = currentDistance;
  27050. currentSprite = sprite;
  27051. if (fastCheck) {
  27052. break;
  27053. }
  27054. }
  27055. }
  27056. }
  27057. if (currentSprite) {
  27058. var result = new BABYLON.PickingInfo();
  27059. result.hit = true;
  27060. result.pickedSprite = currentSprite;
  27061. result.distance = distance;
  27062. return result;
  27063. }
  27064. return null;
  27065. };
  27066. SpriteManager.prototype.render = function () {
  27067. // Check
  27068. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  27069. return;
  27070. var engine = this._scene.getEngine();
  27071. var baseSize = this._spriteTexture.getBaseSize();
  27072. // Sprites
  27073. var deltaTime = engine.getDeltaTime();
  27074. var max = Math.min(this._capacity, this.sprites.length);
  27075. var rowSize = baseSize.width / this.cellWidth;
  27076. var offset = 0;
  27077. for (var index = 0; index < max; index++) {
  27078. var sprite = this.sprites[index];
  27079. if (!sprite) {
  27080. continue;
  27081. }
  27082. sprite._animate(deltaTime);
  27083. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  27084. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  27085. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  27086. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  27087. }
  27088. this._buffer.update(this._vertexData);
  27089. // Render
  27090. var effect = this._effectBase;
  27091. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  27092. effect = this._effectFog;
  27093. }
  27094. engine.enableEffect(effect);
  27095. var viewMatrix = this._scene.getViewMatrix();
  27096. effect.setTexture("diffuseSampler", this._spriteTexture);
  27097. effect.setMatrix("view", viewMatrix);
  27098. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  27099. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  27100. // Fog
  27101. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  27102. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  27103. effect.setColor3("vFogColor", this._scene.fogColor);
  27104. }
  27105. // VBOs
  27106. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27107. // Draw order
  27108. engine.setDepthFunctionToLessOrEqual();
  27109. effect.setBool("alphaTest", true);
  27110. engine.setColorWrite(false);
  27111. engine.draw(true, 0, max * 6);
  27112. engine.setColorWrite(true);
  27113. effect.setBool("alphaTest", false);
  27114. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27115. engine.draw(true, 0, max * 6);
  27116. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27117. };
  27118. SpriteManager.prototype.dispose = function () {
  27119. if (this._buffer) {
  27120. this._buffer.dispose();
  27121. this._buffer = null;
  27122. }
  27123. if (this._indexBuffer) {
  27124. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27125. this._indexBuffer = null;
  27126. }
  27127. if (this._spriteTexture) {
  27128. this._spriteTexture.dispose();
  27129. this._spriteTexture = null;
  27130. }
  27131. // Remove from scene
  27132. var index = this._scene.spriteManagers.indexOf(this);
  27133. this._scene.spriteManagers.splice(index, 1);
  27134. // Callback
  27135. this.onDisposeObservable.notifyObservers(this);
  27136. this.onDisposeObservable.clear();
  27137. };
  27138. return SpriteManager;
  27139. })();
  27140. BABYLON.SpriteManager = SpriteManager;
  27141. })(BABYLON || (BABYLON = {}));
  27142. var BABYLON;
  27143. (function (BABYLON) {
  27144. var Sprite = (function () {
  27145. function Sprite(name, manager) {
  27146. this.name = name;
  27147. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27148. this.width = 1.0;
  27149. this.height = 1.0;
  27150. this.angle = 0;
  27151. this.cellIndex = 0;
  27152. this.invertU = 0;
  27153. this.invertV = 0;
  27154. this.animations = new Array();
  27155. this.isPickable = false;
  27156. this._animationStarted = false;
  27157. this._loopAnimation = false;
  27158. this._fromIndex = 0;
  27159. this._toIndex = 0;
  27160. this._delay = 0;
  27161. this._direction = 1;
  27162. this._frameCount = 0;
  27163. this._time = 0;
  27164. this._manager = manager;
  27165. this._manager.sprites.push(this);
  27166. this.position = BABYLON.Vector3.Zero();
  27167. }
  27168. Object.defineProperty(Sprite.prototype, "size", {
  27169. get: function () {
  27170. return this.width;
  27171. },
  27172. set: function (value) {
  27173. this.width = value;
  27174. this.height = value;
  27175. },
  27176. enumerable: true,
  27177. configurable: true
  27178. });
  27179. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  27180. this._fromIndex = from;
  27181. this._toIndex = to;
  27182. this._loopAnimation = loop;
  27183. this._delay = delay;
  27184. this._animationStarted = true;
  27185. this._direction = from < to ? 1 : -1;
  27186. this.cellIndex = from;
  27187. this._time = 0;
  27188. this._onAnimationEnd = onAnimationEnd;
  27189. };
  27190. Sprite.prototype.stopAnimation = function () {
  27191. this._animationStarted = false;
  27192. };
  27193. Sprite.prototype._animate = function (deltaTime) {
  27194. if (!this._animationStarted)
  27195. return;
  27196. this._time += deltaTime;
  27197. if (this._time > this._delay) {
  27198. this._time = this._time % this._delay;
  27199. this.cellIndex += this._direction;
  27200. if (this.cellIndex === this._toIndex) {
  27201. if (this._loopAnimation) {
  27202. this.cellIndex = this._fromIndex;
  27203. }
  27204. else {
  27205. this._animationStarted = false;
  27206. if (this._onAnimationEnd) {
  27207. this._onAnimationEnd();
  27208. }
  27209. if (this.disposeWhenFinishedAnimating) {
  27210. this.dispose();
  27211. }
  27212. }
  27213. }
  27214. }
  27215. };
  27216. Sprite.prototype.dispose = function () {
  27217. for (var i = 0; i < this._manager.sprites.length; i++) {
  27218. if (this._manager.sprites[i] == this) {
  27219. this._manager.sprites.splice(i, 1);
  27220. }
  27221. }
  27222. };
  27223. return Sprite;
  27224. })();
  27225. BABYLON.Sprite = Sprite;
  27226. })(BABYLON || (BABYLON = {}));
  27227. var BABYLON;
  27228. (function (BABYLON) {
  27229. var Layer = (function () {
  27230. function Layer(name, imgUrl, scene, isBackground, color) {
  27231. this.name = name;
  27232. this.scale = new BABYLON.Vector2(1, 1);
  27233. this.offset = new BABYLON.Vector2(0, 0);
  27234. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  27235. this._vertexBuffers = {};
  27236. // Events
  27237. /**
  27238. * An event triggered when the layer is disposed.
  27239. * @type {BABYLON.Observable}
  27240. */
  27241. this.onDisposeObservable = new BABYLON.Observable();
  27242. /**
  27243. * An event triggered before rendering the scene
  27244. * @type {BABYLON.Observable}
  27245. */
  27246. this.onBeforeRenderObservable = new BABYLON.Observable();
  27247. /**
  27248. * An event triggered after rendering the scene
  27249. * @type {BABYLON.Observable}
  27250. */
  27251. this.onAfterRenderObservable = new BABYLON.Observable();
  27252. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  27253. this.isBackground = isBackground === undefined ? true : isBackground;
  27254. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  27255. this._scene = scene;
  27256. this._scene.layers.push(this);
  27257. var engine = scene.getEngine();
  27258. // VBO
  27259. var vertices = [];
  27260. vertices.push(1, 1);
  27261. vertices.push(-1, 1);
  27262. vertices.push(-1, -1);
  27263. vertices.push(1, -1);
  27264. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  27265. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  27266. // Indices
  27267. var indices = [];
  27268. indices.push(0);
  27269. indices.push(1);
  27270. indices.push(2);
  27271. indices.push(0);
  27272. indices.push(2);
  27273. indices.push(3);
  27274. this._indexBuffer = engine.createIndexBuffer(indices);
  27275. // Effects
  27276. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  27277. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  27278. }
  27279. Object.defineProperty(Layer.prototype, "onDispose", {
  27280. set: function (callback) {
  27281. if (this._onDisposeObserver) {
  27282. this.onDisposeObservable.remove(this._onDisposeObserver);
  27283. }
  27284. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27285. },
  27286. enumerable: true,
  27287. configurable: true
  27288. });
  27289. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  27290. set: function (callback) {
  27291. if (this._onBeforeRenderObserver) {
  27292. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  27293. }
  27294. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  27295. },
  27296. enumerable: true,
  27297. configurable: true
  27298. });
  27299. Object.defineProperty(Layer.prototype, "onAfterRender", {
  27300. set: function (callback) {
  27301. if (this._onAfterRenderObserver) {
  27302. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  27303. }
  27304. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  27305. },
  27306. enumerable: true,
  27307. configurable: true
  27308. });
  27309. Layer.prototype.render = function () {
  27310. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  27311. // Check
  27312. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  27313. return;
  27314. var engine = this._scene.getEngine();
  27315. this.onBeforeRenderObservable.notifyObservers(this);
  27316. // Render
  27317. engine.enableEffect(currentEffect);
  27318. engine.setState(false);
  27319. // Texture
  27320. currentEffect.setTexture("textureSampler", this.texture);
  27321. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  27322. // Color
  27323. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  27324. // Scale / offset
  27325. currentEffect.setVector2("offset", this.offset);
  27326. currentEffect.setVector2("scale", this.scale);
  27327. // VBOs
  27328. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  27329. // Draw order
  27330. if (!this._alphaTestEffect) {
  27331. engine.setAlphaMode(this.alphaBlendingMode);
  27332. engine.draw(true, 0, 6);
  27333. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27334. }
  27335. else {
  27336. engine.draw(true, 0, 6);
  27337. }
  27338. this.onAfterRenderObservable.notifyObservers(this);
  27339. };
  27340. Layer.prototype.dispose = function () {
  27341. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  27342. if (vertexBuffer) {
  27343. vertexBuffer.dispose();
  27344. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  27345. }
  27346. if (this._indexBuffer) {
  27347. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27348. this._indexBuffer = null;
  27349. }
  27350. if (this.texture) {
  27351. this.texture.dispose();
  27352. this.texture = null;
  27353. }
  27354. // Remove from scene
  27355. var index = this._scene.layers.indexOf(this);
  27356. this._scene.layers.splice(index, 1);
  27357. // Callback
  27358. this.onDisposeObservable.notifyObservers(this);
  27359. this.onDisposeObservable.clear();
  27360. this.onAfterRenderObservable.clear();
  27361. this.onBeforeRenderObservable.clear();
  27362. };
  27363. return Layer;
  27364. })();
  27365. BABYLON.Layer = Layer;
  27366. })(BABYLON || (BABYLON = {}));
  27367. var BABYLON;
  27368. (function (BABYLON) {
  27369. var Particle = (function () {
  27370. function Particle() {
  27371. this.position = BABYLON.Vector3.Zero();
  27372. this.direction = BABYLON.Vector3.Zero();
  27373. this.color = new BABYLON.Color4(0, 0, 0, 0);
  27374. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  27375. this.lifeTime = 1.0;
  27376. this.age = 0;
  27377. this.size = 0;
  27378. this.angle = 0;
  27379. this.angularSpeed = 0;
  27380. }
  27381. Particle.prototype.copyTo = function (other) {
  27382. other.position.copyFrom(this.position);
  27383. other.direction.copyFrom(this.direction);
  27384. other.color.copyFrom(this.color);
  27385. other.colorStep.copyFrom(this.colorStep);
  27386. other.lifeTime = this.lifeTime;
  27387. other.age = this.age;
  27388. other.size = this.size;
  27389. other.angle = this.angle;
  27390. other.angularSpeed = this.angularSpeed;
  27391. };
  27392. return Particle;
  27393. })();
  27394. BABYLON.Particle = Particle;
  27395. })(BABYLON || (BABYLON = {}));
  27396. var BABYLON;
  27397. (function (BABYLON) {
  27398. var randomNumber = function (min, max) {
  27399. if (min === max) {
  27400. return (min);
  27401. }
  27402. var random = Math.random();
  27403. return ((random * (max - min)) + min);
  27404. };
  27405. var ParticleSystem = (function () {
  27406. function ParticleSystem(name, capacity, scene, customEffect) {
  27407. var _this = this;
  27408. this.name = name;
  27409. // Members
  27410. this.animations = [];
  27411. this.renderingGroupId = 0;
  27412. this.emitter = null;
  27413. this.emitRate = 10;
  27414. this.manualEmitCount = -1;
  27415. this.updateSpeed = 0.01;
  27416. this.targetStopDuration = 0;
  27417. this.disposeOnStop = false;
  27418. this.minEmitPower = 1;
  27419. this.maxEmitPower = 1;
  27420. this.minLifeTime = 1;
  27421. this.maxLifeTime = 1;
  27422. this.minSize = 1;
  27423. this.maxSize = 1;
  27424. this.minAngularSpeed = 0;
  27425. this.maxAngularSpeed = 0;
  27426. this.layerMask = 0x0FFFFFFF;
  27427. /**
  27428. * An event triggered when the system is disposed.
  27429. * @type {BABYLON.Observable}
  27430. */
  27431. this.onDisposeObservable = new BABYLON.Observable();
  27432. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  27433. this.forceDepthWrite = false;
  27434. this.gravity = BABYLON.Vector3.Zero();
  27435. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  27436. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  27437. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  27438. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  27439. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27440. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27441. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  27442. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27443. this.particles = new Array();
  27444. this._stockParticles = new Array();
  27445. this._newPartsExcess = 0;
  27446. this._vertexBuffers = {};
  27447. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  27448. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  27449. this._scaledDirection = BABYLON.Vector3.Zero();
  27450. this._scaledGravity = BABYLON.Vector3.Zero();
  27451. this._currentRenderId = -1;
  27452. this._started = false;
  27453. this._stopped = false;
  27454. this._actualFrame = 0;
  27455. this.id = name;
  27456. this._capacity = capacity;
  27457. this._scene = scene;
  27458. this._customEffect = customEffect;
  27459. scene.particleSystems.push(this);
  27460. var indices = [];
  27461. var index = 0;
  27462. for (var count = 0; count < capacity; count++) {
  27463. indices.push(index);
  27464. indices.push(index + 1);
  27465. indices.push(index + 2);
  27466. indices.push(index);
  27467. indices.push(index + 2);
  27468. indices.push(index + 3);
  27469. index += 4;
  27470. }
  27471. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  27472. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  27473. this._vertexData = new Float32Array(capacity * 11 * 4);
  27474. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  27475. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  27476. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  27477. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  27478. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  27479. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  27480. this._vertexBuffers["options"] = options;
  27481. // Default behaviors
  27482. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  27483. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  27484. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  27485. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  27486. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  27487. };
  27488. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  27489. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  27490. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  27491. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  27492. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  27493. };
  27494. this.updateFunction = function (particles) {
  27495. for (var index = 0; index < particles.length; index++) {
  27496. var particle = particles[index];
  27497. particle.age += _this._scaledUpdateSpeed;
  27498. if (particle.age >= particle.lifeTime) {
  27499. _this.recycleParticle(particle);
  27500. index--;
  27501. continue;
  27502. }
  27503. else {
  27504. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  27505. particle.color.addInPlace(_this._scaledColorStep);
  27506. if (particle.color.a < 0)
  27507. particle.color.a = 0;
  27508. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  27509. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  27510. particle.position.addInPlace(_this._scaledDirection);
  27511. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  27512. particle.direction.addInPlace(_this._scaledGravity);
  27513. }
  27514. }
  27515. };
  27516. }
  27517. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  27518. set: function (callback) {
  27519. if (this._onDisposeObserver) {
  27520. this.onDisposeObservable.remove(this._onDisposeObserver);
  27521. }
  27522. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27523. },
  27524. enumerable: true,
  27525. configurable: true
  27526. });
  27527. ParticleSystem.prototype.recycleParticle = function (particle) {
  27528. var lastParticle = this.particles.pop();
  27529. if (lastParticle !== particle) {
  27530. lastParticle.copyTo(particle);
  27531. this._stockParticles.push(lastParticle);
  27532. }
  27533. };
  27534. ParticleSystem.prototype.getCapacity = function () {
  27535. return this._capacity;
  27536. };
  27537. ParticleSystem.prototype.isAlive = function () {
  27538. return this._alive;
  27539. };
  27540. ParticleSystem.prototype.isStarted = function () {
  27541. return this._started;
  27542. };
  27543. ParticleSystem.prototype.start = function () {
  27544. this._started = true;
  27545. this._stopped = false;
  27546. this._actualFrame = 0;
  27547. };
  27548. ParticleSystem.prototype.stop = function () {
  27549. this._stopped = true;
  27550. };
  27551. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  27552. var offset = index * 11;
  27553. this._vertexData[offset] = particle.position.x;
  27554. this._vertexData[offset + 1] = particle.position.y;
  27555. this._vertexData[offset + 2] = particle.position.z;
  27556. this._vertexData[offset + 3] = particle.color.r;
  27557. this._vertexData[offset + 4] = particle.color.g;
  27558. this._vertexData[offset + 5] = particle.color.b;
  27559. this._vertexData[offset + 6] = particle.color.a;
  27560. this._vertexData[offset + 7] = particle.angle;
  27561. this._vertexData[offset + 8] = particle.size;
  27562. this._vertexData[offset + 9] = offsetX;
  27563. this._vertexData[offset + 10] = offsetY;
  27564. };
  27565. ParticleSystem.prototype._update = function (newParticles) {
  27566. // Update current
  27567. this._alive = this.particles.length > 0;
  27568. this.updateFunction(this.particles);
  27569. // Add new ones
  27570. var worldMatrix;
  27571. if (this.emitter.position) {
  27572. worldMatrix = this.emitter.getWorldMatrix();
  27573. }
  27574. else {
  27575. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  27576. }
  27577. var particle;
  27578. for (var index = 0; index < newParticles; index++) {
  27579. if (this.particles.length === this._capacity) {
  27580. break;
  27581. }
  27582. if (this._stockParticles.length !== 0) {
  27583. particle = this._stockParticles.pop();
  27584. particle.age = 0;
  27585. }
  27586. else {
  27587. particle = new BABYLON.Particle();
  27588. }
  27589. this.particles.push(particle);
  27590. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  27591. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  27592. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  27593. particle.size = randomNumber(this.minSize, this.maxSize);
  27594. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  27595. this.startPositionFunction(worldMatrix, particle.position, particle);
  27596. var step = randomNumber(0, 1.0);
  27597. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  27598. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  27599. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  27600. }
  27601. };
  27602. ParticleSystem.prototype._getEffect = function () {
  27603. if (this._customEffect) {
  27604. return this._customEffect;
  27605. }
  27606. ;
  27607. var defines = [];
  27608. if (this._scene.clipPlane) {
  27609. defines.push("#define CLIPPLANE");
  27610. }
  27611. // Effect
  27612. var join = defines.join("\n");
  27613. if (this._cachedDefines !== join) {
  27614. this._cachedDefines = join;
  27615. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  27616. }
  27617. return this._effect;
  27618. };
  27619. ParticleSystem.prototype.animate = function () {
  27620. if (!this._started)
  27621. return;
  27622. var effect = this._getEffect();
  27623. // Check
  27624. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  27625. return;
  27626. if (this._currentRenderId === this._scene.getRenderId()) {
  27627. return;
  27628. }
  27629. this._currentRenderId = this._scene.getRenderId();
  27630. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  27631. // determine the number of particles we need to create
  27632. var newParticles;
  27633. if (this.manualEmitCount > -1) {
  27634. newParticles = this.manualEmitCount;
  27635. this._newPartsExcess = 0;
  27636. this.manualEmitCount = 0;
  27637. }
  27638. else {
  27639. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  27640. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  27641. }
  27642. if (this._newPartsExcess > 1.0) {
  27643. newParticles += this._newPartsExcess >> 0;
  27644. this._newPartsExcess -= this._newPartsExcess >> 0;
  27645. }
  27646. this._alive = false;
  27647. if (!this._stopped) {
  27648. this._actualFrame += this._scaledUpdateSpeed;
  27649. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  27650. this.stop();
  27651. }
  27652. else {
  27653. newParticles = 0;
  27654. }
  27655. this._update(newParticles);
  27656. // Stopped?
  27657. if (this._stopped) {
  27658. if (!this._alive) {
  27659. this._started = false;
  27660. if (this.disposeOnStop) {
  27661. this._scene._toBeDisposed.push(this);
  27662. }
  27663. }
  27664. }
  27665. // Update VBO
  27666. var offset = 0;
  27667. for (var index = 0; index < this.particles.length; index++) {
  27668. var particle = this.particles[index];
  27669. this._appendParticleVertex(offset++, particle, 0, 0);
  27670. this._appendParticleVertex(offset++, particle, 1, 0);
  27671. this._appendParticleVertex(offset++, particle, 1, 1);
  27672. this._appendParticleVertex(offset++, particle, 0, 1);
  27673. }
  27674. this._vertexBuffer.update(this._vertexData);
  27675. };
  27676. ParticleSystem.prototype.render = function () {
  27677. var effect = this._getEffect();
  27678. // Check
  27679. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  27680. return 0;
  27681. var engine = this._scene.getEngine();
  27682. // Render
  27683. engine.enableEffect(effect);
  27684. engine.setState(false);
  27685. var viewMatrix = this._scene.getViewMatrix();
  27686. effect.setTexture("diffuseSampler", this.particleTexture);
  27687. effect.setMatrix("view", viewMatrix);
  27688. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  27689. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  27690. if (this._scene.clipPlane) {
  27691. var clipPlane = this._scene.clipPlane;
  27692. var invView = viewMatrix.clone();
  27693. invView.invert();
  27694. effect.setMatrix("invView", invView);
  27695. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  27696. }
  27697. // VBOs
  27698. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27699. // Draw order
  27700. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  27701. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  27702. }
  27703. else {
  27704. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27705. }
  27706. if (this.forceDepthWrite) {
  27707. engine.setDepthWrite(true);
  27708. }
  27709. engine.draw(true, 0, this.particles.length * 6);
  27710. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27711. return this.particles.length;
  27712. };
  27713. ParticleSystem.prototype.dispose = function () {
  27714. if (this._vertexBuffer) {
  27715. this._vertexBuffer.dispose();
  27716. this._vertexBuffer = null;
  27717. }
  27718. if (this._indexBuffer) {
  27719. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27720. this._indexBuffer = null;
  27721. }
  27722. if (this.particleTexture) {
  27723. this.particleTexture.dispose();
  27724. this.particleTexture = null;
  27725. }
  27726. // Remove from scene
  27727. var index = this._scene.particleSystems.indexOf(this);
  27728. this._scene.particleSystems.splice(index, 1);
  27729. // Callback
  27730. this.onDisposeObservable.notifyObservers(this);
  27731. this.onDisposeObservable.clear();
  27732. };
  27733. // Clone
  27734. ParticleSystem.prototype.clone = function (name, newEmitter) {
  27735. var result = new ParticleSystem(name, this._capacity, this._scene);
  27736. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  27737. if (newEmitter === undefined) {
  27738. newEmitter = this.emitter;
  27739. }
  27740. result.emitter = newEmitter;
  27741. if (this.particleTexture) {
  27742. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  27743. }
  27744. result.start();
  27745. return result;
  27746. };
  27747. ParticleSystem.prototype.serialize = function () {
  27748. var serializationObject = {};
  27749. serializationObject.name = this.name;
  27750. serializationObject.id = this.id;
  27751. // Emitter
  27752. if (this.emitter.position) {
  27753. serializationObject.emitterId = this.emitter.id;
  27754. }
  27755. else {
  27756. serializationObject.emitter = this.emitter.asArray();
  27757. }
  27758. serializationObject.capacity = this.getCapacity();
  27759. if (this.particleTexture) {
  27760. serializationObject.textureName = this.particleTexture.name;
  27761. }
  27762. // Animations
  27763. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27764. // Particle system
  27765. serializationObject.minAngularSpeed = this.minAngularSpeed;
  27766. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  27767. serializationObject.minSize = this.minSize;
  27768. serializationObject.maxSize = this.maxSize;
  27769. serializationObject.minEmitPower = this.minEmitPower;
  27770. serializationObject.maxEmitPower = this.maxEmitPower;
  27771. serializationObject.minLifeTime = this.minLifeTime;
  27772. serializationObject.maxLifeTime = this.maxLifeTime;
  27773. serializationObject.emitRate = this.emitRate;
  27774. serializationObject.minEmitBox = this.minEmitBox.asArray();
  27775. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  27776. serializationObject.gravity = this.gravity.asArray();
  27777. serializationObject.direction1 = this.direction1.asArray();
  27778. serializationObject.direction2 = this.direction2.asArray();
  27779. serializationObject.color1 = this.color1.asArray();
  27780. serializationObject.color2 = this.color2.asArray();
  27781. serializationObject.colorDead = this.colorDead.asArray();
  27782. serializationObject.updateSpeed = this.updateSpeed;
  27783. serializationObject.targetStopDuration = this.targetStopDuration;
  27784. serializationObject.textureMask = this.textureMask.asArray();
  27785. serializationObject.blendMode = this.blendMode;
  27786. return serializationObject;
  27787. };
  27788. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  27789. var name = parsedParticleSystem.name;
  27790. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  27791. if (parsedParticleSystem.id) {
  27792. particleSystem.id = parsedParticleSystem.id;
  27793. }
  27794. // Texture
  27795. if (parsedParticleSystem.textureName) {
  27796. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  27797. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  27798. }
  27799. // Emitter
  27800. if (parsedParticleSystem.emitterId) {
  27801. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  27802. }
  27803. else {
  27804. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  27805. }
  27806. // Animations
  27807. if (parsedParticleSystem.animations) {
  27808. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  27809. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  27810. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27811. }
  27812. }
  27813. if (parsedParticleSystem.autoAnimate) {
  27814. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  27815. }
  27816. // Particle system
  27817. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  27818. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  27819. particleSystem.minSize = parsedParticleSystem.minSize;
  27820. particleSystem.maxSize = parsedParticleSystem.maxSize;
  27821. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  27822. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  27823. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  27824. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  27825. particleSystem.emitRate = parsedParticleSystem.emitRate;
  27826. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  27827. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  27828. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  27829. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  27830. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  27831. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  27832. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  27833. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  27834. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  27835. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  27836. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  27837. particleSystem.blendMode = parsedParticleSystem.blendMode;
  27838. if (!parsedParticleSystem.preventAutoStart) {
  27839. particleSystem.start();
  27840. }
  27841. return particleSystem;
  27842. };
  27843. // Statics
  27844. ParticleSystem.BLENDMODE_ONEONE = 0;
  27845. ParticleSystem.BLENDMODE_STANDARD = 1;
  27846. return ParticleSystem;
  27847. })();
  27848. BABYLON.ParticleSystem = ParticleSystem;
  27849. })(BABYLON || (BABYLON = {}));
  27850. var BABYLON;
  27851. (function (BABYLON) {
  27852. var AnimationRange = (function () {
  27853. function AnimationRange(name, from, to) {
  27854. this.name = name;
  27855. this.from = from;
  27856. this.to = to;
  27857. }
  27858. AnimationRange.prototype.clone = function () {
  27859. return new AnimationRange(this.name, this.from, this.to);
  27860. };
  27861. return AnimationRange;
  27862. })();
  27863. BABYLON.AnimationRange = AnimationRange;
  27864. /**
  27865. * Composed of a frame, and an action function
  27866. */
  27867. var AnimationEvent = (function () {
  27868. function AnimationEvent(frame, action, onlyOnce) {
  27869. this.frame = frame;
  27870. this.action = action;
  27871. this.onlyOnce = onlyOnce;
  27872. this.isDone = false;
  27873. }
  27874. return AnimationEvent;
  27875. })();
  27876. BABYLON.AnimationEvent = AnimationEvent;
  27877. var PathCursor = (function () {
  27878. function PathCursor(path) {
  27879. this.path = path;
  27880. this._onchange = new Array();
  27881. this.value = 0;
  27882. this.animations = new Array();
  27883. }
  27884. PathCursor.prototype.getPoint = function () {
  27885. var point = this.path.getPointAtLengthPosition(this.value);
  27886. return new BABYLON.Vector3(point.x, 0, point.y);
  27887. };
  27888. PathCursor.prototype.moveAhead = function (step) {
  27889. if (step === void 0) { step = 0.002; }
  27890. this.move(step);
  27891. return this;
  27892. };
  27893. PathCursor.prototype.moveBack = function (step) {
  27894. if (step === void 0) { step = 0.002; }
  27895. this.move(-step);
  27896. return this;
  27897. };
  27898. PathCursor.prototype.move = function (step) {
  27899. if (Math.abs(step) > 1) {
  27900. throw "step size should be less than 1.";
  27901. }
  27902. this.value += step;
  27903. this.ensureLimits();
  27904. this.raiseOnChange();
  27905. return this;
  27906. };
  27907. PathCursor.prototype.ensureLimits = function () {
  27908. while (this.value > 1) {
  27909. this.value -= 1;
  27910. }
  27911. while (this.value < 0) {
  27912. this.value += 1;
  27913. }
  27914. return this;
  27915. };
  27916. // used by animation engine
  27917. PathCursor.prototype.markAsDirty = function (propertyName) {
  27918. this.ensureLimits();
  27919. this.raiseOnChange();
  27920. return this;
  27921. };
  27922. PathCursor.prototype.raiseOnChange = function () {
  27923. var _this = this;
  27924. this._onchange.forEach(function (f) { return f(_this); });
  27925. return this;
  27926. };
  27927. PathCursor.prototype.onchange = function (f) {
  27928. this._onchange.push(f);
  27929. return this;
  27930. };
  27931. return PathCursor;
  27932. })();
  27933. BABYLON.PathCursor = PathCursor;
  27934. var Animation = (function () {
  27935. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  27936. this.name = name;
  27937. this.targetProperty = targetProperty;
  27938. this.framePerSecond = framePerSecond;
  27939. this.dataType = dataType;
  27940. this.loopMode = loopMode;
  27941. this.enableBlending = enableBlending;
  27942. this._offsetsCache = {};
  27943. this._highLimitsCache = {};
  27944. this._stopped = false;
  27945. this._blendingFactor = 0;
  27946. // The set of event that will be linked to this animation
  27947. this._events = new Array();
  27948. this.allowMatricesInterpolation = false;
  27949. this.blendingSpeed = 0.01;
  27950. this._ranges = {};
  27951. this.targetPropertyPath = targetProperty.split(".");
  27952. this.dataType = dataType;
  27953. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  27954. }
  27955. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  27956. var dataType = undefined;
  27957. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  27958. dataType = Animation.ANIMATIONTYPE_FLOAT;
  27959. }
  27960. else if (from instanceof BABYLON.Quaternion) {
  27961. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  27962. }
  27963. else if (from instanceof BABYLON.Vector3) {
  27964. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  27965. }
  27966. else if (from instanceof BABYLON.Vector2) {
  27967. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  27968. }
  27969. else if (from instanceof BABYLON.Color3) {
  27970. dataType = Animation.ANIMATIONTYPE_COLOR3;
  27971. }
  27972. else if (from instanceof BABYLON.Size) {
  27973. dataType = Animation.ANIMATIONTYPE_SIZE;
  27974. }
  27975. if (dataType == undefined) {
  27976. return null;
  27977. }
  27978. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  27979. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  27980. animation.setKeys(keys);
  27981. if (easingFunction !== undefined) {
  27982. animation.setEasingFunction(easingFunction);
  27983. }
  27984. return animation;
  27985. };
  27986. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  27987. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  27988. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  27989. };
  27990. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  27991. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  27992. node.animations.push(animation);
  27993. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  27994. };
  27995. // Methods
  27996. /**
  27997. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27998. */
  27999. Animation.prototype.toString = function (fullDetails) {
  28000. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  28001. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  28002. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  28003. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  28004. if (fullDetails) {
  28005. ret += ", Ranges: {";
  28006. var first = true;
  28007. for (var name in this._ranges) {
  28008. if (first) {
  28009. ret += ", ";
  28010. first = false;
  28011. }
  28012. ret += name;
  28013. }
  28014. ret += "}";
  28015. }
  28016. return ret;
  28017. };
  28018. /**
  28019. * Add an event to this animation.
  28020. */
  28021. Animation.prototype.addEvent = function (event) {
  28022. this._events.push(event);
  28023. };
  28024. /**
  28025. * Remove all events found at the given frame
  28026. * @param frame
  28027. */
  28028. Animation.prototype.removeEvents = function (frame) {
  28029. for (var index = 0; index < this._events.length; index++) {
  28030. if (this._events[index].frame === frame) {
  28031. this._events.splice(index, 1);
  28032. index--;
  28033. }
  28034. }
  28035. };
  28036. Animation.prototype.createRange = function (name, from, to) {
  28037. // check name not already in use; could happen for bones after serialized
  28038. if (!this._ranges[name]) {
  28039. this._ranges[name] = new AnimationRange(name, from, to);
  28040. }
  28041. };
  28042. Animation.prototype.deleteRange = function (name, deleteFrames) {
  28043. if (deleteFrames === void 0) { deleteFrames = true; }
  28044. if (this._ranges[name]) {
  28045. if (deleteFrames) {
  28046. var from = this._ranges[name].from;
  28047. var to = this._ranges[name].to;
  28048. // this loop MUST go high to low for multiple splices to work
  28049. for (var key = this._keys.length - 1; key >= 0; key--) {
  28050. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  28051. this._keys.splice(key, 1);
  28052. }
  28053. }
  28054. }
  28055. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  28056. }
  28057. };
  28058. Animation.prototype.getRange = function (name) {
  28059. return this._ranges[name];
  28060. };
  28061. Animation.prototype.reset = function () {
  28062. this._offsetsCache = {};
  28063. this._highLimitsCache = {};
  28064. this.currentFrame = 0;
  28065. this._blendingFactor = 0;
  28066. this._originalBlendValue = null;
  28067. };
  28068. Animation.prototype.isStopped = function () {
  28069. return this._stopped;
  28070. };
  28071. Animation.prototype.getKeys = function () {
  28072. return this._keys;
  28073. };
  28074. Animation.prototype.getHighestFrame = function () {
  28075. var ret = 0;
  28076. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  28077. if (ret < this._keys[key].frame) {
  28078. ret = this._keys[key].frame;
  28079. }
  28080. }
  28081. return ret;
  28082. };
  28083. Animation.prototype.getEasingFunction = function () {
  28084. return this._easingFunction;
  28085. };
  28086. Animation.prototype.setEasingFunction = function (easingFunction) {
  28087. this._easingFunction = easingFunction;
  28088. };
  28089. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  28090. return startValue + (endValue - startValue) * gradient;
  28091. };
  28092. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  28093. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  28094. };
  28095. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  28096. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  28097. };
  28098. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  28099. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  28100. };
  28101. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  28102. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  28103. };
  28104. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  28105. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  28106. };
  28107. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  28108. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  28109. };
  28110. Animation.prototype.clone = function () {
  28111. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  28112. if (this._keys) {
  28113. clone.setKeys(this._keys);
  28114. }
  28115. if (this._ranges) {
  28116. clone._ranges = {};
  28117. for (var name in this._ranges) {
  28118. clone._ranges[name] = this._ranges[name].clone();
  28119. }
  28120. }
  28121. return clone;
  28122. };
  28123. Animation.prototype.setKeys = function (values) {
  28124. this._keys = values.slice(0);
  28125. this._offsetsCache = {};
  28126. this._highLimitsCache = {};
  28127. };
  28128. Animation.prototype._getKeyValue = function (value) {
  28129. if (typeof value === "function") {
  28130. return value();
  28131. }
  28132. return value;
  28133. };
  28134. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  28135. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  28136. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  28137. }
  28138. this.currentFrame = currentFrame;
  28139. // Try to get a hash to find the right key
  28140. 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));
  28141. if (this._keys[startKey].frame >= currentFrame) {
  28142. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  28143. startKey--;
  28144. }
  28145. }
  28146. for (var key = startKey; key < this._keys.length; key++) {
  28147. if (this._keys[key + 1].frame >= currentFrame) {
  28148. var startValue = this._getKeyValue(this._keys[key].value);
  28149. var endValue = this._getKeyValue(this._keys[key + 1].value);
  28150. // gradient : percent of currentFrame between the frame inf and the frame sup
  28151. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  28152. // check for easingFunction and correction of gradient
  28153. if (this._easingFunction != null) {
  28154. gradient = this._easingFunction.ease(gradient);
  28155. }
  28156. switch (this.dataType) {
  28157. // Float
  28158. case Animation.ANIMATIONTYPE_FLOAT:
  28159. switch (loopMode) {
  28160. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28161. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28162. return this.floatInterpolateFunction(startValue, endValue, gradient);
  28163. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28164. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  28165. }
  28166. break;
  28167. // Quaternion
  28168. case Animation.ANIMATIONTYPE_QUATERNION:
  28169. var quaternion = null;
  28170. switch (loopMode) {
  28171. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28172. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28173. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  28174. break;
  28175. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28176. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28177. break;
  28178. }
  28179. return quaternion;
  28180. // Vector3
  28181. case Animation.ANIMATIONTYPE_VECTOR3:
  28182. switch (loopMode) {
  28183. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28184. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28185. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  28186. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28187. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28188. }
  28189. // Vector2
  28190. case Animation.ANIMATIONTYPE_VECTOR2:
  28191. switch (loopMode) {
  28192. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28193. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28194. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  28195. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28196. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28197. }
  28198. // Size
  28199. case Animation.ANIMATIONTYPE_SIZE:
  28200. switch (loopMode) {
  28201. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28202. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28203. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  28204. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28205. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28206. }
  28207. // Color3
  28208. case Animation.ANIMATIONTYPE_COLOR3:
  28209. switch (loopMode) {
  28210. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28211. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28212. return this.color3InterpolateFunction(startValue, endValue, gradient);
  28213. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28214. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28215. }
  28216. // Matrix
  28217. case Animation.ANIMATIONTYPE_MATRIX:
  28218. switch (loopMode) {
  28219. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28220. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28221. if (this.allowMatricesInterpolation) {
  28222. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  28223. }
  28224. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28225. return startValue;
  28226. }
  28227. default:
  28228. break;
  28229. }
  28230. break;
  28231. }
  28232. }
  28233. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  28234. };
  28235. Animation.prototype.setValue = function (currentValue, blend) {
  28236. if (blend === void 0) { blend = false; }
  28237. // Set value
  28238. var path;
  28239. var destination;
  28240. if (this.targetPropertyPath.length > 1) {
  28241. var property = this._target[this.targetPropertyPath[0]];
  28242. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  28243. property = property[this.targetPropertyPath[index]];
  28244. }
  28245. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  28246. destination = property;
  28247. }
  28248. else {
  28249. path = this.targetPropertyPath[0];
  28250. destination = this._target;
  28251. }
  28252. // Blending
  28253. if (this.enableBlending && this._blendingFactor <= 1.0) {
  28254. if (!this._originalBlendValue) {
  28255. if (destination[path].clone) {
  28256. this._originalBlendValue = destination[path].clone();
  28257. }
  28258. else {
  28259. this._originalBlendValue = destination[path];
  28260. }
  28261. }
  28262. if (this._originalBlendValue.prototype) {
  28263. if (this._originalBlendValue.prototype.Lerp) {
  28264. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  28265. }
  28266. else {
  28267. destination[path] = currentValue;
  28268. }
  28269. }
  28270. else if (this._originalBlendValue.m) {
  28271. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  28272. }
  28273. else {
  28274. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  28275. }
  28276. this._blendingFactor += this.blendingSpeed;
  28277. }
  28278. else {
  28279. destination[path] = currentValue;
  28280. }
  28281. if (this._target.markAsDirty) {
  28282. this._target.markAsDirty(this.targetProperty);
  28283. }
  28284. };
  28285. Animation.prototype.goToFrame = function (frame) {
  28286. if (frame < this._keys[0].frame) {
  28287. frame = this._keys[0].frame;
  28288. }
  28289. else if (frame > this._keys[this._keys.length - 1].frame) {
  28290. frame = this._keys[this._keys.length - 1].frame;
  28291. }
  28292. var currentValue = this._interpolate(frame, 0, this.loopMode);
  28293. this.setValue(currentValue);
  28294. };
  28295. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  28296. if (blend === void 0) { blend = false; }
  28297. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  28298. this._stopped = true;
  28299. return false;
  28300. }
  28301. var returnValue = true;
  28302. // Adding a start key at frame 0 if missing
  28303. if (this._keys[0].frame !== 0) {
  28304. var newKey = { frame: 0, value: this._keys[0].value };
  28305. this._keys.splice(0, 0, newKey);
  28306. }
  28307. // Check limits
  28308. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  28309. from = this._keys[0].frame;
  28310. }
  28311. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  28312. to = this._keys[this._keys.length - 1].frame;
  28313. }
  28314. // Compute ratio
  28315. var range = to - from;
  28316. var offsetValue;
  28317. // ratio represents the frame delta between from and to
  28318. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  28319. var highLimitValue = 0;
  28320. if (ratio > range && !loop) {
  28321. returnValue = false;
  28322. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  28323. }
  28324. else {
  28325. // Get max value if required
  28326. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  28327. var keyOffset = to.toString() + from.toString();
  28328. if (!this._offsetsCache[keyOffset]) {
  28329. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28330. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28331. switch (this.dataType) {
  28332. // Float
  28333. case Animation.ANIMATIONTYPE_FLOAT:
  28334. this._offsetsCache[keyOffset] = toValue - fromValue;
  28335. break;
  28336. // Quaternion
  28337. case Animation.ANIMATIONTYPE_QUATERNION:
  28338. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28339. break;
  28340. // Vector3
  28341. case Animation.ANIMATIONTYPE_VECTOR3:
  28342. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28343. // Vector2
  28344. case Animation.ANIMATIONTYPE_VECTOR2:
  28345. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28346. // Size
  28347. case Animation.ANIMATIONTYPE_SIZE:
  28348. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28349. // Color3
  28350. case Animation.ANIMATIONTYPE_COLOR3:
  28351. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28352. default:
  28353. break;
  28354. }
  28355. this._highLimitsCache[keyOffset] = toValue;
  28356. }
  28357. highLimitValue = this._highLimitsCache[keyOffset];
  28358. offsetValue = this._offsetsCache[keyOffset];
  28359. }
  28360. }
  28361. if (offsetValue === undefined) {
  28362. switch (this.dataType) {
  28363. // Float
  28364. case Animation.ANIMATIONTYPE_FLOAT:
  28365. offsetValue = 0;
  28366. break;
  28367. // Quaternion
  28368. case Animation.ANIMATIONTYPE_QUATERNION:
  28369. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  28370. break;
  28371. // Vector3
  28372. case Animation.ANIMATIONTYPE_VECTOR3:
  28373. offsetValue = BABYLON.Vector3.Zero();
  28374. break;
  28375. // Vector2
  28376. case Animation.ANIMATIONTYPE_VECTOR2:
  28377. offsetValue = BABYLON.Vector2.Zero();
  28378. break;
  28379. // Size
  28380. case Animation.ANIMATIONTYPE_SIZE:
  28381. offsetValue = BABYLON.Size.Zero();
  28382. break;
  28383. // Color3
  28384. case Animation.ANIMATIONTYPE_COLOR3:
  28385. offsetValue = BABYLON.Color3.Black();
  28386. }
  28387. }
  28388. // Compute value
  28389. var repeatCount = (ratio / range) >> 0;
  28390. var currentFrame = returnValue ? from + ratio % range : to;
  28391. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  28392. // Set value
  28393. this.setValue(currentValue);
  28394. // Check events
  28395. for (var index = 0; index < this._events.length; index++) {
  28396. if (currentFrame >= this._events[index].frame) {
  28397. var event = this._events[index];
  28398. if (!event.isDone) {
  28399. // If event should be done only once, remove it.
  28400. if (event.onlyOnce) {
  28401. this._events.splice(index, 1);
  28402. index--;
  28403. }
  28404. event.isDone = true;
  28405. event.action();
  28406. } // Don't do anything if the event has already be done.
  28407. }
  28408. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  28409. // reset event, the animation is looping
  28410. this._events[index].isDone = false;
  28411. }
  28412. }
  28413. if (!returnValue) {
  28414. this._stopped = true;
  28415. }
  28416. return returnValue;
  28417. };
  28418. Animation.prototype.serialize = function () {
  28419. var serializationObject = {};
  28420. serializationObject.name = this.name;
  28421. serializationObject.property = this.targetProperty;
  28422. serializationObject.framePerSecond = this.framePerSecond;
  28423. serializationObject.dataType = this.dataType;
  28424. serializationObject.loopBehavior = this.loopMode;
  28425. var dataType = this.dataType;
  28426. serializationObject.keys = [];
  28427. var keys = this.getKeys();
  28428. for (var index = 0; index < keys.length; index++) {
  28429. var animationKey = keys[index];
  28430. var key = {};
  28431. key.frame = animationKey.frame;
  28432. switch (dataType) {
  28433. case Animation.ANIMATIONTYPE_FLOAT:
  28434. key.values = [animationKey.value];
  28435. break;
  28436. case Animation.ANIMATIONTYPE_QUATERNION:
  28437. case Animation.ANIMATIONTYPE_MATRIX:
  28438. case Animation.ANIMATIONTYPE_VECTOR3:
  28439. case Animation.ANIMATIONTYPE_COLOR3:
  28440. key.values = animationKey.value.asArray();
  28441. break;
  28442. }
  28443. serializationObject.keys.push(key);
  28444. }
  28445. serializationObject.ranges = [];
  28446. for (var name in this._ranges) {
  28447. var range = {};
  28448. range.name = name;
  28449. range.from = this._ranges[name].from;
  28450. range.to = this._ranges[name].to;
  28451. serializationObject.ranges.push(range);
  28452. }
  28453. return serializationObject;
  28454. };
  28455. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  28456. get: function () {
  28457. return Animation._ANIMATIONTYPE_FLOAT;
  28458. },
  28459. enumerable: true,
  28460. configurable: true
  28461. });
  28462. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  28463. get: function () {
  28464. return Animation._ANIMATIONTYPE_VECTOR3;
  28465. },
  28466. enumerable: true,
  28467. configurable: true
  28468. });
  28469. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  28470. get: function () {
  28471. return Animation._ANIMATIONTYPE_VECTOR2;
  28472. },
  28473. enumerable: true,
  28474. configurable: true
  28475. });
  28476. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  28477. get: function () {
  28478. return Animation._ANIMATIONTYPE_SIZE;
  28479. },
  28480. enumerable: true,
  28481. configurable: true
  28482. });
  28483. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  28484. get: function () {
  28485. return Animation._ANIMATIONTYPE_QUATERNION;
  28486. },
  28487. enumerable: true,
  28488. configurable: true
  28489. });
  28490. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  28491. get: function () {
  28492. return Animation._ANIMATIONTYPE_MATRIX;
  28493. },
  28494. enumerable: true,
  28495. configurable: true
  28496. });
  28497. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  28498. get: function () {
  28499. return Animation._ANIMATIONTYPE_COLOR3;
  28500. },
  28501. enumerable: true,
  28502. configurable: true
  28503. });
  28504. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  28505. get: function () {
  28506. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  28507. },
  28508. enumerable: true,
  28509. configurable: true
  28510. });
  28511. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  28512. get: function () {
  28513. return Animation._ANIMATIONLOOPMODE_CYCLE;
  28514. },
  28515. enumerable: true,
  28516. configurable: true
  28517. });
  28518. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  28519. get: function () {
  28520. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  28521. },
  28522. enumerable: true,
  28523. configurable: true
  28524. });
  28525. Animation.Parse = function (parsedAnimation) {
  28526. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  28527. var dataType = parsedAnimation.dataType;
  28528. var keys = [];
  28529. var data;
  28530. var index;
  28531. for (index = 0; index < parsedAnimation.keys.length; index++) {
  28532. var key = parsedAnimation.keys[index];
  28533. switch (dataType) {
  28534. case Animation.ANIMATIONTYPE_FLOAT:
  28535. data = key.values[0];
  28536. break;
  28537. case Animation.ANIMATIONTYPE_QUATERNION:
  28538. data = BABYLON.Quaternion.FromArray(key.values);
  28539. break;
  28540. case Animation.ANIMATIONTYPE_MATRIX:
  28541. data = BABYLON.Matrix.FromArray(key.values);
  28542. break;
  28543. case Animation.ANIMATIONTYPE_COLOR3:
  28544. data = BABYLON.Color3.FromArray(key.values);
  28545. break;
  28546. case Animation.ANIMATIONTYPE_VECTOR3:
  28547. default:
  28548. data = BABYLON.Vector3.FromArray(key.values);
  28549. break;
  28550. }
  28551. keys.push({
  28552. frame: key.frame,
  28553. value: data
  28554. });
  28555. }
  28556. animation.setKeys(keys);
  28557. if (parsedAnimation.ranges) {
  28558. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  28559. data = parsedAnimation.ranges[index];
  28560. animation.createRange(data.name, data.from, data.to);
  28561. }
  28562. }
  28563. return animation;
  28564. };
  28565. Animation.AppendSerializedAnimations = function (source, destination) {
  28566. if (source.animations) {
  28567. destination.animations = [];
  28568. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  28569. var animation = source.animations[animationIndex];
  28570. destination.animations.push(animation.serialize());
  28571. }
  28572. }
  28573. };
  28574. // Statics
  28575. Animation._ANIMATIONTYPE_FLOAT = 0;
  28576. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  28577. Animation._ANIMATIONTYPE_QUATERNION = 2;
  28578. Animation._ANIMATIONTYPE_MATRIX = 3;
  28579. Animation._ANIMATIONTYPE_COLOR3 = 4;
  28580. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  28581. Animation._ANIMATIONTYPE_SIZE = 6;
  28582. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  28583. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  28584. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  28585. return Animation;
  28586. })();
  28587. BABYLON.Animation = Animation;
  28588. })(BABYLON || (BABYLON = {}));
  28589. var BABYLON;
  28590. (function (BABYLON) {
  28591. var Animatable = (function () {
  28592. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  28593. if (fromFrame === void 0) { fromFrame = 0; }
  28594. if (toFrame === void 0) { toFrame = 100; }
  28595. if (loopAnimation === void 0) { loopAnimation = false; }
  28596. if (speedRatio === void 0) { speedRatio = 1.0; }
  28597. this.target = target;
  28598. this.fromFrame = fromFrame;
  28599. this.toFrame = toFrame;
  28600. this.loopAnimation = loopAnimation;
  28601. this.speedRatio = speedRatio;
  28602. this.onAnimationEnd = onAnimationEnd;
  28603. this._animations = new Array();
  28604. this._paused = false;
  28605. this.animationStarted = false;
  28606. if (animations) {
  28607. this.appendAnimations(target, animations);
  28608. }
  28609. this._scene = scene;
  28610. scene._activeAnimatables.push(this);
  28611. }
  28612. // Methods
  28613. Animatable.prototype.getAnimations = function () {
  28614. return this._animations;
  28615. };
  28616. Animatable.prototype.appendAnimations = function (target, animations) {
  28617. for (var index = 0; index < animations.length; index++) {
  28618. var animation = animations[index];
  28619. animation._target = target;
  28620. this._animations.push(animation);
  28621. }
  28622. };
  28623. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  28624. var animations = this._animations;
  28625. for (var index = 0; index < animations.length; index++) {
  28626. if (animations[index].targetProperty === property) {
  28627. return animations[index];
  28628. }
  28629. }
  28630. return null;
  28631. };
  28632. Animatable.prototype.reset = function () {
  28633. var animations = this._animations;
  28634. for (var index = 0; index < animations.length; index++) {
  28635. animations[index].reset();
  28636. }
  28637. this._localDelayOffset = null;
  28638. this._pausedDelay = null;
  28639. };
  28640. Animatable.prototype.enableBlending = function (blendingSpeed) {
  28641. var animations = this._animations;
  28642. for (var index = 0; index < animations.length; index++) {
  28643. animations[index].enableBlending = true;
  28644. animations[index].blendingSpeed = blendingSpeed;
  28645. }
  28646. };
  28647. Animatable.prototype.disableBlending = function () {
  28648. var animations = this._animations;
  28649. for (var index = 0; index < animations.length; index++) {
  28650. animations[index].enableBlending = false;
  28651. }
  28652. };
  28653. Animatable.prototype.goToFrame = function (frame) {
  28654. var animations = this._animations;
  28655. for (var index = 0; index < animations.length; index++) {
  28656. animations[index].goToFrame(frame);
  28657. }
  28658. };
  28659. Animatable.prototype.pause = function () {
  28660. if (this._paused) {
  28661. return;
  28662. }
  28663. this._paused = true;
  28664. };
  28665. Animatable.prototype.restart = function () {
  28666. this._paused = false;
  28667. };
  28668. Animatable.prototype.stop = function () {
  28669. var index = this._scene._activeAnimatables.indexOf(this);
  28670. if (index > -1) {
  28671. this._scene._activeAnimatables.splice(index, 1);
  28672. var animations = this._animations;
  28673. for (var index = 0; index < animations.length; index++) {
  28674. animations[index].reset();
  28675. }
  28676. if (this.onAnimationEnd) {
  28677. this.onAnimationEnd();
  28678. }
  28679. }
  28680. };
  28681. Animatable.prototype._animate = function (delay) {
  28682. if (this._paused) {
  28683. this.animationStarted = false;
  28684. if (!this._pausedDelay) {
  28685. this._pausedDelay = delay;
  28686. }
  28687. return true;
  28688. }
  28689. if (!this._localDelayOffset) {
  28690. this._localDelayOffset = delay;
  28691. }
  28692. else if (this._pausedDelay) {
  28693. this._localDelayOffset += delay - this._pausedDelay;
  28694. this._pausedDelay = null;
  28695. }
  28696. // Animating
  28697. var running = false;
  28698. var animations = this._animations;
  28699. var index;
  28700. for (index = 0; index < animations.length; index++) {
  28701. var animation = animations[index];
  28702. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  28703. running = running || isRunning;
  28704. }
  28705. this.animationStarted = running;
  28706. if (!running) {
  28707. // Remove from active animatables
  28708. index = this._scene._activeAnimatables.indexOf(this);
  28709. this._scene._activeAnimatables.splice(index, 1);
  28710. }
  28711. if (!running && this.onAnimationEnd) {
  28712. this.onAnimationEnd();
  28713. this.onAnimationEnd = null;
  28714. }
  28715. return running;
  28716. };
  28717. return Animatable;
  28718. })();
  28719. BABYLON.Animatable = Animatable;
  28720. })(BABYLON || (BABYLON = {}));
  28721. var BABYLON;
  28722. (function (BABYLON) {
  28723. var EasingFunction = (function () {
  28724. function EasingFunction() {
  28725. // Properties
  28726. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  28727. }
  28728. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  28729. get: function () {
  28730. return EasingFunction._EASINGMODE_EASEIN;
  28731. },
  28732. enumerable: true,
  28733. configurable: true
  28734. });
  28735. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  28736. get: function () {
  28737. return EasingFunction._EASINGMODE_EASEOUT;
  28738. },
  28739. enumerable: true,
  28740. configurable: true
  28741. });
  28742. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  28743. get: function () {
  28744. return EasingFunction._EASINGMODE_EASEINOUT;
  28745. },
  28746. enumerable: true,
  28747. configurable: true
  28748. });
  28749. EasingFunction.prototype.setEasingMode = function (easingMode) {
  28750. var n = Math.min(Math.max(easingMode, 0), 2);
  28751. this._easingMode = n;
  28752. };
  28753. EasingFunction.prototype.getEasingMode = function () {
  28754. return this._easingMode;
  28755. };
  28756. EasingFunction.prototype.easeInCore = function (gradient) {
  28757. throw new Error('You must implement this method');
  28758. };
  28759. EasingFunction.prototype.ease = function (gradient) {
  28760. switch (this._easingMode) {
  28761. case EasingFunction.EASINGMODE_EASEIN:
  28762. return this.easeInCore(gradient);
  28763. case EasingFunction.EASINGMODE_EASEOUT:
  28764. return (1 - this.easeInCore(1 - gradient));
  28765. }
  28766. if (gradient >= 0.5) {
  28767. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  28768. }
  28769. return (this.easeInCore(gradient * 2) * 0.5);
  28770. };
  28771. //Statics
  28772. EasingFunction._EASINGMODE_EASEIN = 0;
  28773. EasingFunction._EASINGMODE_EASEOUT = 1;
  28774. EasingFunction._EASINGMODE_EASEINOUT = 2;
  28775. return EasingFunction;
  28776. })();
  28777. BABYLON.EasingFunction = EasingFunction;
  28778. var CircleEase = (function (_super) {
  28779. __extends(CircleEase, _super);
  28780. function CircleEase() {
  28781. _super.apply(this, arguments);
  28782. }
  28783. CircleEase.prototype.easeInCore = function (gradient) {
  28784. gradient = Math.max(0, Math.min(1, gradient));
  28785. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  28786. };
  28787. return CircleEase;
  28788. })(EasingFunction);
  28789. BABYLON.CircleEase = CircleEase;
  28790. var BackEase = (function (_super) {
  28791. __extends(BackEase, _super);
  28792. function BackEase(amplitude) {
  28793. if (amplitude === void 0) { amplitude = 1; }
  28794. _super.call(this);
  28795. this.amplitude = amplitude;
  28796. }
  28797. BackEase.prototype.easeInCore = function (gradient) {
  28798. var num = Math.max(0, this.amplitude);
  28799. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  28800. };
  28801. return BackEase;
  28802. })(EasingFunction);
  28803. BABYLON.BackEase = BackEase;
  28804. var BounceEase = (function (_super) {
  28805. __extends(BounceEase, _super);
  28806. function BounceEase(bounces, bounciness) {
  28807. if (bounces === void 0) { bounces = 3; }
  28808. if (bounciness === void 0) { bounciness = 2; }
  28809. _super.call(this);
  28810. this.bounces = bounces;
  28811. this.bounciness = bounciness;
  28812. }
  28813. BounceEase.prototype.easeInCore = function (gradient) {
  28814. var y = Math.max(0.0, this.bounces);
  28815. var bounciness = this.bounciness;
  28816. if (bounciness <= 1.0) {
  28817. bounciness = 1.001;
  28818. }
  28819. var num9 = Math.pow(bounciness, y);
  28820. var num5 = 1.0 - bounciness;
  28821. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  28822. var num15 = gradient * num4;
  28823. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  28824. var num3 = Math.floor(num65);
  28825. var num13 = num3 + 1.0;
  28826. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  28827. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  28828. var num7 = (num8 + num12) * 0.5;
  28829. var num6 = gradient - num7;
  28830. var num2 = num7 - num8;
  28831. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  28832. };
  28833. return BounceEase;
  28834. })(EasingFunction);
  28835. BABYLON.BounceEase = BounceEase;
  28836. var CubicEase = (function (_super) {
  28837. __extends(CubicEase, _super);
  28838. function CubicEase() {
  28839. _super.apply(this, arguments);
  28840. }
  28841. CubicEase.prototype.easeInCore = function (gradient) {
  28842. return (gradient * gradient * gradient);
  28843. };
  28844. return CubicEase;
  28845. })(EasingFunction);
  28846. BABYLON.CubicEase = CubicEase;
  28847. var ElasticEase = (function (_super) {
  28848. __extends(ElasticEase, _super);
  28849. function ElasticEase(oscillations, springiness) {
  28850. if (oscillations === void 0) { oscillations = 3; }
  28851. if (springiness === void 0) { springiness = 3; }
  28852. _super.call(this);
  28853. this.oscillations = oscillations;
  28854. this.springiness = springiness;
  28855. }
  28856. ElasticEase.prototype.easeInCore = function (gradient) {
  28857. var num2;
  28858. var num3 = Math.max(0.0, this.oscillations);
  28859. var num = Math.max(0.0, this.springiness);
  28860. if (num == 0) {
  28861. num2 = gradient;
  28862. }
  28863. else {
  28864. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  28865. }
  28866. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  28867. };
  28868. return ElasticEase;
  28869. })(EasingFunction);
  28870. BABYLON.ElasticEase = ElasticEase;
  28871. var ExponentialEase = (function (_super) {
  28872. __extends(ExponentialEase, _super);
  28873. function ExponentialEase(exponent) {
  28874. if (exponent === void 0) { exponent = 2; }
  28875. _super.call(this);
  28876. this.exponent = exponent;
  28877. }
  28878. ExponentialEase.prototype.easeInCore = function (gradient) {
  28879. if (this.exponent <= 0) {
  28880. return gradient;
  28881. }
  28882. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  28883. };
  28884. return ExponentialEase;
  28885. })(EasingFunction);
  28886. BABYLON.ExponentialEase = ExponentialEase;
  28887. var PowerEase = (function (_super) {
  28888. __extends(PowerEase, _super);
  28889. function PowerEase(power) {
  28890. if (power === void 0) { power = 2; }
  28891. _super.call(this);
  28892. this.power = power;
  28893. }
  28894. PowerEase.prototype.easeInCore = function (gradient) {
  28895. var y = Math.max(0.0, this.power);
  28896. return Math.pow(gradient, y);
  28897. };
  28898. return PowerEase;
  28899. })(EasingFunction);
  28900. BABYLON.PowerEase = PowerEase;
  28901. var QuadraticEase = (function (_super) {
  28902. __extends(QuadraticEase, _super);
  28903. function QuadraticEase() {
  28904. _super.apply(this, arguments);
  28905. }
  28906. QuadraticEase.prototype.easeInCore = function (gradient) {
  28907. return (gradient * gradient);
  28908. };
  28909. return QuadraticEase;
  28910. })(EasingFunction);
  28911. BABYLON.QuadraticEase = QuadraticEase;
  28912. var QuarticEase = (function (_super) {
  28913. __extends(QuarticEase, _super);
  28914. function QuarticEase() {
  28915. _super.apply(this, arguments);
  28916. }
  28917. QuarticEase.prototype.easeInCore = function (gradient) {
  28918. return (gradient * gradient * gradient * gradient);
  28919. };
  28920. return QuarticEase;
  28921. })(EasingFunction);
  28922. BABYLON.QuarticEase = QuarticEase;
  28923. var QuinticEase = (function (_super) {
  28924. __extends(QuinticEase, _super);
  28925. function QuinticEase() {
  28926. _super.apply(this, arguments);
  28927. }
  28928. QuinticEase.prototype.easeInCore = function (gradient) {
  28929. return (gradient * gradient * gradient * gradient * gradient);
  28930. };
  28931. return QuinticEase;
  28932. })(EasingFunction);
  28933. BABYLON.QuinticEase = QuinticEase;
  28934. var SineEase = (function (_super) {
  28935. __extends(SineEase, _super);
  28936. function SineEase() {
  28937. _super.apply(this, arguments);
  28938. }
  28939. SineEase.prototype.easeInCore = function (gradient) {
  28940. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  28941. };
  28942. return SineEase;
  28943. })(EasingFunction);
  28944. BABYLON.SineEase = SineEase;
  28945. var BezierCurveEase = (function (_super) {
  28946. __extends(BezierCurveEase, _super);
  28947. function BezierCurveEase(x1, y1, x2, y2) {
  28948. if (x1 === void 0) { x1 = 0; }
  28949. if (y1 === void 0) { y1 = 0; }
  28950. if (x2 === void 0) { x2 = 1; }
  28951. if (y2 === void 0) { y2 = 1; }
  28952. _super.call(this);
  28953. this.x1 = x1;
  28954. this.y1 = y1;
  28955. this.x2 = x2;
  28956. this.y2 = y2;
  28957. }
  28958. BezierCurveEase.prototype.easeInCore = function (gradient) {
  28959. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  28960. };
  28961. return BezierCurveEase;
  28962. })(EasingFunction);
  28963. BABYLON.BezierCurveEase = BezierCurveEase;
  28964. })(BABYLON || (BABYLON = {}));
  28965. var BABYLON;
  28966. (function (BABYLON) {
  28967. var Bone = (function (_super) {
  28968. __extends(Bone, _super);
  28969. function Bone(name, skeleton, parentBone, matrix, restPose) {
  28970. _super.call(this, name, skeleton.getScene());
  28971. this.name = name;
  28972. this.children = new Array();
  28973. this.animations = new Array();
  28974. this._worldTransform = new BABYLON.Matrix();
  28975. this._absoluteTransform = new BABYLON.Matrix();
  28976. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  28977. this._skeleton = skeleton;
  28978. this._matrix = matrix;
  28979. this._baseMatrix = matrix;
  28980. this._restPose = restPose ? restPose : matrix.clone();
  28981. skeleton.bones.push(this);
  28982. if (parentBone) {
  28983. this._parent = parentBone;
  28984. parentBone.children.push(this);
  28985. }
  28986. else {
  28987. this._parent = null;
  28988. }
  28989. this._updateDifferenceMatrix();
  28990. }
  28991. // Members
  28992. Bone.prototype.getParent = function () {
  28993. return this._parent;
  28994. };
  28995. Bone.prototype.getLocalMatrix = function () {
  28996. return this._matrix;
  28997. };
  28998. Bone.prototype.getBaseMatrix = function () {
  28999. return this._baseMatrix;
  29000. };
  29001. Bone.prototype.getRestPose = function () {
  29002. return this._restPose;
  29003. };
  29004. Bone.prototype.returnToRest = function () {
  29005. this.updateMatrix(this._restPose.clone());
  29006. };
  29007. Bone.prototype.getWorldMatrix = function () {
  29008. return this._worldTransform;
  29009. };
  29010. Bone.prototype.getInvertedAbsoluteTransform = function () {
  29011. return this._invertedAbsoluteTransform;
  29012. };
  29013. Bone.prototype.getAbsoluteTransform = function () {
  29014. return this._absoluteTransform;
  29015. };
  29016. // Methods
  29017. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  29018. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  29019. this._baseMatrix = matrix.clone();
  29020. this._matrix = matrix.clone();
  29021. this._skeleton._markAsDirty();
  29022. if (updateDifferenceMatrix) {
  29023. this._updateDifferenceMatrix();
  29024. }
  29025. };
  29026. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  29027. if (!rootMatrix) {
  29028. rootMatrix = this._baseMatrix;
  29029. }
  29030. if (this._parent) {
  29031. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  29032. }
  29033. else {
  29034. this._absoluteTransform.copyFrom(rootMatrix);
  29035. }
  29036. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  29037. for (var index = 0; index < this.children.length; index++) {
  29038. this.children[index]._updateDifferenceMatrix();
  29039. }
  29040. };
  29041. Bone.prototype.markAsDirty = function () {
  29042. this._currentRenderId++;
  29043. this._skeleton._markAsDirty();
  29044. };
  29045. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  29046. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  29047. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  29048. // all animation may be coming from a library skeleton, so may need to create animation
  29049. if (this.animations.length === 0) {
  29050. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  29051. this.animations[0].setKeys([]);
  29052. }
  29053. // get animation info / verify there is such a range from the source bone
  29054. var sourceRange = source.animations[0].getRange(rangeName);
  29055. if (!sourceRange) {
  29056. return false;
  29057. }
  29058. var from = sourceRange.from;
  29059. var to = sourceRange.to;
  29060. var sourceKeys = source.animations[0].getKeys();
  29061. // rescaling prep
  29062. var sourceBoneLength = source.length;
  29063. var sourceParent = source.getParent();
  29064. var parent = this.getParent();
  29065. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  29066. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  29067. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  29068. var destKeys = this.animations[0].getKeys();
  29069. // loop vars declaration
  29070. var orig;
  29071. var origTranslation;
  29072. var mat;
  29073. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  29074. orig = sourceKeys[key];
  29075. if (orig.frame >= from && orig.frame <= to) {
  29076. if (rescaleAsRequired) {
  29077. mat = orig.value.clone();
  29078. // scale based on parent ratio, when bone has parent
  29079. if (parentScalingReqd) {
  29080. origTranslation = mat.getTranslation();
  29081. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  29082. }
  29083. else if (dimensionsScalingReqd) {
  29084. origTranslation = mat.getTranslation();
  29085. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  29086. }
  29087. else {
  29088. mat = orig.value;
  29089. }
  29090. }
  29091. else {
  29092. mat = orig.value;
  29093. }
  29094. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  29095. }
  29096. }
  29097. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  29098. return true;
  29099. };
  29100. return Bone;
  29101. })(BABYLON.Node);
  29102. BABYLON.Bone = Bone;
  29103. })(BABYLON || (BABYLON = {}));
  29104. var BABYLON;
  29105. (function (BABYLON) {
  29106. var Skeleton = (function () {
  29107. function Skeleton(name, id, scene) {
  29108. this.name = name;
  29109. this.id = id;
  29110. this.bones = new Array();
  29111. this.needInitialSkinMatrix = false;
  29112. this._isDirty = true;
  29113. this._meshesWithPoseMatrix = new Array();
  29114. this._identity = BABYLON.Matrix.Identity();
  29115. this._ranges = {};
  29116. this.bones = [];
  29117. this._scene = scene;
  29118. scene.skeletons.push(this);
  29119. //make sure it will recalculate the matrix next time prepare is called.
  29120. this._isDirty = true;
  29121. }
  29122. // Members
  29123. Skeleton.prototype.getTransformMatrices = function (mesh) {
  29124. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  29125. return mesh._bonesTransformMatrices;
  29126. }
  29127. return this._transformMatrices;
  29128. };
  29129. Skeleton.prototype.getScene = function () {
  29130. return this._scene;
  29131. };
  29132. // Methods
  29133. /**
  29134. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29135. */
  29136. Skeleton.prototype.toString = function (fullDetails) {
  29137. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  29138. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  29139. if (fullDetails) {
  29140. ret += ", Ranges: {";
  29141. var first = true;
  29142. for (var name_1 in this._ranges) {
  29143. if (first) {
  29144. ret += ", ";
  29145. first = false;
  29146. }
  29147. ret += name_1;
  29148. }
  29149. ret += "}";
  29150. }
  29151. return ret;
  29152. };
  29153. /**
  29154. * Get bone's index searching by name
  29155. * @param {string} name is bone's name to search for
  29156. * @return {number} Indice of the bone. Returns -1 if not found
  29157. */
  29158. Skeleton.prototype.getBoneIndexByName = function (name) {
  29159. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  29160. if (this.bones[boneIndex].name === name) {
  29161. return boneIndex;
  29162. }
  29163. }
  29164. return -1;
  29165. };
  29166. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  29167. // check name not already in use
  29168. if (!this._ranges[name]) {
  29169. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  29170. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  29171. if (this.bones[i].animations[0]) {
  29172. this.bones[i].animations[0].createRange(name, from, to);
  29173. }
  29174. }
  29175. }
  29176. };
  29177. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  29178. if (deleteFrames === void 0) { deleteFrames = true; }
  29179. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  29180. if (this.bones[i].animations[0]) {
  29181. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  29182. }
  29183. }
  29184. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  29185. };
  29186. Skeleton.prototype.getAnimationRange = function (name) {
  29187. return this._ranges[name];
  29188. };
  29189. /**
  29190. * Returns as an Array, all AnimationRanges defined on this skeleton
  29191. */
  29192. Skeleton.prototype.getAnimationRanges = function () {
  29193. var animationRanges = [];
  29194. var name;
  29195. var i = 0;
  29196. for (name in this._ranges) {
  29197. animationRanges[i] = this._ranges[name];
  29198. i++;
  29199. }
  29200. return animationRanges;
  29201. };
  29202. /**
  29203. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  29204. */
  29205. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  29206. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  29207. if (this._ranges[name] || !source.getAnimationRange(name)) {
  29208. return false;
  29209. }
  29210. var ret = true;
  29211. var frameOffset = this._getHighestAnimationFrame() + 1;
  29212. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  29213. var boneDict = {};
  29214. var sourceBones = source.bones;
  29215. var nBones;
  29216. var i;
  29217. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  29218. boneDict[sourceBones[i].name] = sourceBones[i];
  29219. }
  29220. if (this.bones.length !== sourceBones.length) {
  29221. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  29222. ret = false;
  29223. }
  29224. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  29225. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  29226. var boneName = this.bones[i].name;
  29227. var sourceBone = boneDict[boneName];
  29228. if (sourceBone) {
  29229. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  29230. }
  29231. else {
  29232. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  29233. ret = false;
  29234. }
  29235. }
  29236. // do not call createAnimationRange(), since it also is done to bones, which was already done
  29237. var range = source.getAnimationRange(name);
  29238. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  29239. return ret;
  29240. };
  29241. Skeleton.prototype.returnToRest = function () {
  29242. for (var index = 0; index < this.bones.length; index++) {
  29243. this.bones[index].returnToRest();
  29244. }
  29245. };
  29246. Skeleton.prototype._getHighestAnimationFrame = function () {
  29247. var ret = 0;
  29248. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  29249. if (this.bones[i].animations[0]) {
  29250. var highest = this.bones[i].animations[0].getHighestFrame();
  29251. if (ret < highest) {
  29252. ret = highest;
  29253. }
  29254. }
  29255. }
  29256. return ret;
  29257. };
  29258. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  29259. var range = this.getAnimationRange(name);
  29260. if (!range) {
  29261. return null;
  29262. }
  29263. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  29264. };
  29265. Skeleton.prototype._markAsDirty = function () {
  29266. this._isDirty = true;
  29267. };
  29268. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  29269. this._meshesWithPoseMatrix.push(mesh);
  29270. };
  29271. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  29272. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  29273. if (index > -1) {
  29274. this._meshesWithPoseMatrix.splice(index, 1);
  29275. }
  29276. };
  29277. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  29278. for (var index = 0; index < this.bones.length; index++) {
  29279. var bone = this.bones[index];
  29280. var parentBone = bone.getParent();
  29281. if (parentBone) {
  29282. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  29283. }
  29284. else {
  29285. if (initialSkinMatrix) {
  29286. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  29287. }
  29288. else {
  29289. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  29290. }
  29291. }
  29292. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  29293. }
  29294. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  29295. };
  29296. Skeleton.prototype.prepare = function () {
  29297. if (!this._isDirty) {
  29298. return;
  29299. }
  29300. if (this.needInitialSkinMatrix) {
  29301. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  29302. var mesh = this._meshesWithPoseMatrix[index];
  29303. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  29304. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  29305. }
  29306. var poseMatrix = mesh.getPoseMatrix();
  29307. // Prepare bones
  29308. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  29309. var bone = this.bones[boneIndex];
  29310. if (!bone.getParent()) {
  29311. var matrix = bone.getBaseMatrix();
  29312. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  29313. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  29314. }
  29315. }
  29316. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  29317. }
  29318. }
  29319. else {
  29320. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  29321. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  29322. }
  29323. this._computeTransformMatrices(this._transformMatrices, null);
  29324. }
  29325. this._isDirty = false;
  29326. this._scene._activeBones.addCount(this.bones.length, false);
  29327. };
  29328. Skeleton.prototype.getAnimatables = function () {
  29329. if (!this._animatables || this._animatables.length !== this.bones.length) {
  29330. this._animatables = [];
  29331. for (var index = 0; index < this.bones.length; index++) {
  29332. this._animatables.push(this.bones[index]);
  29333. }
  29334. }
  29335. return this._animatables;
  29336. };
  29337. Skeleton.prototype.clone = function (name, id) {
  29338. var result = new Skeleton(name, id || name, this._scene);
  29339. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  29340. for (var index = 0; index < this.bones.length; index++) {
  29341. var source = this.bones[index];
  29342. var parentBone = null;
  29343. if (source.getParent()) {
  29344. var parentIndex = this.bones.indexOf(source.getParent());
  29345. parentBone = result.bones[parentIndex];
  29346. }
  29347. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  29348. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  29349. }
  29350. if (this._ranges) {
  29351. result._ranges = {};
  29352. for (var rangeName in this._ranges) {
  29353. result._ranges[rangeName] = this._ranges[rangeName].clone();
  29354. }
  29355. }
  29356. this._isDirty = true;
  29357. return result;
  29358. };
  29359. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  29360. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  29361. this.bones.forEach(function (bone) {
  29362. bone.animations.forEach(function (animation) {
  29363. animation.enableBlending = true;
  29364. animation.blendingSpeed = blendingSpeed;
  29365. });
  29366. });
  29367. };
  29368. Skeleton.prototype.dispose = function () {
  29369. this._meshesWithPoseMatrix = [];
  29370. // Animations
  29371. this.getScene().stopAnimation(this);
  29372. // Remove from scene
  29373. this.getScene().removeSkeleton(this);
  29374. };
  29375. Skeleton.prototype.serialize = function () {
  29376. var serializationObject = {};
  29377. serializationObject.name = this.name;
  29378. serializationObject.id = this.id;
  29379. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  29380. serializationObject.bones = [];
  29381. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  29382. for (var index = 0; index < this.bones.length; index++) {
  29383. var bone = this.bones[index];
  29384. var serializedBone = {
  29385. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  29386. name: bone.name,
  29387. matrix: bone.getLocalMatrix().toArray(),
  29388. rest: bone.getRestPose().toArray()
  29389. };
  29390. serializationObject.bones.push(serializedBone);
  29391. if (bone.length) {
  29392. serializedBone.length = bone.length;
  29393. }
  29394. if (bone.animations && bone.animations.length > 0) {
  29395. serializedBone.animation = bone.animations[0].serialize();
  29396. }
  29397. serializationObject.ranges = [];
  29398. for (var name in this._ranges) {
  29399. var range = {};
  29400. range.name = name;
  29401. range.from = this._ranges[name].from;
  29402. range.to = this._ranges[name].to;
  29403. serializationObject.ranges.push(range);
  29404. }
  29405. }
  29406. return serializationObject;
  29407. };
  29408. Skeleton.Parse = function (parsedSkeleton, scene) {
  29409. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  29410. if (parsedSkeleton.dimensionsAtRest) {
  29411. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  29412. }
  29413. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  29414. var index;
  29415. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  29416. var parsedBone = parsedSkeleton.bones[index];
  29417. var parentBone = null;
  29418. if (parsedBone.parentBoneIndex > -1) {
  29419. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  29420. }
  29421. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  29422. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  29423. if (parsedBone.length) {
  29424. bone.length = parsedBone.length;
  29425. }
  29426. if (parsedBone.animation) {
  29427. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  29428. }
  29429. }
  29430. // placed after bones, so createAnimationRange can cascade down
  29431. if (parsedSkeleton.ranges) {
  29432. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  29433. var data = parsedSkeleton.ranges[index];
  29434. skeleton.createAnimationRange(data.name, data.from, data.to);
  29435. }
  29436. }
  29437. return skeleton;
  29438. };
  29439. return Skeleton;
  29440. })();
  29441. BABYLON.Skeleton = Skeleton;
  29442. })(BABYLON || (BABYLON = {}));
  29443. var BABYLON;
  29444. (function (BABYLON) {
  29445. var PostProcess = (function () {
  29446. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  29447. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  29448. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  29449. this.name = name;
  29450. this.width = -1;
  29451. this.height = -1;
  29452. /*
  29453. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  29454. Can only be used on a single postprocess or on the last one of a chain.
  29455. */
  29456. this.enablePixelPerfectMode = false;
  29457. this._reusable = false;
  29458. this._textures = new BABYLON.SmartArray(2);
  29459. this._currentRenderTextureInd = 0;
  29460. this._scaleRatio = new BABYLON.Vector2(1, 1);
  29461. // Events
  29462. /**
  29463. * An event triggered when the postprocess is activated.
  29464. * @type {BABYLON.Observable}
  29465. */
  29466. this.onActivateObservable = new BABYLON.Observable();
  29467. /**
  29468. * An event triggered when the postprocess changes its size.
  29469. * @type {BABYLON.Observable}
  29470. */
  29471. this.onSizeChangedObservable = new BABYLON.Observable();
  29472. /**
  29473. * An event triggered when the postprocess applies its effect.
  29474. * @type {BABYLON.Observable}
  29475. */
  29476. this.onApplyObservable = new BABYLON.Observable();
  29477. /**
  29478. * An event triggered before rendering the postprocess
  29479. * @type {BABYLON.Observable}
  29480. */
  29481. this.onBeforeRenderObservable = new BABYLON.Observable();
  29482. /**
  29483. * An event triggered after rendering the postprocess
  29484. * @type {BABYLON.Observable}
  29485. */
  29486. this.onAfterRenderObservable = new BABYLON.Observable();
  29487. if (camera != null) {
  29488. this._camera = camera;
  29489. this._scene = camera.getScene();
  29490. camera.attachPostProcess(this);
  29491. this._engine = this._scene.getEngine();
  29492. }
  29493. else {
  29494. this._engine = engine;
  29495. }
  29496. this._options = options;
  29497. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  29498. this._reusable = reusable || false;
  29499. this._textureType = textureType;
  29500. this._samplers = samplers || [];
  29501. this._samplers.push("textureSampler");
  29502. this._fragmentUrl = fragmentUrl;
  29503. this._parameters = parameters || [];
  29504. this._parameters.push("scale");
  29505. this.updateEffect(defines);
  29506. }
  29507. Object.defineProperty(PostProcess.prototype, "onActivate", {
  29508. set: function (callback) {
  29509. if (this._onActivateObserver) {
  29510. this.onActivateObservable.remove(this._onActivateObserver);
  29511. }
  29512. this._onActivateObserver = this.onActivateObservable.add(callback);
  29513. },
  29514. enumerable: true,
  29515. configurable: true
  29516. });
  29517. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  29518. set: function (callback) {
  29519. if (this._onSizeChangedObserver) {
  29520. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  29521. }
  29522. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  29523. },
  29524. enumerable: true,
  29525. configurable: true
  29526. });
  29527. Object.defineProperty(PostProcess.prototype, "onApply", {
  29528. set: function (callback) {
  29529. if (this._onApplyObserver) {
  29530. this.onApplyObservable.remove(this._onApplyObserver);
  29531. }
  29532. this._onApplyObserver = this.onApplyObservable.add(callback);
  29533. },
  29534. enumerable: true,
  29535. configurable: true
  29536. });
  29537. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  29538. set: function (callback) {
  29539. if (this._onBeforeRenderObserver) {
  29540. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  29541. }
  29542. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  29543. },
  29544. enumerable: true,
  29545. configurable: true
  29546. });
  29547. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  29548. set: function (callback) {
  29549. if (this._onAfterRenderObserver) {
  29550. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  29551. }
  29552. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  29553. },
  29554. enumerable: true,
  29555. configurable: true
  29556. });
  29557. PostProcess.prototype.updateEffect = function (defines) {
  29558. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  29559. };
  29560. PostProcess.prototype.isReusable = function () {
  29561. return this._reusable;
  29562. };
  29563. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  29564. PostProcess.prototype.markTextureDirty = function () {
  29565. this.width = -1;
  29566. };
  29567. PostProcess.prototype.activate = function (camera, sourceTexture) {
  29568. camera = camera || this._camera;
  29569. var scene = camera.getScene();
  29570. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  29571. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  29572. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  29573. var desiredWidth = this._options.width || requiredWidth;
  29574. var desiredHeight = this._options.height || requiredHeight;
  29575. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  29576. if (!this._options.width) {
  29577. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  29578. }
  29579. if (!this._options.height) {
  29580. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  29581. }
  29582. }
  29583. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  29584. if (this._textures.length > 0) {
  29585. for (var i = 0; i < this._textures.length; i++) {
  29586. this._engine._releaseTexture(this._textures.data[i]);
  29587. }
  29588. this._textures.reset();
  29589. }
  29590. this.width = desiredWidth;
  29591. this.height = desiredHeight;
  29592. var textureSize = { width: this.width, height: this.height };
  29593. var textureOptions = {
  29594. generateMipMaps: false,
  29595. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  29596. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  29597. samplingMode: this.renderTargetSamplingMode,
  29598. type: this._textureType
  29599. };
  29600. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  29601. if (this._reusable) {
  29602. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  29603. }
  29604. this.onSizeChangedObservable.notifyObservers(this);
  29605. }
  29606. if (this.enablePixelPerfectMode) {
  29607. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  29608. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  29609. }
  29610. else {
  29611. this._scaleRatio.copyFromFloats(1, 1);
  29612. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  29613. }
  29614. this.onActivateObservable.notifyObservers(camera);
  29615. // Clear
  29616. if (this.clearColor) {
  29617. this._engine.clear(this.clearColor, true, true, true);
  29618. }
  29619. else {
  29620. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  29621. }
  29622. if (this._reusable) {
  29623. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  29624. }
  29625. };
  29626. Object.defineProperty(PostProcess.prototype, "isSupported", {
  29627. get: function () {
  29628. return this._effect.isSupported;
  29629. },
  29630. enumerable: true,
  29631. configurable: true
  29632. });
  29633. PostProcess.prototype.apply = function () {
  29634. // Check
  29635. if (!this._effect.isReady())
  29636. return null;
  29637. // States
  29638. this._engine.enableEffect(this._effect);
  29639. this._engine.setState(false);
  29640. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29641. this._engine.setDepthBuffer(false);
  29642. this._engine.setDepthWrite(false);
  29643. // Texture
  29644. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  29645. // Parameters
  29646. this._effect.setVector2("scale", this._scaleRatio);
  29647. this.onApplyObservable.notifyObservers(this._effect);
  29648. return this._effect;
  29649. };
  29650. PostProcess.prototype.dispose = function (camera) {
  29651. camera = camera || this._camera;
  29652. if (this._textures.length > 0) {
  29653. for (var i = 0; i < this._textures.length; i++) {
  29654. this._engine._releaseTexture(this._textures.data[i]);
  29655. }
  29656. this._textures.reset();
  29657. }
  29658. if (!camera) {
  29659. return;
  29660. }
  29661. camera.detachPostProcess(this);
  29662. var index = camera._postProcesses.indexOf(this);
  29663. if (index === 0 && camera._postProcesses.length > 0) {
  29664. this._camera._postProcesses[0].markTextureDirty();
  29665. }
  29666. this.onActivateObservable.clear();
  29667. this.onAfterRenderObservable.clear();
  29668. this.onApplyObservable.clear();
  29669. this.onBeforeRenderObservable.clear();
  29670. this.onSizeChangedObservable.clear();
  29671. };
  29672. return PostProcess;
  29673. })();
  29674. BABYLON.PostProcess = PostProcess;
  29675. })(BABYLON || (BABYLON = {}));
  29676. var BABYLON;
  29677. (function (BABYLON) {
  29678. var PostProcessManager = (function () {
  29679. function PostProcessManager(scene) {
  29680. this._vertexBuffers = {};
  29681. this._scene = scene;
  29682. }
  29683. PostProcessManager.prototype._prepareBuffers = function () {
  29684. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29685. return;
  29686. }
  29687. // VBO
  29688. var vertices = [];
  29689. vertices.push(1, 1);
  29690. vertices.push(-1, 1);
  29691. vertices.push(-1, -1);
  29692. vertices.push(1, -1);
  29693. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29694. // Indices
  29695. var indices = [];
  29696. indices.push(0);
  29697. indices.push(1);
  29698. indices.push(2);
  29699. indices.push(0);
  29700. indices.push(2);
  29701. indices.push(3);
  29702. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  29703. };
  29704. // Methods
  29705. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  29706. var postProcesses = this._scene.activeCamera._postProcesses;
  29707. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29708. return false;
  29709. }
  29710. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  29711. return true;
  29712. };
  29713. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  29714. var engine = this._scene.getEngine();
  29715. for (var index = 0; index < postProcesses.length; index++) {
  29716. if (index < postProcesses.length - 1) {
  29717. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29718. }
  29719. else {
  29720. if (targetTexture) {
  29721. engine.bindFramebuffer(targetTexture);
  29722. }
  29723. else {
  29724. engine.restoreDefaultFramebuffer();
  29725. }
  29726. }
  29727. var pp = postProcesses[index];
  29728. var effect = pp.apply();
  29729. if (effect) {
  29730. pp.onBeforeRenderObservable.notifyObservers(effect);
  29731. // VBOs
  29732. this._prepareBuffers();
  29733. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29734. // Draw order
  29735. engine.draw(true, 0, 6);
  29736. pp.onAfterRenderObservable.notifyObservers(effect);
  29737. }
  29738. }
  29739. // Restore depth buffer
  29740. engine.setDepthBuffer(true);
  29741. engine.setDepthWrite(true);
  29742. };
  29743. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  29744. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29745. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29746. return;
  29747. }
  29748. var engine = this._scene.getEngine();
  29749. for (var index = 0, len = postProcesses.length; index < len; index++) {
  29750. if (index < len - 1) {
  29751. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29752. }
  29753. else {
  29754. if (targetTexture) {
  29755. engine.bindFramebuffer(targetTexture, faceIndex);
  29756. }
  29757. else {
  29758. engine.restoreDefaultFramebuffer();
  29759. }
  29760. }
  29761. if (doNotPresent) {
  29762. break;
  29763. }
  29764. var pp = postProcesses[index];
  29765. var effect = pp.apply();
  29766. if (effect) {
  29767. pp.onBeforeRenderObservable.notifyObservers(effect);
  29768. // VBOs
  29769. this._prepareBuffers();
  29770. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29771. // Draw order
  29772. engine.draw(true, 0, 6);
  29773. pp.onAfterRenderObservable.notifyObservers(effect);
  29774. }
  29775. }
  29776. // Restore depth buffer
  29777. engine.setDepthBuffer(true);
  29778. engine.setDepthWrite(true);
  29779. };
  29780. PostProcessManager.prototype.dispose = function () {
  29781. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29782. if (buffer) {
  29783. buffer.dispose();
  29784. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29785. }
  29786. if (this._indexBuffer) {
  29787. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29788. this._indexBuffer = null;
  29789. }
  29790. };
  29791. return PostProcessManager;
  29792. })();
  29793. BABYLON.PostProcessManager = PostProcessManager;
  29794. })(BABYLON || (BABYLON = {}));
  29795. var BABYLON;
  29796. (function (BABYLON) {
  29797. var PassPostProcess = (function (_super) {
  29798. __extends(PassPostProcess, _super);
  29799. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  29800. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  29801. }
  29802. return PassPostProcess;
  29803. })(BABYLON.PostProcess);
  29804. BABYLON.PassPostProcess = PassPostProcess;
  29805. })(BABYLON || (BABYLON = {}));
  29806. var BABYLON;
  29807. (function (BABYLON) {
  29808. /**
  29809. * This is a holder class for the physics joint created by the physics plugin.
  29810. * It holds a set of functions to control the underlying joint.
  29811. */
  29812. var PhysicsJoint = (function () {
  29813. function PhysicsJoint(type, jointData) {
  29814. this.type = type;
  29815. this.jointData = jointData;
  29816. jointData.nativeParams = jointData.nativeParams || {};
  29817. }
  29818. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  29819. get: function () {
  29820. return this._physicsJoint;
  29821. },
  29822. set: function (newJoint) {
  29823. if (this._physicsJoint) {
  29824. }
  29825. this._physicsJoint = newJoint;
  29826. },
  29827. enumerable: true,
  29828. configurable: true
  29829. });
  29830. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  29831. set: function (physicsPlugin) {
  29832. this._physicsPlugin = physicsPlugin;
  29833. },
  29834. enumerable: true,
  29835. configurable: true
  29836. });
  29837. /**
  29838. * Execute a function that is physics-plugin specific.
  29839. * @param {Function} func the function that will be executed.
  29840. * It accepts two parameters: the physics world and the physics joint.
  29841. */
  29842. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  29843. func(this._physicsPlugin.world, this._physicsJoint);
  29844. };
  29845. //TODO check if the native joints are the same
  29846. //Joint Types
  29847. PhysicsJoint.DistanceJoint = 0;
  29848. PhysicsJoint.HingeJoint = 1;
  29849. PhysicsJoint.BallAndSocketJoint = 2;
  29850. PhysicsJoint.WheelJoint = 3;
  29851. PhysicsJoint.SliderJoint = 4;
  29852. //OIMO
  29853. PhysicsJoint.PrismaticJoint = 5;
  29854. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  29855. PhysicsJoint.UniversalJoint = 6;
  29856. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  29857. //Cannon
  29858. //Similar to a Ball-Joint. Different in params
  29859. PhysicsJoint.PointToPointJoint = 8;
  29860. //Cannon only at the moment
  29861. PhysicsJoint.SpringJoint = 9;
  29862. PhysicsJoint.LockJoint = 10;
  29863. return PhysicsJoint;
  29864. })();
  29865. BABYLON.PhysicsJoint = PhysicsJoint;
  29866. /**
  29867. * A class representing a physics distance joint.
  29868. */
  29869. var DistanceJoint = (function (_super) {
  29870. __extends(DistanceJoint, _super);
  29871. function DistanceJoint(jointData) {
  29872. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  29873. }
  29874. /**
  29875. * Update the predefined distance.
  29876. */
  29877. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  29878. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  29879. };
  29880. return DistanceJoint;
  29881. })(PhysicsJoint);
  29882. BABYLON.DistanceJoint = DistanceJoint;
  29883. var MotorEnabledJoint = (function (_super) {
  29884. __extends(MotorEnabledJoint, _super);
  29885. function MotorEnabledJoint(type, jointData) {
  29886. _super.call(this, type, jointData);
  29887. }
  29888. /**
  29889. * Set the motor values.
  29890. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29891. * @param {number} force the force to apply
  29892. * @param {number} maxForce max force for this motor.
  29893. */
  29894. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  29895. this._physicsPlugin.setMotor(this, force, maxForce);
  29896. };
  29897. /**
  29898. * Set the motor's limits.
  29899. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29900. */
  29901. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  29902. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  29903. };
  29904. return MotorEnabledJoint;
  29905. })(PhysicsJoint);
  29906. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  29907. /**
  29908. * This class represents a single hinge physics joint
  29909. */
  29910. var HingeJoint = (function (_super) {
  29911. __extends(HingeJoint, _super);
  29912. function HingeJoint(jointData) {
  29913. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  29914. }
  29915. /**
  29916. * Set the motor values.
  29917. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29918. * @param {number} force the force to apply
  29919. * @param {number} maxForce max force for this motor.
  29920. */
  29921. HingeJoint.prototype.setMotor = function (force, maxForce) {
  29922. this._physicsPlugin.setMotor(this, force, maxForce);
  29923. };
  29924. /**
  29925. * Set the motor's limits.
  29926. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29927. */
  29928. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  29929. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  29930. };
  29931. return HingeJoint;
  29932. })(MotorEnabledJoint);
  29933. BABYLON.HingeJoint = HingeJoint;
  29934. /**
  29935. * This class represents a dual hinge physics joint (same as wheel joint)
  29936. */
  29937. var Hinge2Joint = (function (_super) {
  29938. __extends(Hinge2Joint, _super);
  29939. function Hinge2Joint(jointData) {
  29940. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  29941. }
  29942. /**
  29943. * Set the motor values.
  29944. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29945. * @param {number} force the force to apply
  29946. * @param {number} maxForce max force for this motor.
  29947. * @param {motorIndex} the motor's index, 0 or 1.
  29948. */
  29949. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  29950. if (motorIndex === void 0) { motorIndex = 0; }
  29951. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  29952. };
  29953. /**
  29954. * Set the motor limits.
  29955. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29956. * @param {number} upperLimit the upper limit
  29957. * @param {number} lowerLimit lower limit
  29958. * @param {motorIndex} the motor's index, 0 or 1.
  29959. */
  29960. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  29961. if (motorIndex === void 0) { motorIndex = 0; }
  29962. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  29963. };
  29964. return Hinge2Joint;
  29965. })(MotorEnabledJoint);
  29966. BABYLON.Hinge2Joint = Hinge2Joint;
  29967. })(BABYLON || (BABYLON = {}));
  29968. var BABYLON;
  29969. (function (BABYLON) {
  29970. var PhysicsImpostor = (function () {
  29971. function PhysicsImpostor(object, type, _options, _scene) {
  29972. var _this = this;
  29973. if (_options === void 0) { _options = { mass: 0 }; }
  29974. this.object = object;
  29975. this.type = type;
  29976. this._options = _options;
  29977. this._scene = _scene;
  29978. this._bodyUpdateRequired = false;
  29979. this._onBeforePhysicsStepCallbacks = new Array();
  29980. this._onAfterPhysicsStepCallbacks = new Array();
  29981. this._onPhysicsCollideCallbacks = [];
  29982. this._deltaPosition = BABYLON.Vector3.Zero();
  29983. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  29984. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  29985. /**
  29986. * this function is executed by the physics engine.
  29987. */
  29988. this.beforeStep = function () {
  29989. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  29990. //conjugate deltaRotation
  29991. if (_this._deltaRotationConjugated) {
  29992. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  29993. }
  29994. else {
  29995. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  29996. }
  29997. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  29998. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  29999. func(_this);
  30000. });
  30001. };
  30002. /**
  30003. * this function is executed by the physics engine.
  30004. */
  30005. this.afterStep = function () {
  30006. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  30007. func(_this);
  30008. });
  30009. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  30010. _this.object.position.addInPlace(_this._deltaPosition);
  30011. if (_this._deltaRotation) {
  30012. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  30013. }
  30014. };
  30015. //event and body object due to cannon's event-based architecture.
  30016. this.onCollide = function (e) {
  30017. if (!_this._onPhysicsCollideCallbacks.length)
  30018. return;
  30019. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  30020. if (otherImpostor) {
  30021. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  30022. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  30023. }).forEach(function (obj) {
  30024. obj.callback(_this, otherImpostor);
  30025. });
  30026. }
  30027. };
  30028. //sanity check!
  30029. if (!this.object) {
  30030. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  30031. return;
  30032. }
  30033. //legacy support for old syntax.
  30034. if (!this._scene && object.getScene) {
  30035. this._scene = object.getScene();
  30036. }
  30037. this._physicsEngine = this._scene.getPhysicsEngine();
  30038. if (!this._physicsEngine) {
  30039. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  30040. }
  30041. else {
  30042. //set the object's quaternion, if not set
  30043. if (!this.object.rotationQuaternion) {
  30044. if (this.object.rotation) {
  30045. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  30046. }
  30047. else {
  30048. this.object.rotationQuaternion = new BABYLON.Quaternion();
  30049. }
  30050. }
  30051. //default options params
  30052. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  30053. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  30054. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  30055. this._joints = [];
  30056. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  30057. if (!this.object.parent) {
  30058. this._init();
  30059. }
  30060. }
  30061. }
  30062. /**
  30063. * This function will completly initialize this impostor.
  30064. * It will create a new body - but only if this mesh has no parent.
  30065. * If it has, this impostor will not be used other than to define the impostor
  30066. * of the child mesh.
  30067. */
  30068. PhysicsImpostor.prototype._init = function () {
  30069. this._physicsEngine.removeImpostor(this);
  30070. this.physicsBody = null;
  30071. this._parent = this._parent || this._getPhysicsParent();
  30072. if (!this.parent) {
  30073. this._physicsEngine.addImpostor(this);
  30074. }
  30075. };
  30076. PhysicsImpostor.prototype._getPhysicsParent = function () {
  30077. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  30078. var parentMesh = this.object.parent;
  30079. return parentMesh.physicsImpostor;
  30080. }
  30081. return;
  30082. };
  30083. /**
  30084. * Should a new body be generated.
  30085. */
  30086. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  30087. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  30088. };
  30089. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  30090. this.forceUpdate();
  30091. };
  30092. /**
  30093. * Force a regeneration of this or the parent's impostor's body.
  30094. * Use under cautious - This will remove all joints already implemented.
  30095. */
  30096. PhysicsImpostor.prototype.forceUpdate = function () {
  30097. this._init();
  30098. if (this.parent) {
  30099. this.parent.forceUpdate();
  30100. }
  30101. };
  30102. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  30103. /*public get mesh(): AbstractMesh {
  30104. return this._mesh;
  30105. }*/
  30106. /**
  30107. * Gets the body that holds this impostor. Either its own, or its parent.
  30108. */
  30109. get: function () {
  30110. return this._parent ? this._parent.physicsBody : this._physicsBody;
  30111. },
  30112. /**
  30113. * Set the physics body. Used mainly by the physics engine/plugin
  30114. */
  30115. set: function (physicsBody) {
  30116. if (this._physicsBody) {
  30117. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  30118. }
  30119. this._physicsBody = physicsBody;
  30120. this.resetUpdateFlags();
  30121. },
  30122. enumerable: true,
  30123. configurable: true
  30124. });
  30125. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  30126. get: function () {
  30127. return this._parent;
  30128. },
  30129. enumerable: true,
  30130. configurable: true
  30131. });
  30132. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  30133. this._bodyUpdateRequired = false;
  30134. };
  30135. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  30136. if (this.object.getBoundingInfo) {
  30137. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  30138. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  30139. }
  30140. else {
  30141. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  30142. }
  30143. };
  30144. PhysicsImpostor.prototype.getObjectCenter = function () {
  30145. if (this.object.getBoundingInfo) {
  30146. return this.object.getBoundingInfo().boundingBox.center;
  30147. }
  30148. else {
  30149. return this.object.position;
  30150. }
  30151. };
  30152. /**
  30153. * Get a specific parametes from the options parameter.
  30154. */
  30155. PhysicsImpostor.prototype.getParam = function (paramName) {
  30156. return this._options[paramName];
  30157. };
  30158. /**
  30159. * Sets a specific parameter in the options given to the physics plugin
  30160. */
  30161. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  30162. this._options[paramName] = value;
  30163. this._bodyUpdateRequired = true;
  30164. };
  30165. /**
  30166. * Specifically change the body's mass option. Won't recreate the physics body object
  30167. */
  30168. PhysicsImpostor.prototype.setMass = function (mass) {
  30169. if (this.getParam("mass") !== mass) {
  30170. this.setParam("mass", mass);
  30171. }
  30172. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  30173. };
  30174. PhysicsImpostor.prototype.getLinearVelocity = function () {
  30175. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  30176. };
  30177. /**
  30178. * Set the body's linear velocity.
  30179. */
  30180. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  30181. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  30182. };
  30183. PhysicsImpostor.prototype.getAngularVelocity = function () {
  30184. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  30185. };
  30186. /**
  30187. * Set the body's linear velocity.
  30188. */
  30189. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  30190. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  30191. };
  30192. /**
  30193. * Execute a function with the physics plugin native code.
  30194. * Provide a function the will have two variables - the world object and the physics body object.
  30195. */
  30196. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  30197. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  30198. };
  30199. /**
  30200. * Register a function that will be executed before the physics world is stepping forward.
  30201. */
  30202. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  30203. this._onBeforePhysicsStepCallbacks.push(func);
  30204. };
  30205. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  30206. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  30207. if (index > -1) {
  30208. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  30209. }
  30210. else {
  30211. BABYLON.Tools.Warn("Function to remove was not found");
  30212. }
  30213. };
  30214. /**
  30215. * Register a function that will be executed after the physics step
  30216. */
  30217. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  30218. this._onAfterPhysicsStepCallbacks.push(func);
  30219. };
  30220. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  30221. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  30222. if (index > -1) {
  30223. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  30224. }
  30225. else {
  30226. BABYLON.Tools.Warn("Function to remove was not found");
  30227. }
  30228. };
  30229. /**
  30230. * register a function that will be executed when this impostor collides against a different body.
  30231. */
  30232. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  30233. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  30234. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  30235. };
  30236. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  30237. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  30238. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  30239. if (index > -1) {
  30240. this._onPhysicsCollideCallbacks.splice(index, 1);
  30241. }
  30242. else {
  30243. BABYLON.Tools.Warn("Function to remove was not found");
  30244. }
  30245. };
  30246. /**
  30247. * Apply a force
  30248. */
  30249. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  30250. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  30251. };
  30252. /**
  30253. * Apply an impulse
  30254. */
  30255. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  30256. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  30257. };
  30258. /**
  30259. * A help function to create a joint.
  30260. */
  30261. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  30262. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  30263. this.addJoint(otherImpostor, joint);
  30264. };
  30265. /**
  30266. * Add a joint to this impostor with a different impostor.
  30267. */
  30268. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  30269. this._joints.push({
  30270. otherImpostor: otherImpostor,
  30271. joint: joint
  30272. });
  30273. this._physicsEngine.addJoint(this, otherImpostor, joint);
  30274. };
  30275. /**
  30276. * Will keep this body still, in a sleep mode.
  30277. */
  30278. PhysicsImpostor.prototype.sleep = function () {
  30279. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  30280. };
  30281. /**
  30282. * Wake the body up.
  30283. */
  30284. PhysicsImpostor.prototype.wakeUp = function () {
  30285. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  30286. };
  30287. PhysicsImpostor.prototype.clone = function (newObject) {
  30288. if (!newObject)
  30289. return null;
  30290. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  30291. };
  30292. PhysicsImpostor.prototype.dispose = function () {
  30293. var _this = this;
  30294. //no dispose if no physics engine is available.
  30295. if (!this._physicsEngine) {
  30296. return;
  30297. }
  30298. this._joints.forEach(function (j) {
  30299. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  30300. });
  30301. //dispose the physics body
  30302. this._physicsEngine.removeImpostor(this);
  30303. if (this.parent) {
  30304. this.parent.forceUpdate();
  30305. }
  30306. else {
  30307. }
  30308. };
  30309. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  30310. this._deltaPosition.copyFrom(position);
  30311. };
  30312. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  30313. if (!this._deltaRotation) {
  30314. this._deltaRotation = new BABYLON.Quaternion();
  30315. }
  30316. this._deltaRotation.copyFrom(rotation);
  30317. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  30318. };
  30319. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  30320. //Impostor types
  30321. PhysicsImpostor.NoImpostor = 0;
  30322. PhysicsImpostor.SphereImpostor = 1;
  30323. PhysicsImpostor.BoxImpostor = 2;
  30324. PhysicsImpostor.PlaneImpostor = 3;
  30325. PhysicsImpostor.MeshImpostor = 4;
  30326. PhysicsImpostor.CylinderImpostor = 7;
  30327. PhysicsImpostor.ParticleImpostor = 8;
  30328. PhysicsImpostor.HeightmapImpostor = 9;
  30329. return PhysicsImpostor;
  30330. })();
  30331. BABYLON.PhysicsImpostor = PhysicsImpostor;
  30332. })(BABYLON || (BABYLON = {}));
  30333. var BABYLON;
  30334. (function (BABYLON) {
  30335. var PhysicsEngine = (function () {
  30336. function PhysicsEngine(gravity, _physicsPlugin) {
  30337. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  30338. this._physicsPlugin = _physicsPlugin;
  30339. //new methods and parameters
  30340. this._impostors = [];
  30341. this._joints = [];
  30342. if (!this._physicsPlugin.isSupported()) {
  30343. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  30344. + "Please make sure it is included.");
  30345. }
  30346. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  30347. this.setGravity(gravity);
  30348. this.setTimeStep();
  30349. }
  30350. PhysicsEngine.prototype.setGravity = function (gravity) {
  30351. this.gravity = gravity;
  30352. this._physicsPlugin.setGravity(this.gravity);
  30353. };
  30354. /**
  30355. * Set the time step of the physics engine.
  30356. * default is 1/60.
  30357. * To slow it down, enter 1/600 for example.
  30358. * To speed it up, 1/30
  30359. * @param {number} newTimeStep the new timestep to apply to this world.
  30360. */
  30361. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  30362. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  30363. this._physicsPlugin.setTimeStep(newTimeStep);
  30364. };
  30365. PhysicsEngine.prototype.dispose = function () {
  30366. this._impostors.forEach(function (impostor) {
  30367. impostor.dispose();
  30368. });
  30369. this._physicsPlugin.dispose();
  30370. };
  30371. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  30372. return this._physicsPlugin.name;
  30373. };
  30374. /**
  30375. * Adding a new impostor for the impostor tracking.
  30376. * This will be done by the impostor itself.
  30377. * @param {PhysicsImpostor} impostor the impostor to add
  30378. */
  30379. PhysicsEngine.prototype.addImpostor = function (impostor) {
  30380. impostor.uniqueId = this._impostors.push(impostor);
  30381. //if no parent, generate the body
  30382. if (!impostor.parent) {
  30383. this._physicsPlugin.generatePhysicsBody(impostor);
  30384. }
  30385. };
  30386. /**
  30387. * Remove an impostor from the engine.
  30388. * This impostor and its mesh will not longer be updated by the physics engine.
  30389. * @param {PhysicsImpostor} impostor the impostor to remove
  30390. */
  30391. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  30392. var index = this._impostors.indexOf(impostor);
  30393. if (index > -1) {
  30394. var removed = this._impostors.splice(index, 1);
  30395. //Is it needed?
  30396. if (removed.length) {
  30397. //this will also remove it from the world.
  30398. removed[0].physicsBody = null;
  30399. }
  30400. }
  30401. };
  30402. /**
  30403. * Add a joint to the physics engine
  30404. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  30405. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  30406. * @param {PhysicsJoint} the joint that will connect both impostors.
  30407. */
  30408. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  30409. var impostorJoint = {
  30410. mainImpostor: mainImpostor,
  30411. connectedImpostor: connectedImpostor,
  30412. joint: joint
  30413. };
  30414. joint.physicsPlugin = this._physicsPlugin;
  30415. this._joints.push(impostorJoint);
  30416. this._physicsPlugin.generateJoint(impostorJoint);
  30417. };
  30418. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  30419. var matchingJoints = this._joints.filter(function (impostorJoint) {
  30420. return (impostorJoint.connectedImpostor === connectedImpostor
  30421. && impostorJoint.joint === joint
  30422. && impostorJoint.mainImpostor === mainImpostor);
  30423. });
  30424. if (matchingJoints.length) {
  30425. this._physicsPlugin.removeJoint(matchingJoints[0]);
  30426. }
  30427. };
  30428. /**
  30429. * Called by the scene. no need to call it.
  30430. */
  30431. PhysicsEngine.prototype._step = function (delta) {
  30432. var _this = this;
  30433. //check if any mesh has no body / requires an update
  30434. this._impostors.forEach(function (impostor) {
  30435. if (impostor.isBodyInitRequired()) {
  30436. _this._physicsPlugin.generatePhysicsBody(impostor);
  30437. }
  30438. });
  30439. if (delta > 0.1) {
  30440. delta = 0.1;
  30441. }
  30442. else if (delta <= 0) {
  30443. delta = 1.0 / 60.0;
  30444. }
  30445. this._physicsPlugin.executeStep(delta, this._impostors);
  30446. };
  30447. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  30448. return this._physicsPlugin;
  30449. };
  30450. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  30451. for (var i = 0; i < this._impostors.length; ++i) {
  30452. if (this._impostors[i].object === object) {
  30453. return this._impostors[i];
  30454. }
  30455. }
  30456. };
  30457. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  30458. for (var i = 0; i < this._impostors.length; ++i) {
  30459. if (this._impostors[i].physicsBody === body) {
  30460. return this._impostors[i];
  30461. }
  30462. }
  30463. };
  30464. // Statics, Legacy support.
  30465. /**
  30466. * @Deprecated
  30467. *
  30468. */
  30469. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  30470. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  30471. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  30472. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  30473. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  30474. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  30475. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  30476. PhysicsEngine.CapsuleImpostor = -1;
  30477. PhysicsEngine.ConeImpostor = -1;
  30478. PhysicsEngine.ConvexHullImpostor = -1;
  30479. PhysicsEngine.Epsilon = 0.001;
  30480. return PhysicsEngine;
  30481. })();
  30482. BABYLON.PhysicsEngine = PhysicsEngine;
  30483. })(BABYLON || (BABYLON = {}));
  30484. var BABYLON;
  30485. (function (BABYLON) {
  30486. var VertexData = (function () {
  30487. function VertexData() {
  30488. }
  30489. VertexData.prototype.set = function (data, kind) {
  30490. switch (kind) {
  30491. case BABYLON.VertexBuffer.PositionKind:
  30492. this.positions = data;
  30493. break;
  30494. case BABYLON.VertexBuffer.NormalKind:
  30495. this.normals = data;
  30496. break;
  30497. case BABYLON.VertexBuffer.UVKind:
  30498. this.uvs = data;
  30499. break;
  30500. case BABYLON.VertexBuffer.UV2Kind:
  30501. this.uvs2 = data;
  30502. break;
  30503. case BABYLON.VertexBuffer.UV3Kind:
  30504. this.uvs3 = data;
  30505. break;
  30506. case BABYLON.VertexBuffer.UV4Kind:
  30507. this.uvs4 = data;
  30508. break;
  30509. case BABYLON.VertexBuffer.UV5Kind:
  30510. this.uvs5 = data;
  30511. break;
  30512. case BABYLON.VertexBuffer.UV6Kind:
  30513. this.uvs6 = data;
  30514. break;
  30515. case BABYLON.VertexBuffer.ColorKind:
  30516. this.colors = data;
  30517. break;
  30518. case BABYLON.VertexBuffer.MatricesIndicesKind:
  30519. this.matricesIndices = data;
  30520. break;
  30521. case BABYLON.VertexBuffer.MatricesWeightsKind:
  30522. this.matricesWeights = data;
  30523. break;
  30524. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  30525. this.matricesIndicesExtra = data;
  30526. break;
  30527. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  30528. this.matricesWeightsExtra = data;
  30529. break;
  30530. }
  30531. };
  30532. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  30533. this._applyTo(mesh, updatable);
  30534. };
  30535. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  30536. this._applyTo(geometry, updatable);
  30537. };
  30538. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  30539. this._update(mesh);
  30540. };
  30541. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  30542. this._update(geometry);
  30543. };
  30544. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  30545. if (this.positions) {
  30546. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  30547. }
  30548. if (this.normals) {
  30549. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  30550. }
  30551. if (this.uvs) {
  30552. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  30553. }
  30554. if (this.uvs2) {
  30555. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  30556. }
  30557. if (this.uvs3) {
  30558. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  30559. }
  30560. if (this.uvs4) {
  30561. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  30562. }
  30563. if (this.uvs5) {
  30564. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  30565. }
  30566. if (this.uvs6) {
  30567. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  30568. }
  30569. if (this.colors) {
  30570. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  30571. }
  30572. if (this.matricesIndices) {
  30573. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  30574. }
  30575. if (this.matricesWeights) {
  30576. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  30577. }
  30578. if (this.matricesIndicesExtra) {
  30579. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  30580. }
  30581. if (this.matricesWeightsExtra) {
  30582. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  30583. }
  30584. if (this.indices) {
  30585. meshOrGeometry.setIndices(this.indices);
  30586. }
  30587. };
  30588. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  30589. if (this.positions) {
  30590. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  30591. }
  30592. if (this.normals) {
  30593. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  30594. }
  30595. if (this.uvs) {
  30596. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  30597. }
  30598. if (this.uvs2) {
  30599. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  30600. }
  30601. if (this.uvs3) {
  30602. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  30603. }
  30604. if (this.uvs4) {
  30605. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  30606. }
  30607. if (this.uvs5) {
  30608. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  30609. }
  30610. if (this.uvs6) {
  30611. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  30612. }
  30613. if (this.colors) {
  30614. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  30615. }
  30616. if (this.matricesIndices) {
  30617. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  30618. }
  30619. if (this.matricesWeights) {
  30620. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  30621. }
  30622. if (this.matricesIndicesExtra) {
  30623. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  30624. }
  30625. if (this.matricesWeightsExtra) {
  30626. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  30627. }
  30628. if (this.indices) {
  30629. meshOrGeometry.setIndices(this.indices);
  30630. }
  30631. };
  30632. VertexData.prototype.transform = function (matrix) {
  30633. var transformed = BABYLON.Vector3.Zero();
  30634. var index;
  30635. if (this.positions) {
  30636. var position = BABYLON.Vector3.Zero();
  30637. for (index = 0; index < this.positions.length; index += 3) {
  30638. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  30639. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  30640. this.positions[index] = transformed.x;
  30641. this.positions[index + 1] = transformed.y;
  30642. this.positions[index + 2] = transformed.z;
  30643. }
  30644. }
  30645. if (this.normals) {
  30646. var normal = BABYLON.Vector3.Zero();
  30647. for (index = 0; index < this.normals.length; index += 3) {
  30648. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  30649. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  30650. this.normals[index] = transformed.x;
  30651. this.normals[index + 1] = transformed.y;
  30652. this.normals[index + 2] = transformed.z;
  30653. }
  30654. }
  30655. };
  30656. VertexData.prototype.merge = function (other) {
  30657. if (other.indices) {
  30658. if (!this.indices) {
  30659. this.indices = [];
  30660. }
  30661. var offset = this.positions ? this.positions.length / 3 : 0;
  30662. for (var index = 0; index < other.indices.length; index++) {
  30663. //TODO check type - if Int32Array!
  30664. this.indices.push(other.indices[index] + offset);
  30665. }
  30666. }
  30667. this.positions = this._mergeElement(this.positions, other.positions);
  30668. this.normals = this._mergeElement(this.normals, other.normals);
  30669. this.uvs = this._mergeElement(this.uvs, other.uvs);
  30670. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  30671. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  30672. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  30673. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  30674. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  30675. this.colors = this._mergeElement(this.colors, other.colors);
  30676. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  30677. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  30678. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  30679. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  30680. };
  30681. VertexData.prototype._mergeElement = function (source, other) {
  30682. if (!other)
  30683. return source;
  30684. if (!source)
  30685. return other;
  30686. var len = other.length + source.length;
  30687. var isSrcTypedArray = source instanceof Float32Array;
  30688. var isOthTypedArray = other instanceof Float32Array;
  30689. // use non-loop method when the source is Float32Array
  30690. if (isSrcTypedArray) {
  30691. var ret32 = new Float32Array(len);
  30692. ret32.set(source);
  30693. ret32.set(other, source.length);
  30694. return ret32;
  30695. }
  30696. else if (!isOthTypedArray) {
  30697. return source.concat(other);
  30698. }
  30699. else {
  30700. var ret = source.slice(0); // copy source to a separate array
  30701. for (var i = 0, len = other.length; i < len; i++) {
  30702. ret.push(other[i]);
  30703. }
  30704. return ret;
  30705. }
  30706. };
  30707. VertexData.prototype.serialize = function () {
  30708. var serializationObject = this.serialize();
  30709. if (this.positions) {
  30710. serializationObject.positions = this.positions;
  30711. }
  30712. if (this.normals) {
  30713. serializationObject.normals = this.normals;
  30714. }
  30715. if (this.uvs) {
  30716. serializationObject.uvs = this.uvs;
  30717. }
  30718. if (this.uvs2) {
  30719. serializationObject.uvs2 = this.uvs2;
  30720. }
  30721. if (this.uvs3) {
  30722. serializationObject.uvs3 = this.uvs3;
  30723. }
  30724. if (this.uvs4) {
  30725. serializationObject.uvs4 = this.uvs4;
  30726. }
  30727. if (this.uvs5) {
  30728. serializationObject.uvs5 = this.uvs5;
  30729. }
  30730. if (this.uvs6) {
  30731. serializationObject.uvs6 = this.uvs6;
  30732. }
  30733. if (this.colors) {
  30734. serializationObject.colors = this.colors;
  30735. }
  30736. if (this.matricesIndices) {
  30737. serializationObject.matricesIndices = this.matricesIndices;
  30738. serializationObject.matricesIndices._isExpanded = true;
  30739. }
  30740. if (this.matricesWeights) {
  30741. serializationObject.matricesWeights = this.matricesWeights;
  30742. }
  30743. if (this.matricesIndicesExtra) {
  30744. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  30745. serializationObject.matricesIndicesExtra._isExpanded = true;
  30746. }
  30747. if (this.matricesWeightsExtra) {
  30748. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  30749. }
  30750. serializationObject.indices = this.indices;
  30751. return serializationObject;
  30752. };
  30753. // Statics
  30754. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  30755. return VertexData._ExtractFrom(mesh, copyWhenShared);
  30756. };
  30757. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  30758. return VertexData._ExtractFrom(geometry, copyWhenShared);
  30759. };
  30760. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  30761. var result = new VertexData();
  30762. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30763. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  30764. }
  30765. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30766. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  30767. }
  30768. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30769. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  30770. }
  30771. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30772. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  30773. }
  30774. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30775. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  30776. }
  30777. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30778. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  30779. }
  30780. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30781. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  30782. }
  30783. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30784. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  30785. }
  30786. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30787. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  30788. }
  30789. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30790. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  30791. }
  30792. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30793. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  30794. }
  30795. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  30796. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  30797. }
  30798. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  30799. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  30800. }
  30801. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  30802. return result;
  30803. };
  30804. VertexData.CreateRibbon = function (options) {
  30805. var pathArray = options.pathArray;
  30806. var closeArray = options.closeArray || false;
  30807. var closePath = options.closePath || false;
  30808. var invertUV = options.invertUV || false;
  30809. var defaultOffset = Math.floor(pathArray[0].length / 2);
  30810. var offset = options.offset || defaultOffset;
  30811. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  30812. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30813. var positions = [];
  30814. var indices = [];
  30815. var normals = [];
  30816. var uvs = [];
  30817. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  30818. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  30819. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  30820. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  30821. var minlg; // minimal length among all paths from pathArray
  30822. var lg = []; // array of path lengths : nb of vertex per path
  30823. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  30824. var p; // path iterator
  30825. var i; // point iterator
  30826. var j; // point iterator
  30827. // if single path in pathArray
  30828. if (pathArray.length < 2) {
  30829. var ar1 = [];
  30830. var ar2 = [];
  30831. for (i = 0; i < pathArray[0].length - offset; i++) {
  30832. ar1.push(pathArray[0][i]);
  30833. ar2.push(pathArray[0][i + offset]);
  30834. }
  30835. pathArray = [ar1, ar2];
  30836. }
  30837. // positions and horizontal distances (u)
  30838. var idc = 0;
  30839. var closePathCorr = (closePath) ? 1 : 0;
  30840. var path;
  30841. var l;
  30842. minlg = pathArray[0].length;
  30843. var vectlg;
  30844. var dist;
  30845. for (p = 0; p < pathArray.length; p++) {
  30846. uTotalDistance[p] = 0;
  30847. us[p] = [0];
  30848. path = pathArray[p];
  30849. l = path.length;
  30850. minlg = (minlg < l) ? minlg : l;
  30851. j = 0;
  30852. while (j < l) {
  30853. positions.push(path[j].x, path[j].y, path[j].z);
  30854. if (j > 0) {
  30855. vectlg = path[j].subtract(path[j - 1]).length();
  30856. dist = vectlg + uTotalDistance[p];
  30857. us[p].push(dist);
  30858. uTotalDistance[p] = dist;
  30859. }
  30860. j++;
  30861. }
  30862. if (closePath) {
  30863. j--;
  30864. positions.push(path[0].x, path[0].y, path[0].z);
  30865. vectlg = path[j].subtract(path[0]).length();
  30866. dist = vectlg + uTotalDistance[p];
  30867. us[p].push(dist);
  30868. uTotalDistance[p] = dist;
  30869. }
  30870. lg[p] = l + closePathCorr;
  30871. idx[p] = idc;
  30872. idc += (l + closePathCorr);
  30873. }
  30874. // vertical distances (v)
  30875. var path1;
  30876. var path2;
  30877. var vertex1;
  30878. var vertex2;
  30879. for (i = 0; i < minlg + closePathCorr; i++) {
  30880. vTotalDistance[i] = 0;
  30881. vs[i] = [0];
  30882. for (p = 0; p < pathArray.length - 1; p++) {
  30883. path1 = pathArray[p];
  30884. path2 = pathArray[p + 1];
  30885. if (i === minlg) {
  30886. vertex1 = path1[0];
  30887. vertex2 = path2[0];
  30888. }
  30889. else {
  30890. vertex1 = path1[i];
  30891. vertex2 = path2[i];
  30892. }
  30893. vectlg = vertex2.subtract(vertex1).length();
  30894. dist = vectlg + vTotalDistance[i];
  30895. vs[i].push(dist);
  30896. vTotalDistance[i] = dist;
  30897. }
  30898. if (closeArray) {
  30899. path1 = pathArray[p];
  30900. path2 = pathArray[0];
  30901. if (i === minlg) {
  30902. vertex2 = path2[0];
  30903. }
  30904. vectlg = vertex2.subtract(vertex1).length();
  30905. dist = vectlg + vTotalDistance[i];
  30906. vTotalDistance[i] = dist;
  30907. }
  30908. }
  30909. // uvs
  30910. var u;
  30911. var v;
  30912. for (p = 0; p < pathArray.length; p++) {
  30913. for (i = 0; i < minlg + closePathCorr; i++) {
  30914. u = us[p][i] / uTotalDistance[p];
  30915. v = vs[i][p] / vTotalDistance[i];
  30916. if (invertUV) {
  30917. uvs.push(v, u);
  30918. }
  30919. else {
  30920. uvs.push(u, v);
  30921. }
  30922. }
  30923. }
  30924. // indices
  30925. p = 0; // path index
  30926. var pi = 0; // positions array index
  30927. var l1 = lg[p] - 1; // path1 length
  30928. var l2 = lg[p + 1] - 1; // path2 length
  30929. var min = (l1 < l2) ? l1 : l2; // current path stop index
  30930. var shft = idx[1] - idx[0]; // shift
  30931. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  30932. while (pi <= min && p < path1nb) {
  30933. // 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
  30934. indices.push(pi, pi + shft, pi + 1);
  30935. indices.push(pi + shft + 1, pi + 1, pi + shft);
  30936. pi += 1;
  30937. if (pi === min) {
  30938. p++;
  30939. if (p === lg.length - 1) {
  30940. shft = idx[0] - idx[p];
  30941. l1 = lg[p] - 1;
  30942. l2 = lg[0] - 1;
  30943. }
  30944. else {
  30945. shft = idx[p + 1] - idx[p];
  30946. l1 = lg[p] - 1;
  30947. l2 = lg[p + 1] - 1;
  30948. }
  30949. pi = idx[p];
  30950. min = (l1 < l2) ? l1 + pi : l2 + pi;
  30951. }
  30952. }
  30953. // normals
  30954. VertexData.ComputeNormals(positions, indices, normals);
  30955. if (closePath) {
  30956. var indexFirst = 0;
  30957. var indexLast = 0;
  30958. for (p = 0; p < pathArray.length; p++) {
  30959. indexFirst = idx[p] * 3;
  30960. if (p + 1 < pathArray.length) {
  30961. indexLast = (idx[p + 1] - 1) * 3;
  30962. }
  30963. else {
  30964. indexLast = normals.length - 3;
  30965. }
  30966. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  30967. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  30968. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  30969. normals[indexLast] = normals[indexFirst];
  30970. normals[indexLast + 1] = normals[indexFirst + 1];
  30971. normals[indexLast + 2] = normals[indexFirst + 2];
  30972. }
  30973. }
  30974. // sides
  30975. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30976. // Result
  30977. var vertexData = new VertexData();
  30978. vertexData.indices = indices;
  30979. vertexData.positions = positions;
  30980. vertexData.normals = normals;
  30981. vertexData.uvs = uvs;
  30982. if (closePath) {
  30983. vertexData._idx = idx;
  30984. }
  30985. return vertexData;
  30986. };
  30987. VertexData.CreateBox = function (options) {
  30988. var normalsSource = [
  30989. new BABYLON.Vector3(0, 0, 1),
  30990. new BABYLON.Vector3(0, 0, -1),
  30991. new BABYLON.Vector3(1, 0, 0),
  30992. new BABYLON.Vector3(-1, 0, 0),
  30993. new BABYLON.Vector3(0, 1, 0),
  30994. new BABYLON.Vector3(0, -1, 0)
  30995. ];
  30996. var indices = [];
  30997. var positions = [];
  30998. var normals = [];
  30999. var uvs = [];
  31000. var width = options.width || options.size || 1;
  31001. var height = options.height || options.size || 1;
  31002. var depth = options.depth || options.size || 1;
  31003. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31004. var faceUV = options.faceUV || new Array(6);
  31005. var faceColors = options.faceColors;
  31006. var colors = [];
  31007. // default face colors and UV if undefined
  31008. for (var f = 0; f < 6; f++) {
  31009. if (faceUV[f] === undefined) {
  31010. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31011. }
  31012. if (faceColors && faceColors[f] === undefined) {
  31013. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31014. }
  31015. }
  31016. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  31017. // Create each face in turn.
  31018. for (var index = 0; index < normalsSource.length; index++) {
  31019. var normal = normalsSource[index];
  31020. // Get two vectors perpendicular to the face normal and to each other.
  31021. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  31022. var side2 = BABYLON.Vector3.Cross(normal, side1);
  31023. // Six indices (two triangles) per face.
  31024. var verticesLength = positions.length / 3;
  31025. indices.push(verticesLength);
  31026. indices.push(verticesLength + 1);
  31027. indices.push(verticesLength + 2);
  31028. indices.push(verticesLength);
  31029. indices.push(verticesLength + 2);
  31030. indices.push(verticesLength + 3);
  31031. // Four vertices per face.
  31032. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  31033. positions.push(vertex.x, vertex.y, vertex.z);
  31034. normals.push(normal.x, normal.y, normal.z);
  31035. uvs.push(faceUV[index].z, faceUV[index].w);
  31036. if (faceColors) {
  31037. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31038. }
  31039. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  31040. positions.push(vertex.x, vertex.y, vertex.z);
  31041. normals.push(normal.x, normal.y, normal.z);
  31042. uvs.push(faceUV[index].x, faceUV[index].w);
  31043. if (faceColors) {
  31044. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31045. }
  31046. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  31047. positions.push(vertex.x, vertex.y, vertex.z);
  31048. normals.push(normal.x, normal.y, normal.z);
  31049. uvs.push(faceUV[index].x, faceUV[index].y);
  31050. if (faceColors) {
  31051. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31052. }
  31053. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  31054. positions.push(vertex.x, vertex.y, vertex.z);
  31055. normals.push(normal.x, normal.y, normal.z);
  31056. uvs.push(faceUV[index].z, faceUV[index].y);
  31057. if (faceColors) {
  31058. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31059. }
  31060. }
  31061. // sides
  31062. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31063. // Result
  31064. var vertexData = new VertexData();
  31065. vertexData.indices = indices;
  31066. vertexData.positions = positions;
  31067. vertexData.normals = normals;
  31068. vertexData.uvs = uvs;
  31069. if (faceColors) {
  31070. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31071. vertexData.colors = totalColors;
  31072. }
  31073. return vertexData;
  31074. };
  31075. VertexData.CreateSphere = function (options) {
  31076. var segments = options.segments || 32;
  31077. var diameterX = options.diameterX || options.diameter || 1;
  31078. var diameterY = options.diameterY || options.diameter || 1;
  31079. var diameterZ = options.diameterZ || options.diameter || 1;
  31080. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31081. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  31082. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31083. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  31084. var totalZRotationSteps = 2 + segments;
  31085. var totalYRotationSteps = 2 * totalZRotationSteps;
  31086. var indices = [];
  31087. var positions = [];
  31088. var normals = [];
  31089. var uvs = [];
  31090. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  31091. var normalizedZ = zRotationStep / totalZRotationSteps;
  31092. var angleZ = normalizedZ * Math.PI * slice;
  31093. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  31094. var normalizedY = yRotationStep / totalYRotationSteps;
  31095. var angleY = normalizedY * Math.PI * 2 * arc;
  31096. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  31097. var rotationY = BABYLON.Matrix.RotationY(angleY);
  31098. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  31099. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  31100. var vertex = complete.multiply(radius);
  31101. var normal = complete.divide(radius).normalize();
  31102. positions.push(vertex.x, vertex.y, vertex.z);
  31103. normals.push(normal.x, normal.y, normal.z);
  31104. uvs.push(normalizedY, normalizedZ);
  31105. }
  31106. if (zRotationStep > 0) {
  31107. var verticesCount = positions.length / 3;
  31108. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  31109. indices.push((firstIndex));
  31110. indices.push((firstIndex + 1));
  31111. indices.push(firstIndex + totalYRotationSteps + 1);
  31112. indices.push((firstIndex + totalYRotationSteps + 1));
  31113. indices.push((firstIndex + 1));
  31114. indices.push((firstIndex + totalYRotationSteps + 2));
  31115. }
  31116. }
  31117. }
  31118. // Sides
  31119. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31120. // Result
  31121. var vertexData = new VertexData();
  31122. vertexData.indices = indices;
  31123. vertexData.positions = positions;
  31124. vertexData.normals = normals;
  31125. vertexData.uvs = uvs;
  31126. return vertexData;
  31127. };
  31128. // Cylinder and cone
  31129. VertexData.CreateCylinder = function (options) {
  31130. var height = options.height || 2;
  31131. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  31132. var diameterBottom = options.diameterBottom || options.diameter || 1;
  31133. var tessellation = options.tessellation || 24;
  31134. var subdivisions = options.subdivisions || 1;
  31135. var hasRings = options.hasRings;
  31136. var enclose = options.enclose;
  31137. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31138. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31139. var faceUV = options.faceUV || new Array(3);
  31140. var faceColors = options.faceColors;
  31141. // default face colors and UV if undefined
  31142. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  31143. var ringNb = (hasRings) ? subdivisions : 1;
  31144. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  31145. var f;
  31146. for (f = 0; f < surfaceNb; f++) {
  31147. if (faceColors && faceColors[f] === undefined) {
  31148. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31149. }
  31150. }
  31151. for (f = 0; f < surfaceNb; f++) {
  31152. if (faceUV && faceUV[f] === undefined) {
  31153. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31154. }
  31155. }
  31156. var indices = [];
  31157. var positions = [];
  31158. var normals = [];
  31159. var uvs = [];
  31160. var colors = [];
  31161. var angle_step = Math.PI * 2 * arc / tessellation;
  31162. var angle;
  31163. var h;
  31164. var radius;
  31165. var tan = (diameterBottom - diameterTop) / 2 / height;
  31166. var ringVertex = BABYLON.Vector3.Zero();
  31167. var ringNormal = BABYLON.Vector3.Zero();
  31168. var ringFirstVertex = BABYLON.Vector3.Zero();
  31169. var ringFirstNormal = BABYLON.Vector3.Zero();
  31170. var quadNormal = BABYLON.Vector3.Zero();
  31171. var Y = BABYLON.Axis.Y;
  31172. // positions, normals, uvs
  31173. var i;
  31174. var j;
  31175. var r;
  31176. var ringIdx = 1;
  31177. var s = 1; // surface index
  31178. var cs = 0;
  31179. var v = 0;
  31180. for (i = 0; i <= subdivisions; i++) {
  31181. h = i / subdivisions;
  31182. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  31183. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  31184. for (r = 0; r < ringIdx; r++) {
  31185. if (hasRings) {
  31186. s += r;
  31187. }
  31188. if (enclose) {
  31189. s += 2 * r;
  31190. }
  31191. for (j = 0; j <= tessellation; j++) {
  31192. angle = j * angle_step;
  31193. // position
  31194. ringVertex.x = Math.cos(-angle) * radius;
  31195. ringVertex.y = -height / 2 + h * height;
  31196. ringVertex.z = Math.sin(-angle) * radius;
  31197. // normal
  31198. if (diameterTop === 0 && i === subdivisions) {
  31199. // if no top cap, reuse former normals
  31200. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  31201. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  31202. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  31203. }
  31204. else {
  31205. ringNormal.x = ringVertex.x;
  31206. ringNormal.z = ringVertex.z;
  31207. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  31208. ringNormal.normalize();
  31209. }
  31210. // keep first ring vertex values for enclose
  31211. if (j === 0) {
  31212. ringFirstVertex.copyFrom(ringVertex);
  31213. ringFirstNormal.copyFrom(ringNormal);
  31214. }
  31215. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31216. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  31217. if (hasRings) {
  31218. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  31219. }
  31220. else {
  31221. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  31222. }
  31223. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  31224. if (faceColors) {
  31225. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  31226. }
  31227. }
  31228. // if enclose, add four vertices and their dedicated normals
  31229. if (arc !== 1 && enclose) {
  31230. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31231. positions.push(0, ringVertex.y, 0);
  31232. positions.push(0, ringVertex.y, 0);
  31233. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  31234. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  31235. quadNormal.normalize();
  31236. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31237. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  31238. quadNormal.normalize();
  31239. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31240. if (hasRings) {
  31241. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  31242. }
  31243. else {
  31244. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  31245. }
  31246. uvs.push(faceUV[s + 1].x, v);
  31247. uvs.push(faceUV[s + 1].z, v);
  31248. if (hasRings) {
  31249. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  31250. }
  31251. else {
  31252. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  31253. }
  31254. uvs.push(faceUV[s + 2].x, v);
  31255. uvs.push(faceUV[s + 2].z, v);
  31256. if (faceColors) {
  31257. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31258. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31259. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31260. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31261. }
  31262. }
  31263. if (cs !== s) {
  31264. cs = s;
  31265. }
  31266. }
  31267. }
  31268. // indices
  31269. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  31270. var s;
  31271. i = 0;
  31272. for (s = 0; s < subdivisions; s++) {
  31273. for (j = 0; j < tessellation; j++) {
  31274. var i0 = i * (e + 1) + j;
  31275. var i1 = (i + 1) * (e + 1) + j;
  31276. var i2 = i * (e + 1) + (j + 1);
  31277. var i3 = (i + 1) * (e + 1) + (j + 1);
  31278. indices.push(i0, i1, i2);
  31279. indices.push(i3, i2, i1);
  31280. }
  31281. if (arc !== 1 && enclose) {
  31282. indices.push(i0 + 2, i1 + 2, i2 + 2);
  31283. indices.push(i3 + 2, i2 + 2, i1 + 2);
  31284. indices.push(i0 + 4, i1 + 4, i2 + 4);
  31285. indices.push(i3 + 4, i2 + 4, i1 + 4);
  31286. }
  31287. i = (hasRings) ? (i + 2) : (i + 1);
  31288. }
  31289. // Caps
  31290. var createCylinderCap = function (isTop) {
  31291. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  31292. if (radius === 0) {
  31293. return;
  31294. }
  31295. // Cap positions, normals & uvs
  31296. var angle;
  31297. var circleVector;
  31298. var i;
  31299. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  31300. var c;
  31301. if (faceColors) {
  31302. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  31303. }
  31304. // cap center
  31305. var vbase = positions.length / 3;
  31306. var offset = isTop ? height / 2 : -height / 2;
  31307. var center = new BABYLON.Vector3(0, offset, 0);
  31308. positions.push(center.x, center.y, center.z);
  31309. normals.push(0, isTop ? 1 : -1, 0);
  31310. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  31311. if (faceColors) {
  31312. colors.push(c.r, c.g, c.b, c.a);
  31313. }
  31314. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  31315. for (i = 0; i <= tessellation; i++) {
  31316. angle = Math.PI * 2 * i * arc / tessellation;
  31317. var cos = Math.cos(-angle);
  31318. var sin = Math.sin(-angle);
  31319. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  31320. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  31321. positions.push(circleVector.x, circleVector.y, circleVector.z);
  31322. normals.push(0, isTop ? 1 : -1, 0);
  31323. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  31324. if (faceColors) {
  31325. colors.push(c.r, c.g, c.b, c.a);
  31326. }
  31327. }
  31328. // Cap indices
  31329. for (i = 0; i < tessellation; i++) {
  31330. if (!isTop) {
  31331. indices.push(vbase);
  31332. indices.push(vbase + (i + 1));
  31333. indices.push(vbase + (i + 2));
  31334. }
  31335. else {
  31336. indices.push(vbase);
  31337. indices.push(vbase + (i + 2));
  31338. indices.push(vbase + (i + 1));
  31339. }
  31340. }
  31341. };
  31342. // add caps to geometry
  31343. createCylinderCap(false);
  31344. createCylinderCap(true);
  31345. // Sides
  31346. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31347. var vertexData = new VertexData();
  31348. vertexData.indices = indices;
  31349. vertexData.positions = positions;
  31350. vertexData.normals = normals;
  31351. vertexData.uvs = uvs;
  31352. if (faceColors) {
  31353. vertexData.colors = colors;
  31354. }
  31355. return vertexData;
  31356. };
  31357. VertexData.CreateTorus = function (options) {
  31358. var indices = [];
  31359. var positions = [];
  31360. var normals = [];
  31361. var uvs = [];
  31362. var diameter = options.diameter || 1;
  31363. var thickness = options.thickness || 0.5;
  31364. var tessellation = options.tessellation || 16;
  31365. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31366. var stride = tessellation + 1;
  31367. for (var i = 0; i <= tessellation; i++) {
  31368. var u = i / tessellation;
  31369. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  31370. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  31371. for (var j = 0; j <= tessellation; j++) {
  31372. var v = 1 - j / tessellation;
  31373. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  31374. var dx = Math.cos(innerAngle);
  31375. var dy = Math.sin(innerAngle);
  31376. // Create a vertex.
  31377. var normal = new BABYLON.Vector3(dx, dy, 0);
  31378. var position = normal.scale(thickness / 2);
  31379. var textureCoordinate = new BABYLON.Vector2(u, v);
  31380. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  31381. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  31382. positions.push(position.x, position.y, position.z);
  31383. normals.push(normal.x, normal.y, normal.z);
  31384. uvs.push(textureCoordinate.x, textureCoordinate.y);
  31385. // And create indices for two triangles.
  31386. var nextI = (i + 1) % stride;
  31387. var nextJ = (j + 1) % stride;
  31388. indices.push(i * stride + j);
  31389. indices.push(i * stride + nextJ);
  31390. indices.push(nextI * stride + j);
  31391. indices.push(i * stride + nextJ);
  31392. indices.push(nextI * stride + nextJ);
  31393. indices.push(nextI * stride + j);
  31394. }
  31395. }
  31396. // Sides
  31397. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31398. // Result
  31399. var vertexData = new VertexData();
  31400. vertexData.indices = indices;
  31401. vertexData.positions = positions;
  31402. vertexData.normals = normals;
  31403. vertexData.uvs = uvs;
  31404. return vertexData;
  31405. };
  31406. VertexData.CreateLineSystem = function (options) {
  31407. var indices = [];
  31408. var positions = [];
  31409. var lines = options.lines;
  31410. var idx = 0;
  31411. for (var l = 0; l < lines.length; l++) {
  31412. var points = lines[l];
  31413. for (var index = 0; index < points.length; index++) {
  31414. positions.push(points[index].x, points[index].y, points[index].z);
  31415. if (index > 0) {
  31416. indices.push(idx - 1);
  31417. indices.push(idx);
  31418. }
  31419. idx++;
  31420. }
  31421. }
  31422. var vertexData = new VertexData();
  31423. vertexData.indices = indices;
  31424. vertexData.positions = positions;
  31425. return vertexData;
  31426. };
  31427. VertexData.CreateDashedLines = function (options) {
  31428. var dashSize = options.dashSize || 3;
  31429. var gapSize = options.gapSize || 1;
  31430. var dashNb = options.dashNb || 200;
  31431. var points = options.points;
  31432. var positions = new Array();
  31433. var indices = new Array();
  31434. var curvect = BABYLON.Vector3.Zero();
  31435. var lg = 0;
  31436. var nb = 0;
  31437. var shft = 0;
  31438. var dashshft = 0;
  31439. var curshft = 0;
  31440. var idx = 0;
  31441. var i = 0;
  31442. for (i = 0; i < points.length - 1; i++) {
  31443. points[i + 1].subtractToRef(points[i], curvect);
  31444. lg += curvect.length();
  31445. }
  31446. shft = lg / dashNb;
  31447. dashshft = dashSize * shft / (dashSize + gapSize);
  31448. for (i = 0; i < points.length - 1; i++) {
  31449. points[i + 1].subtractToRef(points[i], curvect);
  31450. nb = Math.floor(curvect.length() / shft);
  31451. curvect.normalize();
  31452. for (var j = 0; j < nb; j++) {
  31453. curshft = shft * j;
  31454. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  31455. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  31456. indices.push(idx, idx + 1);
  31457. idx += 2;
  31458. }
  31459. }
  31460. // Result
  31461. var vertexData = new VertexData();
  31462. vertexData.positions = positions;
  31463. vertexData.indices = indices;
  31464. return vertexData;
  31465. };
  31466. VertexData.CreateGround = function (options) {
  31467. var indices = [];
  31468. var positions = [];
  31469. var normals = [];
  31470. var uvs = [];
  31471. var row, col;
  31472. var width = options.width || 1;
  31473. var height = options.height || 1;
  31474. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  31475. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  31476. for (row = 0; row <= subdivisionsY; row++) {
  31477. for (col = 0; col <= subdivisionsX; col++) {
  31478. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  31479. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31480. positions.push(position.x, position.y, position.z);
  31481. normals.push(normal.x, normal.y, normal.z);
  31482. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsX);
  31483. }
  31484. }
  31485. for (row = 0; row < subdivisionsY; row++) {
  31486. for (col = 0; col < subdivisionsX; col++) {
  31487. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31488. indices.push(col + 1 + row * (subdivisionsX + 1));
  31489. indices.push(col + row * (subdivisionsX + 1));
  31490. indices.push(col + (row + 1) * (subdivisionsX + 1));
  31491. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31492. indices.push(col + row * (subdivisionsX + 1));
  31493. }
  31494. }
  31495. // Result
  31496. var vertexData = new VertexData();
  31497. vertexData.indices = indices;
  31498. vertexData.positions = positions;
  31499. vertexData.normals = normals;
  31500. vertexData.uvs = uvs;
  31501. return vertexData;
  31502. };
  31503. VertexData.CreateTiledGround = function (options) {
  31504. var xmin = options.xmin || -1.0;
  31505. var zmin = options.zmin || -1.0;
  31506. var xmax = options.xmax || 1.0;
  31507. var zmax = options.zmax || 1.0;
  31508. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  31509. var precision = options.precision || { w: 1, h: 1 };
  31510. var indices = [];
  31511. var positions = [];
  31512. var normals = [];
  31513. var uvs = [];
  31514. var row, col, tileRow, tileCol;
  31515. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  31516. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  31517. precision.w = (precision.w < 1) ? 1 : precision.w;
  31518. precision.h = (precision.h < 1) ? 1 : precision.h;
  31519. var tileSize = {
  31520. 'w': (xmax - xmin) / subdivisions.w,
  31521. 'h': (zmax - zmin) / subdivisions.h
  31522. };
  31523. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  31524. // Indices
  31525. var base = positions.length / 3;
  31526. var rowLength = precision.w + 1;
  31527. for (row = 0; row < precision.h; row++) {
  31528. for (col = 0; col < precision.w; col++) {
  31529. var square = [
  31530. base + col + row * rowLength,
  31531. base + (col + 1) + row * rowLength,
  31532. base + (col + 1) + (row + 1) * rowLength,
  31533. base + col + (row + 1) * rowLength
  31534. ];
  31535. indices.push(square[1]);
  31536. indices.push(square[2]);
  31537. indices.push(square[3]);
  31538. indices.push(square[0]);
  31539. indices.push(square[1]);
  31540. indices.push(square[3]);
  31541. }
  31542. }
  31543. // Position, normals and uvs
  31544. var position = BABYLON.Vector3.Zero();
  31545. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31546. for (row = 0; row <= precision.h; row++) {
  31547. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  31548. for (col = 0; col <= precision.w; col++) {
  31549. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  31550. position.y = 0;
  31551. positions.push(position.x, position.y, position.z);
  31552. normals.push(normal.x, normal.y, normal.z);
  31553. uvs.push(col / precision.w, row / precision.h);
  31554. }
  31555. }
  31556. }
  31557. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  31558. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  31559. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  31560. }
  31561. }
  31562. // Result
  31563. var vertexData = new VertexData();
  31564. vertexData.indices = indices;
  31565. vertexData.positions = positions;
  31566. vertexData.normals = normals;
  31567. vertexData.uvs = uvs;
  31568. return vertexData;
  31569. };
  31570. VertexData.CreateGroundFromHeightMap = function (options) {
  31571. var indices = [];
  31572. var positions = [];
  31573. var normals = [];
  31574. var uvs = [];
  31575. var row, col;
  31576. // Vertices
  31577. for (row = 0; row <= options.subdivisions; row++) {
  31578. for (col = 0; col <= options.subdivisions; col++) {
  31579. 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));
  31580. // Compute height
  31581. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  31582. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  31583. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  31584. var r = options.buffer[pos] / 255.0;
  31585. var g = options.buffer[pos + 1] / 255.0;
  31586. var b = options.buffer[pos + 2] / 255.0;
  31587. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  31588. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  31589. // Add vertex
  31590. positions.push(position.x, position.y, position.z);
  31591. normals.push(0, 0, 0);
  31592. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  31593. }
  31594. }
  31595. // Indices
  31596. for (row = 0; row < options.subdivisions; row++) {
  31597. for (col = 0; col < options.subdivisions; col++) {
  31598. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31599. indices.push(col + 1 + row * (options.subdivisions + 1));
  31600. indices.push(col + row * (options.subdivisions + 1));
  31601. indices.push(col + (row + 1) * (options.subdivisions + 1));
  31602. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31603. indices.push(col + row * (options.subdivisions + 1));
  31604. }
  31605. }
  31606. // Normals
  31607. VertexData.ComputeNormals(positions, indices, normals);
  31608. // Result
  31609. var vertexData = new VertexData();
  31610. vertexData.indices = indices;
  31611. vertexData.positions = positions;
  31612. vertexData.normals = normals;
  31613. vertexData.uvs = uvs;
  31614. return vertexData;
  31615. };
  31616. VertexData.CreatePlane = function (options) {
  31617. var indices = [];
  31618. var positions = [];
  31619. var normals = [];
  31620. var uvs = [];
  31621. var width = options.width || options.size || 1;
  31622. var height = options.height || options.size || 1;
  31623. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31624. // Vertices
  31625. var halfWidth = width / 2.0;
  31626. var halfHeight = height / 2.0;
  31627. positions.push(-halfWidth, -halfHeight, 0);
  31628. normals.push(0, 0, -1.0);
  31629. uvs.push(0.0, 0.0);
  31630. positions.push(halfWidth, -halfHeight, 0);
  31631. normals.push(0, 0, -1.0);
  31632. uvs.push(1.0, 0.0);
  31633. positions.push(halfWidth, halfHeight, 0);
  31634. normals.push(0, 0, -1.0);
  31635. uvs.push(1.0, 1.0);
  31636. positions.push(-halfWidth, halfHeight, 0);
  31637. normals.push(0, 0, -1.0);
  31638. uvs.push(0.0, 1.0);
  31639. // Indices
  31640. indices.push(0);
  31641. indices.push(1);
  31642. indices.push(2);
  31643. indices.push(0);
  31644. indices.push(2);
  31645. indices.push(3);
  31646. // Sides
  31647. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31648. // Result
  31649. var vertexData = new VertexData();
  31650. vertexData.indices = indices;
  31651. vertexData.positions = positions;
  31652. vertexData.normals = normals;
  31653. vertexData.uvs = uvs;
  31654. return vertexData;
  31655. };
  31656. VertexData.CreateDisc = function (options) {
  31657. var positions = [];
  31658. var indices = [];
  31659. var normals = [];
  31660. var uvs = [];
  31661. var radius = options.radius || 0.5;
  31662. var tessellation = options.tessellation || 64;
  31663. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31664. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31665. // positions and uvs
  31666. positions.push(0, 0, 0); // disc center first
  31667. uvs.push(0.5, 0.5);
  31668. var theta = Math.PI * 2 * arc;
  31669. var step = theta / tessellation;
  31670. for (var a = 0; a < theta; a += step) {
  31671. var x = Math.cos(a);
  31672. var y = Math.sin(a);
  31673. var u = (x + 1) / 2;
  31674. var v = (1 - y) / 2;
  31675. positions.push(radius * x, radius * y, 0);
  31676. uvs.push(u, v);
  31677. }
  31678. if (arc === 1) {
  31679. positions.push(positions[3], positions[4], positions[5]); // close the circle
  31680. uvs.push(uvs[2], uvs[3]);
  31681. }
  31682. //indices
  31683. var vertexNb = positions.length / 3;
  31684. for (var i = 1; i < vertexNb - 1; i++) {
  31685. indices.push(i + 1, 0, i);
  31686. }
  31687. // result
  31688. VertexData.ComputeNormals(positions, indices, normals);
  31689. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31690. var vertexData = new VertexData();
  31691. vertexData.indices = indices;
  31692. vertexData.positions = positions;
  31693. vertexData.normals = normals;
  31694. vertexData.uvs = uvs;
  31695. return vertexData;
  31696. };
  31697. VertexData.CreateIcoSphere = function (options) {
  31698. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31699. var radius = options.radius || 1;
  31700. var flat = (options.flat === undefined) ? true : options.flat;
  31701. var subdivisions = options.subdivisions || 4;
  31702. var radiusX = options.radiusX || radius;
  31703. var radiusY = options.radiusY || radius;
  31704. var radiusZ = options.radiusZ || radius;
  31705. var t = (1 + Math.sqrt(5)) / 2;
  31706. // 12 vertex x,y,z
  31707. var ico_vertices = [
  31708. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  31709. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  31710. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  31711. ];
  31712. // index of 3 vertex makes a face of icopshere
  31713. var ico_indices = [
  31714. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  31715. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  31716. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  31717. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  31718. ];
  31719. // vertex for uv have aliased position, not for UV
  31720. var vertices_unalias_id = [
  31721. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  31722. // vertex alias
  31723. 0,
  31724. 2,
  31725. 3,
  31726. 3,
  31727. 3,
  31728. 4,
  31729. 7,
  31730. 8,
  31731. 9,
  31732. 9,
  31733. 10,
  31734. 11 // 23: B + 12
  31735. ];
  31736. // uv as integer step (not pixels !)
  31737. var ico_vertexuv = [
  31738. 5, 1, 3, 1, 6, 4, 0, 0,
  31739. 5, 3, 4, 2, 2, 2, 4, 0,
  31740. 2, 0, 1, 1, 6, 0, 6, 2,
  31741. // vertex alias (for same vertex on different faces)
  31742. 0, 4,
  31743. 3, 3,
  31744. 4, 4,
  31745. 3, 1,
  31746. 4, 2,
  31747. 4, 4,
  31748. 0, 2,
  31749. 1, 1,
  31750. 2, 2,
  31751. 3, 3,
  31752. 1, 3,
  31753. 2, 4 // 23: B + 12
  31754. ];
  31755. // Vertices[0, 1, ...9, A, B] : position on UV plane
  31756. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  31757. // First island of uv mapping
  31758. // v = 4h 3+ 2
  31759. // v = 3h 9+ 4
  31760. // v = 2h 9+ 5 B
  31761. // v = 1h 9 1 0
  31762. // v = 0h 3 8 7 A
  31763. // u = 0 1 2 3 4 5 6 *a
  31764. // Second island of uv mapping
  31765. // v = 4h 0+ B+ 4+
  31766. // v = 3h A+ 2+
  31767. // v = 2h 7+ 6 3+
  31768. // v = 1h 8+ 3+
  31769. // v = 0h
  31770. // u = 0 1 2 3 4 5 6 *a
  31771. // Face layout on texture UV mapping
  31772. // ============
  31773. // \ 4 /\ 16 / ======
  31774. // \ / \ / /\ 11 /
  31775. // \/ 7 \/ / \ /
  31776. // ======= / 10 \/
  31777. // /\ 17 /\ =======
  31778. // / \ / \ \ 15 /\
  31779. // / 8 \/ 12 \ \ / \
  31780. // ============ \/ 6 \
  31781. // \ 18 /\ ============
  31782. // \ / \ \ 5 /\ 0 /
  31783. // \/ 13 \ \ / \ /
  31784. // ======= \/ 1 \/
  31785. // =============
  31786. // /\ 19 /\ 2 /\
  31787. // / \ / \ / \
  31788. // / 14 \/ 9 \/ 3 \
  31789. // ===================
  31790. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  31791. var ustep = 138 / 1024;
  31792. var vstep = 239 / 1024;
  31793. var uoffset = 60 / 1024;
  31794. var voffset = 26 / 1024;
  31795. // Second island should have margin, not to touch the first island
  31796. // avoid any borderline artefact in pixel rounding
  31797. var island_u_offset = -40 / 1024;
  31798. var island_v_offset = +20 / 1024;
  31799. // face is either island 0 or 1 :
  31800. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  31801. var island = [
  31802. 0, 0, 0, 0, 1,
  31803. 0, 0, 1, 1, 0,
  31804. 0, 0, 1, 1, 0,
  31805. 0, 1, 1, 1, 0 // 15 - 19
  31806. ];
  31807. var indices = [];
  31808. var positions = [];
  31809. var normals = [];
  31810. var uvs = [];
  31811. var current_indice = 0;
  31812. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  31813. var face_vertex_pos = new Array(3);
  31814. var face_vertex_uv = new Array(3);
  31815. var v012;
  31816. for (v012 = 0; v012 < 3; v012++) {
  31817. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  31818. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  31819. }
  31820. // create all with normals
  31821. for (var face = 0; face < 20; face++) {
  31822. // 3 vertex per face
  31823. for (v012 = 0; v012 < 3; v012++) {
  31824. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  31825. var v_id = ico_indices[3 * face + v012];
  31826. // vertex have 3D position (x,y,z)
  31827. 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]);
  31828. // Normalize to get normal, then scale to radius
  31829. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  31830. // uv Coordinates from vertex ID
  31831. 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);
  31832. }
  31833. // Subdivide the face (interpolate pos, norm, uv)
  31834. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  31835. // - norm is linear interpolation of vertex corner normal
  31836. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  31837. // - uv is linear interpolation
  31838. //
  31839. // Topology is as below for sub-divide by 2
  31840. // vertex shown as v0,v1,v2
  31841. // interp index is i1 to progress in range [v0,v1[
  31842. // interp index is i2 to progress in range [v0,v2[
  31843. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  31844. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31845. //
  31846. //
  31847. // i2 v2
  31848. // ^ ^
  31849. // / / \
  31850. // / / \
  31851. // / / \
  31852. // / / (0,1) \
  31853. // / #---------\
  31854. // / / \ (0,0)'/ \
  31855. // / / \ / \
  31856. // / / \ / \
  31857. // / / (0,0) \ / (1,0) \
  31858. // / #---------#---------\
  31859. // v0 v1
  31860. //
  31861. // --------------------> i1
  31862. //
  31863. // interp of (i1,i2):
  31864. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  31865. // along i1 : lerp(x0,x1, i1/(S-i2))
  31866. //
  31867. // centroid of triangle is needed to get help normal computation
  31868. // (c1,c2) are used for centroid location
  31869. var interp_vertex = function (i1, i2, c1, c2) {
  31870. // vertex is interpolated from
  31871. // - face_vertex_pos[0..2]
  31872. // - face_vertex_uv[0..2]
  31873. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  31874. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  31875. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  31876. pos_interp.normalize();
  31877. var vertex_normal;
  31878. if (flat) {
  31879. // in flat mode, recalculate normal as face centroid normal
  31880. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  31881. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  31882. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  31883. }
  31884. else {
  31885. // in smooth mode, recalculate normal from each single vertex position
  31886. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  31887. }
  31888. // Vertex normal need correction due to X,Y,Z radius scaling
  31889. vertex_normal.x /= radiusX;
  31890. vertex_normal.y /= radiusY;
  31891. vertex_normal.z /= radiusZ;
  31892. vertex_normal.normalize();
  31893. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  31894. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  31895. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  31896. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  31897. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  31898. uvs.push(uv_interp.x, uv_interp.y);
  31899. // push each vertex has member of a face
  31900. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  31901. indices.push(current_indice);
  31902. current_indice++;
  31903. };
  31904. for (var i2 = 0; i2 < subdivisions; i2++) {
  31905. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  31906. // face : (i1,i2) for /\ :
  31907. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  31908. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31909. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31910. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31911. if (i1 + i2 + 1 < subdivisions) {
  31912. // face : (i1,i2)' for \/ :
  31913. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31914. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31915. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31916. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31917. }
  31918. }
  31919. }
  31920. }
  31921. // Sides
  31922. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31923. // Result
  31924. var vertexData = new VertexData();
  31925. vertexData.indices = indices;
  31926. vertexData.positions = positions;
  31927. vertexData.normals = normals;
  31928. vertexData.uvs = uvs;
  31929. return vertexData;
  31930. };
  31931. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  31932. VertexData.CreatePolyhedron = function (options) {
  31933. // provided polyhedron types :
  31934. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  31935. // 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)
  31936. var polyhedra = [];
  31937. 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]] };
  31938. 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]] };
  31939. polyhedra[2] = {
  31940. 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]],
  31941. 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]]
  31942. };
  31943. polyhedra[3] = {
  31944. 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]],
  31945. 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]]
  31946. };
  31947. polyhedra[4] = {
  31948. 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]],
  31949. 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]]
  31950. };
  31951. 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]] };
  31952. 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]] };
  31953. 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]] };
  31954. 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]] };
  31955. 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]] };
  31956. 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]] };
  31957. 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]] };
  31958. 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]] };
  31959. 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]] };
  31960. polyhedra[14] = {
  31961. 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]],
  31962. 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]]
  31963. };
  31964. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  31965. var size = options.size;
  31966. var sizeX = options.sizeX || size || 1;
  31967. var sizeY = options.sizeY || size || 1;
  31968. var sizeZ = options.sizeZ || size || 1;
  31969. var data = options.custom || polyhedra[type];
  31970. var nbfaces = data.face.length;
  31971. var faceUV = options.faceUV || new Array(nbfaces);
  31972. var faceColors = options.faceColors;
  31973. var flat = (options.flat === undefined) ? true : options.flat;
  31974. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31975. var positions = [];
  31976. var indices = [];
  31977. var normals = [];
  31978. var uvs = [];
  31979. var colors = [];
  31980. var index = 0;
  31981. var faceIdx = 0; // face cursor in the array "indexes"
  31982. var indexes = [];
  31983. var i = 0;
  31984. var f = 0;
  31985. var u, v, ang, x, y, tmp;
  31986. // default face colors and UV if undefined
  31987. if (flat) {
  31988. for (f = 0; f < nbfaces; f++) {
  31989. if (faceColors && faceColors[f] === undefined) {
  31990. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31991. }
  31992. if (faceUV && faceUV[f] === undefined) {
  31993. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31994. }
  31995. }
  31996. }
  31997. if (!flat) {
  31998. for (i = 0; i < data.vertex.length; i++) {
  31999. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  32000. uvs.push(0, 0);
  32001. }
  32002. for (f = 0; f < nbfaces; f++) {
  32003. for (i = 0; i < data.face[f].length - 2; i++) {
  32004. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  32005. }
  32006. }
  32007. }
  32008. else {
  32009. for (f = 0; f < nbfaces; f++) {
  32010. var fl = data.face[f].length; // number of vertices of the current face
  32011. ang = 2 * Math.PI / fl;
  32012. x = 0.5 * Math.tan(ang / 2);
  32013. y = 0.5;
  32014. // positions, uvs, colors
  32015. for (i = 0; i < fl; i++) {
  32016. // positions
  32017. 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);
  32018. indexes.push(index);
  32019. index++;
  32020. // uvs
  32021. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  32022. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  32023. uvs.push(u, v);
  32024. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  32025. y = x * Math.sin(ang) + y * Math.cos(ang);
  32026. x = tmp;
  32027. // colors
  32028. if (faceColors) {
  32029. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  32030. }
  32031. }
  32032. // indices from indexes
  32033. for (i = 0; i < fl - 2; i++) {
  32034. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  32035. }
  32036. faceIdx += fl;
  32037. }
  32038. }
  32039. VertexData.ComputeNormals(positions, indices, normals);
  32040. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32041. var vertexData = new VertexData();
  32042. vertexData.positions = positions;
  32043. vertexData.indices = indices;
  32044. vertexData.normals = normals;
  32045. vertexData.uvs = uvs;
  32046. if (faceColors && flat) {
  32047. vertexData.colors = colors;
  32048. }
  32049. return vertexData;
  32050. };
  32051. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  32052. VertexData.CreateTorusKnot = function (options) {
  32053. var indices = [];
  32054. var positions = [];
  32055. var normals = [];
  32056. var uvs = [];
  32057. var radius = options.radius || 2;
  32058. var tube = options.tube || 0.5;
  32059. var radialSegments = options.radialSegments || 32;
  32060. var tubularSegments = options.tubularSegments || 32;
  32061. var p = options.p || 2;
  32062. var q = options.q || 3;
  32063. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32064. // Helper
  32065. var getPos = function (angle) {
  32066. var cu = Math.cos(angle);
  32067. var su = Math.sin(angle);
  32068. var quOverP = q / p * angle;
  32069. var cs = Math.cos(quOverP);
  32070. var tx = radius * (2 + cs) * 0.5 * cu;
  32071. var ty = radius * (2 + cs) * su * 0.5;
  32072. var tz = radius * Math.sin(quOverP) * 0.5;
  32073. return new BABYLON.Vector3(tx, ty, tz);
  32074. };
  32075. // Vertices
  32076. var i;
  32077. var j;
  32078. for (i = 0; i <= radialSegments; i++) {
  32079. var modI = i % radialSegments;
  32080. var u = modI / radialSegments * 2 * p * Math.PI;
  32081. var p1 = getPos(u);
  32082. var p2 = getPos(u + 0.01);
  32083. var tang = p2.subtract(p1);
  32084. var n = p2.add(p1);
  32085. var bitan = BABYLON.Vector3.Cross(tang, n);
  32086. n = BABYLON.Vector3.Cross(bitan, tang);
  32087. bitan.normalize();
  32088. n.normalize();
  32089. for (j = 0; j < tubularSegments; j++) {
  32090. var modJ = j % tubularSegments;
  32091. var v = modJ / tubularSegments * 2 * Math.PI;
  32092. var cx = -tube * Math.cos(v);
  32093. var cy = tube * Math.sin(v);
  32094. positions.push(p1.x + cx * n.x + cy * bitan.x);
  32095. positions.push(p1.y + cx * n.y + cy * bitan.y);
  32096. positions.push(p1.z + cx * n.z + cy * bitan.z);
  32097. uvs.push(i / radialSegments);
  32098. uvs.push(j / tubularSegments);
  32099. }
  32100. }
  32101. for (i = 0; i < radialSegments; i++) {
  32102. for (j = 0; j < tubularSegments; j++) {
  32103. var jNext = (j + 1) % tubularSegments;
  32104. var a = i * tubularSegments + j;
  32105. var b = (i + 1) * tubularSegments + j;
  32106. var c = (i + 1) * tubularSegments + jNext;
  32107. var d = i * tubularSegments + jNext;
  32108. indices.push(d);
  32109. indices.push(b);
  32110. indices.push(a);
  32111. indices.push(d);
  32112. indices.push(c);
  32113. indices.push(b);
  32114. }
  32115. }
  32116. // Normals
  32117. VertexData.ComputeNormals(positions, indices, normals);
  32118. // Sides
  32119. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32120. // Result
  32121. var vertexData = new VertexData();
  32122. vertexData.indices = indices;
  32123. vertexData.positions = positions;
  32124. vertexData.normals = normals;
  32125. vertexData.uvs = uvs;
  32126. return vertexData;
  32127. };
  32128. // Tools
  32129. /**
  32130. * @param {any} - positions (number[] or Float32Array)
  32131. * @param {any} - indices (number[] or Uint16Array)
  32132. * @param {any} - normals (number[] or Float32Array)
  32133. */
  32134. VertexData.ComputeNormals = function (positions, indices, normals) {
  32135. var index = 0;
  32136. var p1p2x = 0.0;
  32137. var p1p2y = 0.0;
  32138. var p1p2z = 0.0;
  32139. var p3p2x = 0.0;
  32140. var p3p2y = 0.0;
  32141. var p3p2z = 0.0;
  32142. var faceNormalx = 0.0;
  32143. var faceNormaly = 0.0;
  32144. var faceNormalz = 0.0;
  32145. var length = 0.0;
  32146. var i1 = 0;
  32147. var i2 = 0;
  32148. var i3 = 0;
  32149. for (index = 0; index < positions.length; index++) {
  32150. normals[index] = 0.0;
  32151. }
  32152. // indice triplet = 1 face
  32153. var nbFaces = indices.length / 3;
  32154. for (index = 0; index < nbFaces; index++) {
  32155. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  32156. i2 = indices[index * 3 + 1];
  32157. i3 = indices[index * 3 + 2];
  32158. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  32159. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  32160. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  32161. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  32162. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  32163. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  32164. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  32165. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  32166. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  32167. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32168. length = (length === 0) ? 1.0 : length;
  32169. faceNormalx /= length; // normalize this normal
  32170. faceNormaly /= length;
  32171. faceNormalz /= length;
  32172. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  32173. normals[i1 * 3 + 1] += faceNormaly;
  32174. normals[i1 * 3 + 2] += faceNormalz;
  32175. normals[i2 * 3] += faceNormalx;
  32176. normals[i2 * 3 + 1] += faceNormaly;
  32177. normals[i2 * 3 + 2] += faceNormalz;
  32178. normals[i3 * 3] += faceNormalx;
  32179. normals[i3 * 3 + 1] += faceNormaly;
  32180. normals[i3 * 3 + 2] += faceNormalz;
  32181. }
  32182. // last normalization of each normal
  32183. for (index = 0; index < normals.length / 3; index++) {
  32184. faceNormalx = normals[index * 3];
  32185. faceNormaly = normals[index * 3 + 1];
  32186. faceNormalz = normals[index * 3 + 2];
  32187. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32188. length = (length === 0) ? 1.0 : length;
  32189. faceNormalx /= length;
  32190. faceNormaly /= length;
  32191. faceNormalz /= length;
  32192. normals[index * 3] = faceNormalx;
  32193. normals[index * 3 + 1] = faceNormaly;
  32194. normals[index * 3 + 2] = faceNormalz;
  32195. }
  32196. };
  32197. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  32198. var li = indices.length;
  32199. var ln = normals.length;
  32200. var i;
  32201. var n;
  32202. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32203. switch (sideOrientation) {
  32204. case BABYLON.Mesh.FRONTSIDE:
  32205. // nothing changed
  32206. break;
  32207. case BABYLON.Mesh.BACKSIDE:
  32208. var tmp;
  32209. // indices
  32210. for (i = 0; i < li; i += 3) {
  32211. tmp = indices[i];
  32212. indices[i] = indices[i + 2];
  32213. indices[i + 2] = tmp;
  32214. }
  32215. // normals
  32216. for (n = 0; n < ln; n++) {
  32217. normals[n] = -normals[n];
  32218. }
  32219. break;
  32220. case BABYLON.Mesh.DOUBLESIDE:
  32221. // positions
  32222. var lp = positions.length;
  32223. var l = lp / 3;
  32224. for (var p = 0; p < lp; p++) {
  32225. positions[lp + p] = positions[p];
  32226. }
  32227. // indices
  32228. for (i = 0; i < li; i += 3) {
  32229. indices[i + li] = indices[i + 2] + l;
  32230. indices[i + 1 + li] = indices[i + 1] + l;
  32231. indices[i + 2 + li] = indices[i] + l;
  32232. }
  32233. // normals
  32234. for (n = 0; n < ln; n++) {
  32235. normals[ln + n] = -normals[n];
  32236. }
  32237. // uvs
  32238. var lu = uvs.length;
  32239. for (var u = 0; u < lu; u++) {
  32240. uvs[u + lu] = uvs[u];
  32241. }
  32242. break;
  32243. }
  32244. };
  32245. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  32246. var vertexData = new VertexData();
  32247. // positions
  32248. var positions = parsedVertexData.positions;
  32249. if (positions) {
  32250. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  32251. }
  32252. // normals
  32253. var normals = parsedVertexData.normals;
  32254. if (normals) {
  32255. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  32256. }
  32257. // uvs
  32258. var uvs = parsedVertexData.uvs;
  32259. if (uvs) {
  32260. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  32261. }
  32262. // uv2s
  32263. var uv2s = parsedVertexData.uv2s;
  32264. if (uv2s) {
  32265. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  32266. }
  32267. // uv3s
  32268. var uv3s = parsedVertexData.uv3s;
  32269. if (uv3s) {
  32270. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  32271. }
  32272. // uv4s
  32273. var uv4s = parsedVertexData.uv4s;
  32274. if (uv4s) {
  32275. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  32276. }
  32277. // uv5s
  32278. var uv5s = parsedVertexData.uv5s;
  32279. if (uv5s) {
  32280. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  32281. }
  32282. // uv6s
  32283. var uv6s = parsedVertexData.uv6s;
  32284. if (uv6s) {
  32285. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  32286. }
  32287. // colors
  32288. var colors = parsedVertexData.colors;
  32289. if (colors) {
  32290. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  32291. }
  32292. // matricesIndices
  32293. var matricesIndices = parsedVertexData.matricesIndices;
  32294. if (matricesIndices) {
  32295. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  32296. }
  32297. // matricesWeights
  32298. var matricesWeights = parsedVertexData.matricesWeights;
  32299. if (matricesWeights) {
  32300. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  32301. }
  32302. // indices
  32303. var indices = parsedVertexData.indices;
  32304. if (indices) {
  32305. vertexData.indices = indices;
  32306. }
  32307. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  32308. };
  32309. return VertexData;
  32310. })();
  32311. BABYLON.VertexData = VertexData;
  32312. })(BABYLON || (BABYLON = {}));
  32313. var BABYLON;
  32314. (function (BABYLON) {
  32315. var Tags = (function () {
  32316. function Tags() {
  32317. }
  32318. Tags.EnableFor = function (obj) {
  32319. obj._tags = obj._tags || {};
  32320. obj.hasTags = function () {
  32321. return Tags.HasTags(obj);
  32322. };
  32323. obj.addTags = function (tagsString) {
  32324. return Tags.AddTagsTo(obj, tagsString);
  32325. };
  32326. obj.removeTags = function (tagsString) {
  32327. return Tags.RemoveTagsFrom(obj, tagsString);
  32328. };
  32329. obj.matchesTagsQuery = function (tagsQuery) {
  32330. return Tags.MatchesQuery(obj, tagsQuery);
  32331. };
  32332. };
  32333. Tags.DisableFor = function (obj) {
  32334. delete obj._tags;
  32335. delete obj.hasTags;
  32336. delete obj.addTags;
  32337. delete obj.removeTags;
  32338. delete obj.matchesTagsQuery;
  32339. };
  32340. Tags.HasTags = function (obj) {
  32341. if (!obj._tags) {
  32342. return false;
  32343. }
  32344. return !BABYLON.Tools.IsEmpty(obj._tags);
  32345. };
  32346. Tags.GetTags = function (obj, asString) {
  32347. if (asString === void 0) { asString = true; }
  32348. if (!obj._tags) {
  32349. return null;
  32350. }
  32351. if (asString) {
  32352. var tagsArray = [];
  32353. for (var tag in obj._tags) {
  32354. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  32355. tagsArray.push(tag);
  32356. }
  32357. }
  32358. return tagsArray.join(" ");
  32359. }
  32360. else {
  32361. return obj._tags;
  32362. }
  32363. };
  32364. // the tags 'true' and 'false' are reserved and cannot be used as tags
  32365. // a tag cannot start with '||', '&&', and '!'
  32366. // it cannot contain whitespaces
  32367. Tags.AddTagsTo = function (obj, tagsString) {
  32368. if (!tagsString) {
  32369. return;
  32370. }
  32371. if (typeof tagsString !== "string") {
  32372. return;
  32373. }
  32374. var tags = tagsString.split(" ");
  32375. for (var t in tags) {
  32376. Tags._AddTagTo(obj, tags[t]);
  32377. }
  32378. };
  32379. Tags._AddTagTo = function (obj, tag) {
  32380. tag = tag.trim();
  32381. if (tag === "" || tag === "true" || tag === "false") {
  32382. return;
  32383. }
  32384. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  32385. return;
  32386. }
  32387. Tags.EnableFor(obj);
  32388. obj._tags[tag] = true;
  32389. };
  32390. Tags.RemoveTagsFrom = function (obj, tagsString) {
  32391. if (!Tags.HasTags(obj)) {
  32392. return;
  32393. }
  32394. var tags = tagsString.split(" ");
  32395. for (var t in tags) {
  32396. Tags._RemoveTagFrom(obj, tags[t]);
  32397. }
  32398. };
  32399. Tags._RemoveTagFrom = function (obj, tag) {
  32400. delete obj._tags[tag];
  32401. };
  32402. Tags.MatchesQuery = function (obj, tagsQuery) {
  32403. if (tagsQuery === undefined) {
  32404. return true;
  32405. }
  32406. if (tagsQuery === "") {
  32407. return Tags.HasTags(obj);
  32408. }
  32409. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  32410. };
  32411. return Tags;
  32412. })();
  32413. BABYLON.Tags = Tags;
  32414. })(BABYLON || (BABYLON = {}));
  32415. var BABYLON;
  32416. (function (BABYLON) {
  32417. var Internals;
  32418. (function (Internals) {
  32419. var AndOrNotEvaluator = (function () {
  32420. function AndOrNotEvaluator() {
  32421. }
  32422. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  32423. if (!query.match(/\([^\(\)]*\)/g)) {
  32424. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  32425. }
  32426. else {
  32427. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  32428. // remove parenthesis
  32429. r = r.slice(1, r.length - 1);
  32430. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  32431. });
  32432. }
  32433. if (query === "true") {
  32434. return true;
  32435. }
  32436. if (query === "false") {
  32437. return false;
  32438. }
  32439. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  32440. };
  32441. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  32442. evaluateCallback = evaluateCallback || (function (r) {
  32443. return r === "true" ? true : false;
  32444. });
  32445. var result;
  32446. var or = parenthesisContent.split("||");
  32447. for (var i in or) {
  32448. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  32449. var and = ori.split("&&");
  32450. if (and.length > 1) {
  32451. for (var j = 0; j < and.length; ++j) {
  32452. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  32453. if (andj !== "true" && andj !== "false") {
  32454. if (andj[0] === "!") {
  32455. result = !evaluateCallback(andj.substring(1));
  32456. }
  32457. else {
  32458. result = evaluateCallback(andj);
  32459. }
  32460. }
  32461. else {
  32462. result = andj === "true" ? true : false;
  32463. }
  32464. if (!result) {
  32465. ori = "false";
  32466. break;
  32467. }
  32468. }
  32469. }
  32470. if (result || ori === "true") {
  32471. result = true;
  32472. break;
  32473. }
  32474. // result equals false (or undefined)
  32475. if (ori !== "true" && ori !== "false") {
  32476. if (ori[0] === "!") {
  32477. result = !evaluateCallback(ori.substring(1));
  32478. }
  32479. else {
  32480. result = evaluateCallback(ori);
  32481. }
  32482. }
  32483. else {
  32484. result = ori === "true" ? true : false;
  32485. }
  32486. }
  32487. // the whole parenthesis scope is replaced by 'true' or 'false'
  32488. return result ? "true" : "false";
  32489. };
  32490. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  32491. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  32492. // remove whitespaces
  32493. r = r.replace(/[\s]/g, function () { return ""; });
  32494. return r.length % 2 ? "!" : "";
  32495. });
  32496. booleanString = booleanString.trim();
  32497. if (booleanString === "!true") {
  32498. booleanString = "false";
  32499. }
  32500. else if (booleanString === "!false") {
  32501. booleanString = "true";
  32502. }
  32503. return booleanString;
  32504. };
  32505. return AndOrNotEvaluator;
  32506. })();
  32507. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  32508. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32509. })(BABYLON || (BABYLON = {}));
  32510. var BABYLON;
  32511. (function (BABYLON) {
  32512. var PostProcessRenderPass = (function () {
  32513. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  32514. this._enabled = true;
  32515. this._refCount = 0;
  32516. this._name = name;
  32517. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  32518. this.setRenderList(renderList);
  32519. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  32520. this._renderTexture.onAfterRenderObservable.add(afterRender);
  32521. this._scene = scene;
  32522. this._renderList = renderList;
  32523. }
  32524. // private
  32525. PostProcessRenderPass.prototype._incRefCount = function () {
  32526. if (this._refCount === 0) {
  32527. this._scene.customRenderTargets.push(this._renderTexture);
  32528. }
  32529. return ++this._refCount;
  32530. };
  32531. PostProcessRenderPass.prototype._decRefCount = function () {
  32532. this._refCount--;
  32533. if (this._refCount <= 0) {
  32534. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  32535. }
  32536. return this._refCount;
  32537. };
  32538. PostProcessRenderPass.prototype._update = function () {
  32539. this.setRenderList(this._renderList);
  32540. };
  32541. // public
  32542. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  32543. this._renderTexture.renderList = renderList;
  32544. };
  32545. PostProcessRenderPass.prototype.getRenderTexture = function () {
  32546. return this._renderTexture;
  32547. };
  32548. return PostProcessRenderPass;
  32549. })();
  32550. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  32551. })(BABYLON || (BABYLON = {}));
  32552. var BABYLON;
  32553. (function (BABYLON) {
  32554. var PostProcessRenderEffect = (function () {
  32555. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  32556. this._engine = engine;
  32557. this._name = name;
  32558. this._singleInstance = singleInstance || true;
  32559. this._getPostProcess = getPostProcess;
  32560. this._cameras = [];
  32561. this._indicesForCamera = [];
  32562. this._postProcesses = {};
  32563. this._renderPasses = {};
  32564. this._renderEffectAsPasses = {};
  32565. }
  32566. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  32567. get: function () {
  32568. for (var index in this._postProcesses) {
  32569. if (!this._postProcesses[index].isSupported) {
  32570. return false;
  32571. }
  32572. }
  32573. return true;
  32574. },
  32575. enumerable: true,
  32576. configurable: true
  32577. });
  32578. PostProcessRenderEffect.prototype._update = function () {
  32579. for (var renderPassName in this._renderPasses) {
  32580. this._renderPasses[renderPassName]._update();
  32581. }
  32582. };
  32583. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  32584. this._renderPasses[renderPass._name] = renderPass;
  32585. this._linkParameters();
  32586. };
  32587. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  32588. delete this._renderPasses[renderPass._name];
  32589. this._linkParameters();
  32590. };
  32591. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  32592. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  32593. this._linkParameters();
  32594. };
  32595. PostProcessRenderEffect.prototype.getPass = function (passName) {
  32596. for (var renderPassName in this._renderPasses) {
  32597. if (renderPassName === passName) {
  32598. return this._renderPasses[passName];
  32599. }
  32600. }
  32601. };
  32602. PostProcessRenderEffect.prototype.emptyPasses = function () {
  32603. this._renderPasses = {};
  32604. this._linkParameters();
  32605. };
  32606. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  32607. var cameraKey;
  32608. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32609. for (var i = 0; i < _cam.length; i++) {
  32610. var camera = _cam[i];
  32611. var cameraName = camera.name;
  32612. if (this._singleInstance) {
  32613. cameraKey = 0;
  32614. }
  32615. else {
  32616. cameraKey = cameraName;
  32617. }
  32618. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  32619. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  32620. if (!this._indicesForCamera[cameraName]) {
  32621. this._indicesForCamera[cameraName] = [];
  32622. }
  32623. this._indicesForCamera[cameraName].push(index);
  32624. if (this._cameras.indexOf(camera) === -1) {
  32625. this._cameras[cameraName] = camera;
  32626. }
  32627. for (var passName in this._renderPasses) {
  32628. this._renderPasses[passName]._incRefCount();
  32629. }
  32630. }
  32631. this._linkParameters();
  32632. };
  32633. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  32634. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32635. for (var i = 0; i < _cam.length; i++) {
  32636. var camera = _cam[i];
  32637. var cameraName = camera.name;
  32638. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  32639. var index = this._cameras.indexOf(cameraName);
  32640. this._indicesForCamera.splice(index, 1);
  32641. this._cameras.splice(index, 1);
  32642. for (var passName in this._renderPasses) {
  32643. this._renderPasses[passName]._decRefCount();
  32644. }
  32645. }
  32646. };
  32647. PostProcessRenderEffect.prototype._enable = function (cameras) {
  32648. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32649. for (var i = 0; i < _cam.length; i++) {
  32650. var camera = _cam[i];
  32651. var cameraName = camera.name;
  32652. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  32653. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  32654. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  32655. }
  32656. }
  32657. for (var passName in this._renderPasses) {
  32658. this._renderPasses[passName]._incRefCount();
  32659. }
  32660. }
  32661. };
  32662. PostProcessRenderEffect.prototype._disable = function (cameras) {
  32663. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32664. for (var i = 0; i < _cam.length; i++) {
  32665. var camera = _cam[i];
  32666. var cameraName = camera.Name;
  32667. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  32668. for (var passName in this._renderPasses) {
  32669. this._renderPasses[passName]._decRefCount();
  32670. }
  32671. }
  32672. };
  32673. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  32674. if (this._singleInstance) {
  32675. return this._postProcesses[0];
  32676. }
  32677. else {
  32678. return this._postProcesses[camera.name];
  32679. }
  32680. };
  32681. PostProcessRenderEffect.prototype._linkParameters = function () {
  32682. var _this = this;
  32683. for (var index in this._postProcesses) {
  32684. if (this.applyParameters) {
  32685. this.applyParameters(this._postProcesses[index]);
  32686. }
  32687. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  32688. _this._linkTextures(effect);
  32689. });
  32690. }
  32691. };
  32692. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  32693. for (var renderPassName in this._renderPasses) {
  32694. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  32695. }
  32696. for (var renderEffectName in this._renderEffectAsPasses) {
  32697. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  32698. }
  32699. };
  32700. return PostProcessRenderEffect;
  32701. })();
  32702. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  32703. })(BABYLON || (BABYLON = {}));
  32704. var BABYLON;
  32705. (function (BABYLON) {
  32706. var PostProcessRenderPipeline = (function () {
  32707. function PostProcessRenderPipeline(engine, name) {
  32708. this._engine = engine;
  32709. this._name = name;
  32710. this._renderEffects = {};
  32711. this._renderEffectsForIsolatedPass = {};
  32712. this._cameras = [];
  32713. }
  32714. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  32715. get: function () {
  32716. for (var renderEffectName in this._renderEffects) {
  32717. if (!this._renderEffects[renderEffectName].isSupported) {
  32718. return false;
  32719. }
  32720. }
  32721. return true;
  32722. },
  32723. enumerable: true,
  32724. configurable: true
  32725. });
  32726. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  32727. this._renderEffects[renderEffect._name] = renderEffect;
  32728. };
  32729. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  32730. var renderEffects = this._renderEffects[renderEffectName];
  32731. if (!renderEffects) {
  32732. return;
  32733. }
  32734. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  32735. };
  32736. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  32737. var renderEffects = this._renderEffects[renderEffectName];
  32738. if (!renderEffects) {
  32739. return;
  32740. }
  32741. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  32742. };
  32743. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  32744. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32745. var indicesToDelete = [];
  32746. var i;
  32747. for (i = 0; i < _cam.length; i++) {
  32748. var camera = _cam[i];
  32749. var cameraName = camera.name;
  32750. if (this._cameras.indexOf(camera) === -1) {
  32751. this._cameras[cameraName] = camera;
  32752. }
  32753. else if (unique) {
  32754. indicesToDelete.push(i);
  32755. }
  32756. }
  32757. for (i = 0; i < indicesToDelete.length; i++) {
  32758. cameras.splice(indicesToDelete[i], 1);
  32759. }
  32760. for (var renderEffectName in this._renderEffects) {
  32761. this._renderEffects[renderEffectName]._attachCameras(_cam);
  32762. }
  32763. };
  32764. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  32765. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32766. for (var renderEffectName in this._renderEffects) {
  32767. this._renderEffects[renderEffectName]._detachCameras(_cam);
  32768. }
  32769. for (var i = 0; i < _cam.length; i++) {
  32770. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  32771. }
  32772. };
  32773. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  32774. var _this = this;
  32775. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32776. var pass = null;
  32777. var renderEffectName;
  32778. for (renderEffectName in this._renderEffects) {
  32779. pass = this._renderEffects[renderEffectName].getPass(passName);
  32780. if (pass != null) {
  32781. break;
  32782. }
  32783. }
  32784. if (pass === null) {
  32785. return;
  32786. }
  32787. for (renderEffectName in this._renderEffects) {
  32788. this._renderEffects[renderEffectName]._disable(_cam);
  32789. }
  32790. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  32791. for (var i = 0; i < _cam.length; i++) {
  32792. var camera = _cam[i];
  32793. var cameraName = camera.name;
  32794. 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); });
  32795. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  32796. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  32797. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  32798. }
  32799. };
  32800. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  32801. var _this = this;
  32802. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32803. for (var i = 0; i < _cam.length; i++) {
  32804. var camera = _cam[i];
  32805. var cameraName = camera.name;
  32806. 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); });
  32807. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  32808. }
  32809. for (var renderEffectName in this._renderEffects) {
  32810. this._renderEffects[renderEffectName]._enable(_cam);
  32811. }
  32812. };
  32813. PostProcessRenderPipeline.prototype._update = function () {
  32814. for (var renderEffectName in this._renderEffects) {
  32815. this._renderEffects[renderEffectName]._update();
  32816. }
  32817. for (var i = 0; i < this._cameras.length; i++) {
  32818. var cameraName = this._cameras[i].name;
  32819. if (this._renderEffectsForIsolatedPass[cameraName]) {
  32820. this._renderEffectsForIsolatedPass[cameraName]._update();
  32821. }
  32822. }
  32823. };
  32824. PostProcessRenderPipeline.prototype.dispose = function () {
  32825. // Must be implemented by children
  32826. };
  32827. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  32828. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  32829. return PostProcessRenderPipeline;
  32830. })();
  32831. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  32832. })(BABYLON || (BABYLON = {}));
  32833. var BABYLON;
  32834. (function (BABYLON) {
  32835. var PostProcessRenderPipelineManager = (function () {
  32836. function PostProcessRenderPipelineManager() {
  32837. this._renderPipelines = {};
  32838. }
  32839. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  32840. this._renderPipelines[renderPipeline._name] = renderPipeline;
  32841. };
  32842. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  32843. var renderPipeline = this._renderPipelines[renderPipelineName];
  32844. if (!renderPipeline) {
  32845. return;
  32846. }
  32847. renderPipeline._attachCameras(cameras, unique);
  32848. };
  32849. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  32850. var renderPipeline = this._renderPipelines[renderPipelineName];
  32851. if (!renderPipeline) {
  32852. return;
  32853. }
  32854. renderPipeline._detachCameras(cameras);
  32855. };
  32856. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  32857. var renderPipeline = this._renderPipelines[renderPipelineName];
  32858. if (!renderPipeline) {
  32859. return;
  32860. }
  32861. renderPipeline._enableEffect(renderEffectName, cameras);
  32862. };
  32863. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  32864. var renderPipeline = this._renderPipelines[renderPipelineName];
  32865. if (!renderPipeline) {
  32866. return;
  32867. }
  32868. renderPipeline._disableEffect(renderEffectName, cameras);
  32869. };
  32870. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  32871. var renderPipeline = this._renderPipelines[renderPipelineName];
  32872. if (!renderPipeline) {
  32873. return;
  32874. }
  32875. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  32876. };
  32877. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  32878. var renderPipeline = this._renderPipelines[renderPipelineName];
  32879. if (!renderPipeline) {
  32880. return;
  32881. }
  32882. renderPipeline._disableDisplayOnlyPass(cameras);
  32883. };
  32884. PostProcessRenderPipelineManager.prototype.update = function () {
  32885. for (var renderPipelineName in this._renderPipelines) {
  32886. var pipeline = this._renderPipelines[renderPipelineName];
  32887. if (!pipeline.isSupported) {
  32888. pipeline.dispose();
  32889. delete this._renderPipelines[renderPipelineName];
  32890. }
  32891. else {
  32892. pipeline._update();
  32893. }
  32894. }
  32895. };
  32896. return PostProcessRenderPipelineManager;
  32897. })();
  32898. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  32899. })(BABYLON || (BABYLON = {}));
  32900. var BABYLON;
  32901. (function (BABYLON) {
  32902. var BoundingBoxRenderer = (function () {
  32903. function BoundingBoxRenderer(scene) {
  32904. this.frontColor = new BABYLON.Color3(1, 1, 1);
  32905. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  32906. this.showBackLines = true;
  32907. this.renderList = new BABYLON.SmartArray(32);
  32908. this._vertexBuffers = {};
  32909. this._scene = scene;
  32910. }
  32911. BoundingBoxRenderer.prototype._prepareRessources = function () {
  32912. if (this._colorShader) {
  32913. return;
  32914. }
  32915. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  32916. attributes: [BABYLON.VertexBuffer.PositionKind],
  32917. uniforms: ["worldViewProjection", "color"]
  32918. });
  32919. var engine = this._scene.getEngine();
  32920. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  32921. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  32922. 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]);
  32923. };
  32924. BoundingBoxRenderer.prototype.reset = function () {
  32925. this.renderList.reset();
  32926. };
  32927. BoundingBoxRenderer.prototype.render = function () {
  32928. if (this.renderList.length === 0) {
  32929. return;
  32930. }
  32931. this._prepareRessources();
  32932. if (!this._colorShader.isReady()) {
  32933. return;
  32934. }
  32935. var engine = this._scene.getEngine();
  32936. engine.setDepthWrite(false);
  32937. this._colorShader._preBind();
  32938. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  32939. var boundingBox = this.renderList.data[boundingBoxIndex];
  32940. var min = boundingBox.minimum;
  32941. var max = boundingBox.maximum;
  32942. var diff = max.subtract(min);
  32943. var median = min.add(diff.scale(0.5));
  32944. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  32945. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  32946. .multiply(boundingBox.getWorldMatrix());
  32947. // VBOs
  32948. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  32949. if (this.showBackLines) {
  32950. // Back
  32951. engine.setDepthFunctionToGreaterOrEqual();
  32952. this._scene.resetCachedMaterial();
  32953. this._colorShader.setColor4("color", this.backColor.toColor4());
  32954. this._colorShader.bind(worldMatrix);
  32955. // Draw order
  32956. engine.draw(false, 0, 24);
  32957. }
  32958. // Front
  32959. engine.setDepthFunctionToLess();
  32960. this._scene.resetCachedMaterial();
  32961. this._colorShader.setColor4("color", this.frontColor.toColor4());
  32962. this._colorShader.bind(worldMatrix);
  32963. // Draw order
  32964. engine.draw(false, 0, 24);
  32965. }
  32966. this._colorShader.unbind();
  32967. engine.setDepthFunctionToLessOrEqual();
  32968. engine.setDepthWrite(true);
  32969. };
  32970. BoundingBoxRenderer.prototype.dispose = function () {
  32971. if (!this._colorShader) {
  32972. return;
  32973. }
  32974. this._colorShader.dispose();
  32975. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32976. if (buffer) {
  32977. buffer.dispose();
  32978. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32979. }
  32980. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32981. };
  32982. return BoundingBoxRenderer;
  32983. })();
  32984. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  32985. })(BABYLON || (BABYLON = {}));
  32986. var BABYLON;
  32987. (function (BABYLON) {
  32988. var Condition = (function () {
  32989. function Condition(actionManager) {
  32990. this._actionManager = actionManager;
  32991. }
  32992. Condition.prototype.isValid = function () {
  32993. return true;
  32994. };
  32995. Condition.prototype._getProperty = function (propertyPath) {
  32996. return this._actionManager._getProperty(propertyPath);
  32997. };
  32998. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  32999. return this._actionManager._getEffectiveTarget(target, propertyPath);
  33000. };
  33001. Condition.prototype.serialize = function () {
  33002. };
  33003. Condition.prototype._serialize = function (serializedCondition) {
  33004. return {
  33005. type: 2,
  33006. children: [],
  33007. name: serializedCondition.name,
  33008. properties: serializedCondition.properties
  33009. };
  33010. };
  33011. return Condition;
  33012. })();
  33013. BABYLON.Condition = Condition;
  33014. var ValueCondition = (function (_super) {
  33015. __extends(ValueCondition, _super);
  33016. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  33017. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  33018. _super.call(this, actionManager);
  33019. this.propertyPath = propertyPath;
  33020. this.value = value;
  33021. this.operator = operator;
  33022. this._target = target;
  33023. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  33024. this._property = this._getProperty(this.propertyPath);
  33025. }
  33026. Object.defineProperty(ValueCondition, "IsEqual", {
  33027. get: function () {
  33028. return ValueCondition._IsEqual;
  33029. },
  33030. enumerable: true,
  33031. configurable: true
  33032. });
  33033. Object.defineProperty(ValueCondition, "IsDifferent", {
  33034. get: function () {
  33035. return ValueCondition._IsDifferent;
  33036. },
  33037. enumerable: true,
  33038. configurable: true
  33039. });
  33040. Object.defineProperty(ValueCondition, "IsGreater", {
  33041. get: function () {
  33042. return ValueCondition._IsGreater;
  33043. },
  33044. enumerable: true,
  33045. configurable: true
  33046. });
  33047. Object.defineProperty(ValueCondition, "IsLesser", {
  33048. get: function () {
  33049. return ValueCondition._IsLesser;
  33050. },
  33051. enumerable: true,
  33052. configurable: true
  33053. });
  33054. // Methods
  33055. ValueCondition.prototype.isValid = function () {
  33056. switch (this.operator) {
  33057. case ValueCondition.IsGreater:
  33058. return this._effectiveTarget[this._property] > this.value;
  33059. case ValueCondition.IsLesser:
  33060. return this._effectiveTarget[this._property] < this.value;
  33061. case ValueCondition.IsEqual:
  33062. case ValueCondition.IsDifferent:
  33063. var check;
  33064. if (this.value.equals) {
  33065. check = this.value.equals(this._effectiveTarget[this._property]);
  33066. }
  33067. else {
  33068. check = this.value === this._effectiveTarget[this._property];
  33069. }
  33070. return this.operator === ValueCondition.IsEqual ? check : !check;
  33071. }
  33072. return false;
  33073. };
  33074. ValueCondition.prototype.serialize = function () {
  33075. return this._serialize({
  33076. name: "ValueCondition",
  33077. properties: [
  33078. BABYLON.Action._GetTargetProperty(this._target),
  33079. { name: "propertyPath", value: this.propertyPath },
  33080. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  33081. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  33082. ]
  33083. });
  33084. };
  33085. ValueCondition.GetOperatorName = function (operator) {
  33086. switch (operator) {
  33087. case ValueCondition._IsEqual: return "IsEqual";
  33088. case ValueCondition._IsDifferent: return "IsDifferent";
  33089. case ValueCondition._IsGreater: return "IsGreater";
  33090. case ValueCondition._IsLesser: return "IsLesser";
  33091. default: return "";
  33092. }
  33093. };
  33094. // Statics
  33095. ValueCondition._IsEqual = 0;
  33096. ValueCondition._IsDifferent = 1;
  33097. ValueCondition._IsGreater = 2;
  33098. ValueCondition._IsLesser = 3;
  33099. return ValueCondition;
  33100. })(Condition);
  33101. BABYLON.ValueCondition = ValueCondition;
  33102. var PredicateCondition = (function (_super) {
  33103. __extends(PredicateCondition, _super);
  33104. function PredicateCondition(actionManager, predicate) {
  33105. _super.call(this, actionManager);
  33106. this.predicate = predicate;
  33107. }
  33108. PredicateCondition.prototype.isValid = function () {
  33109. return this.predicate();
  33110. };
  33111. return PredicateCondition;
  33112. })(Condition);
  33113. BABYLON.PredicateCondition = PredicateCondition;
  33114. var StateCondition = (function (_super) {
  33115. __extends(StateCondition, _super);
  33116. function StateCondition(actionManager, target, value) {
  33117. _super.call(this, actionManager);
  33118. this.value = value;
  33119. this._target = target;
  33120. }
  33121. // Methods
  33122. StateCondition.prototype.isValid = function () {
  33123. return this._target.state === this.value;
  33124. };
  33125. StateCondition.prototype.serialize = function () {
  33126. return this._serialize({
  33127. name: "StateCondition",
  33128. properties: [
  33129. BABYLON.Action._GetTargetProperty(this._target),
  33130. { name: "value", value: this.value }
  33131. ]
  33132. });
  33133. };
  33134. return StateCondition;
  33135. })(Condition);
  33136. BABYLON.StateCondition = StateCondition;
  33137. })(BABYLON || (BABYLON = {}));
  33138. var BABYLON;
  33139. (function (BABYLON) {
  33140. var Action = (function () {
  33141. function Action(triggerOptions, condition) {
  33142. this.triggerOptions = triggerOptions;
  33143. if (triggerOptions.parameter) {
  33144. this.trigger = triggerOptions.trigger;
  33145. this._triggerParameter = triggerOptions.parameter;
  33146. }
  33147. else {
  33148. this.trigger = triggerOptions;
  33149. }
  33150. this._nextActiveAction = this;
  33151. this._condition = condition;
  33152. }
  33153. // Methods
  33154. Action.prototype._prepare = function () {
  33155. };
  33156. Action.prototype.getTriggerParameter = function () {
  33157. return this._triggerParameter;
  33158. };
  33159. Action.prototype._executeCurrent = function (evt) {
  33160. if (this._nextActiveAction._condition) {
  33161. var condition = this._nextActiveAction._condition;
  33162. var currentRenderId = this._actionManager.getScene().getRenderId();
  33163. // We cache the current evaluation for the current frame
  33164. if (condition._evaluationId === currentRenderId) {
  33165. if (!condition._currentResult) {
  33166. return;
  33167. }
  33168. }
  33169. else {
  33170. condition._evaluationId = currentRenderId;
  33171. if (!condition.isValid()) {
  33172. condition._currentResult = false;
  33173. return;
  33174. }
  33175. condition._currentResult = true;
  33176. }
  33177. }
  33178. this._nextActiveAction.execute(evt);
  33179. this.skipToNextActiveAction();
  33180. };
  33181. Action.prototype.execute = function (evt) {
  33182. };
  33183. Action.prototype.skipToNextActiveAction = function () {
  33184. if (this._nextActiveAction._child) {
  33185. if (!this._nextActiveAction._child._actionManager) {
  33186. this._nextActiveAction._child._actionManager = this._actionManager;
  33187. }
  33188. this._nextActiveAction = this._nextActiveAction._child;
  33189. }
  33190. else {
  33191. this._nextActiveAction = this;
  33192. }
  33193. };
  33194. Action.prototype.then = function (action) {
  33195. this._child = action;
  33196. action._actionManager = this._actionManager;
  33197. action._prepare();
  33198. return action;
  33199. };
  33200. Action.prototype._getProperty = function (propertyPath) {
  33201. return this._actionManager._getProperty(propertyPath);
  33202. };
  33203. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  33204. return this._actionManager._getEffectiveTarget(target, propertyPath);
  33205. };
  33206. Action.prototype.serialize = function (parent) {
  33207. };
  33208. // Called by BABYLON.Action objects in serialize(...). Internal use
  33209. Action.prototype._serialize = function (serializedAction, parent) {
  33210. var serializationObject = {
  33211. type: 1,
  33212. children: [],
  33213. name: serializedAction.name,
  33214. properties: serializedAction.properties || []
  33215. };
  33216. // Serialize child
  33217. if (this._child) {
  33218. this._child.serialize(serializationObject);
  33219. }
  33220. // Check if "this" has a condition
  33221. if (this._condition) {
  33222. var serializedCondition = this._condition.serialize();
  33223. serializedCondition.children.push(serializationObject);
  33224. if (parent) {
  33225. parent.children.push(serializedCondition);
  33226. }
  33227. return serializedCondition;
  33228. }
  33229. if (parent) {
  33230. parent.children.push(serializationObject);
  33231. }
  33232. return serializationObject;
  33233. };
  33234. Action._SerializeValueAsString = function (value) {
  33235. if (typeof value === "number") {
  33236. return value.toString();
  33237. }
  33238. if (typeof value === "boolean") {
  33239. return value ? "true" : "false";
  33240. }
  33241. if (value instanceof BABYLON.Vector2) {
  33242. return value.x + ", " + value.y;
  33243. }
  33244. if (value instanceof BABYLON.Vector3) {
  33245. return value.x + ", " + value.y + ", " + value.z;
  33246. }
  33247. if (value instanceof BABYLON.Color3) {
  33248. return value.r + ", " + value.g + ", " + value.b;
  33249. }
  33250. if (value instanceof BABYLON.Color4) {
  33251. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  33252. }
  33253. return value; // string
  33254. };
  33255. Action._GetTargetProperty = function (target) {
  33256. return {
  33257. name: "target",
  33258. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  33259. : target instanceof BABYLON.Light ? "LightProperties"
  33260. : target instanceof BABYLON.Camera ? "CameraProperties"
  33261. : "SceneProperties",
  33262. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  33263. };
  33264. };
  33265. return Action;
  33266. })();
  33267. BABYLON.Action = Action;
  33268. })(BABYLON || (BABYLON = {}));
  33269. var BABYLON;
  33270. (function (BABYLON) {
  33271. /**
  33272. * ActionEvent is the event beint sent when an action is triggered.
  33273. */
  33274. var ActionEvent = (function () {
  33275. /**
  33276. * @constructor
  33277. * @param source The mesh or sprite that triggered the action.
  33278. * @param pointerX The X mouse cursor position at the time of the event
  33279. * @param pointerY The Y mouse cursor position at the time of the event
  33280. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  33281. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  33282. */
  33283. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  33284. this.source = source;
  33285. this.pointerX = pointerX;
  33286. this.pointerY = pointerY;
  33287. this.meshUnderPointer = meshUnderPointer;
  33288. this.sourceEvent = sourceEvent;
  33289. this.additionalData = additionalData;
  33290. }
  33291. /**
  33292. * Helper function to auto-create an ActionEvent from a source mesh.
  33293. * @param source The source mesh that triggered the event
  33294. * @param evt {Event} The original (browser) event
  33295. */
  33296. ActionEvent.CreateNew = function (source, evt, additionalData) {
  33297. var scene = source.getScene();
  33298. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  33299. };
  33300. /**
  33301. * Helper function to auto-create an ActionEvent from a source mesh.
  33302. * @param source The source sprite that triggered the event
  33303. * @param scene Scene associated with the sprite
  33304. * @param evt {Event} The original (browser) event
  33305. */
  33306. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  33307. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  33308. };
  33309. /**
  33310. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  33311. * @param scene the scene where the event occurred
  33312. * @param evt {Event} The original (browser) event
  33313. */
  33314. ActionEvent.CreateNewFromScene = function (scene, evt) {
  33315. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  33316. };
  33317. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  33318. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  33319. };
  33320. return ActionEvent;
  33321. })();
  33322. BABYLON.ActionEvent = ActionEvent;
  33323. /**
  33324. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  33325. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  33326. */
  33327. var ActionManager = (function () {
  33328. function ActionManager(scene) {
  33329. // Members
  33330. this.actions = new Array();
  33331. this._scene = scene;
  33332. scene._actionManagers.push(this);
  33333. }
  33334. Object.defineProperty(ActionManager, "NothingTrigger", {
  33335. get: function () {
  33336. return ActionManager._NothingTrigger;
  33337. },
  33338. enumerable: true,
  33339. configurable: true
  33340. });
  33341. Object.defineProperty(ActionManager, "OnPickTrigger", {
  33342. get: function () {
  33343. return ActionManager._OnPickTrigger;
  33344. },
  33345. enumerable: true,
  33346. configurable: true
  33347. });
  33348. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  33349. get: function () {
  33350. return ActionManager._OnLeftPickTrigger;
  33351. },
  33352. enumerable: true,
  33353. configurable: true
  33354. });
  33355. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  33356. get: function () {
  33357. return ActionManager._OnRightPickTrigger;
  33358. },
  33359. enumerable: true,
  33360. configurable: true
  33361. });
  33362. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  33363. get: function () {
  33364. return ActionManager._OnCenterPickTrigger;
  33365. },
  33366. enumerable: true,
  33367. configurable: true
  33368. });
  33369. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  33370. get: function () {
  33371. return ActionManager._OnPickDownTrigger;
  33372. },
  33373. enumerable: true,
  33374. configurable: true
  33375. });
  33376. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  33377. get: function () {
  33378. return ActionManager._OnPickUpTrigger;
  33379. },
  33380. enumerable: true,
  33381. configurable: true
  33382. });
  33383. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  33384. /// This trigger will only be raised if you also declared a OnPickDown
  33385. get: function () {
  33386. return ActionManager._OnPickOutTrigger;
  33387. },
  33388. enumerable: true,
  33389. configurable: true
  33390. });
  33391. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  33392. get: function () {
  33393. return ActionManager._OnLongPressTrigger;
  33394. },
  33395. enumerable: true,
  33396. configurable: true
  33397. });
  33398. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  33399. get: function () {
  33400. return ActionManager._OnPointerOverTrigger;
  33401. },
  33402. enumerable: true,
  33403. configurable: true
  33404. });
  33405. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  33406. get: function () {
  33407. return ActionManager._OnPointerOutTrigger;
  33408. },
  33409. enumerable: true,
  33410. configurable: true
  33411. });
  33412. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  33413. get: function () {
  33414. return ActionManager._OnEveryFrameTrigger;
  33415. },
  33416. enumerable: true,
  33417. configurable: true
  33418. });
  33419. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  33420. get: function () {
  33421. return ActionManager._OnIntersectionEnterTrigger;
  33422. },
  33423. enumerable: true,
  33424. configurable: true
  33425. });
  33426. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  33427. get: function () {
  33428. return ActionManager._OnIntersectionExitTrigger;
  33429. },
  33430. enumerable: true,
  33431. configurable: true
  33432. });
  33433. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  33434. get: function () {
  33435. return ActionManager._OnKeyDownTrigger;
  33436. },
  33437. enumerable: true,
  33438. configurable: true
  33439. });
  33440. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  33441. get: function () {
  33442. return ActionManager._OnKeyUpTrigger;
  33443. },
  33444. enumerable: true,
  33445. configurable: true
  33446. });
  33447. // Methods
  33448. ActionManager.prototype.dispose = function () {
  33449. var index = this._scene._actionManagers.indexOf(this);
  33450. if (index > -1) {
  33451. this._scene._actionManagers.splice(index, 1);
  33452. }
  33453. };
  33454. ActionManager.prototype.getScene = function () {
  33455. return this._scene;
  33456. };
  33457. /**
  33458. * Does this action manager handles actions of any of the given triggers
  33459. * @param {number[]} triggers - the triggers to be tested
  33460. * @return {boolean} whether one (or more) of the triggers is handeled
  33461. */
  33462. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  33463. for (var index = 0; index < this.actions.length; index++) {
  33464. var action = this.actions[index];
  33465. if (triggers.indexOf(action.trigger) > -1) {
  33466. return true;
  33467. }
  33468. }
  33469. return false;
  33470. };
  33471. /**
  33472. * Does this action manager handles actions of a given trigger
  33473. * @param {number} trigger - the trigger to be tested
  33474. * @return {boolean} whether the trigger is handeled
  33475. */
  33476. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  33477. for (var index = 0; index < this.actions.length; index++) {
  33478. var action = this.actions[index];
  33479. if (action.trigger === trigger) {
  33480. return true;
  33481. }
  33482. }
  33483. return false;
  33484. };
  33485. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  33486. /**
  33487. * Does this action manager has pointer triggers
  33488. * @return {boolean} whether or not it has pointer triggers
  33489. */
  33490. get: function () {
  33491. for (var index = 0; index < this.actions.length; index++) {
  33492. var action = this.actions[index];
  33493. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  33494. return true;
  33495. }
  33496. }
  33497. return false;
  33498. },
  33499. enumerable: true,
  33500. configurable: true
  33501. });
  33502. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  33503. /**
  33504. * Does this action manager has pick triggers
  33505. * @return {boolean} whether or not it has pick triggers
  33506. */
  33507. get: function () {
  33508. for (var index = 0; index < this.actions.length; index++) {
  33509. var action = this.actions[index];
  33510. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  33511. return true;
  33512. }
  33513. }
  33514. return false;
  33515. },
  33516. enumerable: true,
  33517. configurable: true
  33518. });
  33519. /**
  33520. * Registers an action to this action manager
  33521. * @param {BABYLON.Action} action - the action to be registered
  33522. * @return {BABYLON.Action} the action amended (prepared) after registration
  33523. */
  33524. ActionManager.prototype.registerAction = function (action) {
  33525. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  33526. if (this.getScene().actionManager !== this) {
  33527. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  33528. return null;
  33529. }
  33530. }
  33531. this.actions.push(action);
  33532. action._actionManager = this;
  33533. action._prepare();
  33534. return action;
  33535. };
  33536. /**
  33537. * Process a specific trigger
  33538. * @param {number} trigger - the trigger to process
  33539. * @param evt {BABYLON.ActionEvent} the event details to be processed
  33540. */
  33541. ActionManager.prototype.processTrigger = function (trigger, evt) {
  33542. for (var index = 0; index < this.actions.length; index++) {
  33543. var action = this.actions[index];
  33544. if (action.trigger === trigger) {
  33545. if (trigger === ActionManager.OnKeyUpTrigger
  33546. || trigger === ActionManager.OnKeyDownTrigger) {
  33547. var parameter = action.getTriggerParameter();
  33548. if (parameter) {
  33549. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  33550. var actualkey = String.fromCharCode(unicode).toLowerCase();
  33551. if (actualkey !== parameter.toLowerCase()) {
  33552. continue;
  33553. }
  33554. }
  33555. }
  33556. action._executeCurrent(evt);
  33557. }
  33558. }
  33559. };
  33560. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  33561. var properties = propertyPath.split(".");
  33562. for (var index = 0; index < properties.length - 1; index++) {
  33563. target = target[properties[index]];
  33564. }
  33565. return target;
  33566. };
  33567. ActionManager.prototype._getProperty = function (propertyPath) {
  33568. var properties = propertyPath.split(".");
  33569. return properties[properties.length - 1];
  33570. };
  33571. ActionManager.prototype.serialize = function (name) {
  33572. var root = {
  33573. children: [],
  33574. name: name,
  33575. type: 3,
  33576. properties: [] // Empty for root but required
  33577. };
  33578. for (var i = 0; i < this.actions.length; i++) {
  33579. var triggerObject = {
  33580. type: 0,
  33581. children: [],
  33582. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  33583. properties: []
  33584. };
  33585. var triggerOptions = this.actions[i].triggerOptions;
  33586. if (triggerOptions && typeof triggerOptions !== "number") {
  33587. if (triggerOptions.parameter instanceof BABYLON.Node) {
  33588. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  33589. }
  33590. else {
  33591. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  33592. }
  33593. }
  33594. // Serialize child action, recursively
  33595. this.actions[i].serialize(triggerObject);
  33596. // Add serialized trigger
  33597. root.children.push(triggerObject);
  33598. }
  33599. return root;
  33600. };
  33601. ActionManager.Parse = function (parsedActions, object, scene) {
  33602. var actionManager = new BABYLON.ActionManager(scene);
  33603. if (object === null)
  33604. scene.actionManager = actionManager;
  33605. else
  33606. object.actionManager = actionManager;
  33607. // instanciate a new object
  33608. var instanciate = function (name, params) {
  33609. var newInstance = Object.create(BABYLON[name].prototype);
  33610. newInstance.constructor.apply(newInstance, params);
  33611. return newInstance;
  33612. };
  33613. var parseParameter = function (name, value, target, propertyPath) {
  33614. if (propertyPath === null) {
  33615. // String, boolean or float
  33616. var floatValue = parseFloat(value);
  33617. if (value === "true" || value === "false")
  33618. return value === "true";
  33619. else
  33620. return isNaN(floatValue) ? value : floatValue;
  33621. }
  33622. var effectiveTarget = propertyPath.split(".");
  33623. var values = value.split(",");
  33624. // Get effective Target
  33625. for (var i = 0; i < effectiveTarget.length; i++) {
  33626. target = target[effectiveTarget[i]];
  33627. }
  33628. // Return appropriate value with its type
  33629. if (typeof (target) === "boolean")
  33630. return values[0] === "true";
  33631. if (typeof (target) === "string")
  33632. return values[0];
  33633. // Parameters with multiple values such as Vector3 etc.
  33634. var split = new Array();
  33635. for (var i = 0; i < values.length; i++)
  33636. split.push(parseFloat(values[i]));
  33637. if (target instanceof BABYLON.Vector3)
  33638. return BABYLON.Vector3.FromArray(split);
  33639. if (target instanceof BABYLON.Vector4)
  33640. return BABYLON.Vector4.FromArray(split);
  33641. if (target instanceof BABYLON.Color3)
  33642. return BABYLON.Color3.FromArray(split);
  33643. if (target instanceof BABYLON.Color4)
  33644. return BABYLON.Color4.FromArray(split);
  33645. return parseFloat(values[0]);
  33646. };
  33647. // traverse graph per trigger
  33648. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  33649. if (combineArray === void 0) { combineArray = null; }
  33650. if (parsedAction.detached)
  33651. return;
  33652. var parameters = new Array();
  33653. var target = null;
  33654. var propertyPath = null;
  33655. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  33656. // Parameters
  33657. if (parsedAction.type === 2)
  33658. parameters.push(actionManager);
  33659. else
  33660. parameters.push(trigger);
  33661. if (combine) {
  33662. var actions = new Array();
  33663. for (var j = 0; j < parsedAction.combine.length; j++) {
  33664. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  33665. }
  33666. parameters.push(actions);
  33667. }
  33668. else {
  33669. for (var i = 0; i < parsedAction.properties.length; i++) {
  33670. var value = parsedAction.properties[i].value;
  33671. var name = parsedAction.properties[i].name;
  33672. var targetType = parsedAction.properties[i].targetType;
  33673. if (name === "target")
  33674. if (targetType !== null && targetType === "SceneProperties")
  33675. value = target = scene;
  33676. else
  33677. value = target = scene.getNodeByName(value);
  33678. else if (name === "parent")
  33679. value = scene.getNodeByName(value);
  33680. else if (name === "sound")
  33681. value = scene.getSoundByName(value);
  33682. else if (name !== "propertyPath") {
  33683. if (parsedAction.type === 2 && name === "operator")
  33684. value = BABYLON.ValueCondition[value];
  33685. else
  33686. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  33687. }
  33688. else {
  33689. propertyPath = value;
  33690. }
  33691. parameters.push(value);
  33692. }
  33693. }
  33694. if (combineArray === null) {
  33695. parameters.push(condition);
  33696. }
  33697. else {
  33698. parameters.push(null);
  33699. }
  33700. // If interpolate value action
  33701. if (parsedAction.name === "InterpolateValueAction") {
  33702. var param = parameters[parameters.length - 2];
  33703. parameters[parameters.length - 1] = param;
  33704. parameters[parameters.length - 2] = condition;
  33705. }
  33706. // Action or condition(s) and not CombineAction
  33707. var newAction = instanciate(parsedAction.name, parameters);
  33708. if (newAction instanceof BABYLON.Condition && condition !== null) {
  33709. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  33710. if (action)
  33711. action.then(nothing);
  33712. else
  33713. actionManager.registerAction(nothing);
  33714. action = nothing;
  33715. }
  33716. if (combineArray === null) {
  33717. if (newAction instanceof BABYLON.Condition) {
  33718. condition = newAction;
  33719. newAction = action;
  33720. }
  33721. else {
  33722. condition = null;
  33723. if (action)
  33724. action.then(newAction);
  33725. else
  33726. actionManager.registerAction(newAction);
  33727. }
  33728. }
  33729. else {
  33730. combineArray.push(newAction);
  33731. }
  33732. for (var i = 0; i < parsedAction.children.length; i++)
  33733. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  33734. };
  33735. // triggers
  33736. for (var i = 0; i < parsedActions.children.length; i++) {
  33737. var triggerParams;
  33738. var trigger = parsedActions.children[i];
  33739. if (trigger.properties.length > 0) {
  33740. var param = trigger.properties[0].value;
  33741. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  33742. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  33743. }
  33744. else
  33745. triggerParams = BABYLON.ActionManager[trigger.name];
  33746. for (var j = 0; j < trigger.children.length; j++) {
  33747. if (!trigger.detached)
  33748. traverse(trigger.children[j], triggerParams, null, null);
  33749. }
  33750. }
  33751. };
  33752. ActionManager.GetTriggerName = function (trigger) {
  33753. switch (trigger) {
  33754. case 0: return "NothingTrigger";
  33755. case 1: return "OnPickTrigger";
  33756. case 2: return "OnLeftPickTrigger";
  33757. case 3: return "OnRightPickTrigger";
  33758. case 4: return "OnCenterPickTrigger";
  33759. case 5: return "OnPickDownTrigger";
  33760. case 6: return "OnPickUpTrigger";
  33761. case 7: return "OnLongPressTrigger";
  33762. case 8: return "OnPointerOverTrigger";
  33763. case 9: return "OnPointerOutTrigger";
  33764. case 10: return "OnEveryFrameTrigger";
  33765. case 11: return "OnIntersectionEnterTrigger";
  33766. case 12: return "OnIntersectionExitTrigger";
  33767. case 13: return "OnKeyDownTrigger";
  33768. case 14: return "OnKeyUpTrigger";
  33769. case 15: return "OnPickOutTrigger";
  33770. default: return "";
  33771. }
  33772. };
  33773. // Statics
  33774. ActionManager._NothingTrigger = 0;
  33775. ActionManager._OnPickTrigger = 1;
  33776. ActionManager._OnLeftPickTrigger = 2;
  33777. ActionManager._OnRightPickTrigger = 3;
  33778. ActionManager._OnCenterPickTrigger = 4;
  33779. ActionManager._OnPickDownTrigger = 5;
  33780. ActionManager._OnPickUpTrigger = 6;
  33781. ActionManager._OnLongPressTrigger = 7;
  33782. ActionManager._OnPointerOverTrigger = 8;
  33783. ActionManager._OnPointerOutTrigger = 9;
  33784. ActionManager._OnEveryFrameTrigger = 10;
  33785. ActionManager._OnIntersectionEnterTrigger = 11;
  33786. ActionManager._OnIntersectionExitTrigger = 12;
  33787. ActionManager._OnKeyDownTrigger = 13;
  33788. ActionManager._OnKeyUpTrigger = 14;
  33789. ActionManager._OnPickOutTrigger = 15;
  33790. ActionManager.DragMovementThreshold = 10; // in pixels
  33791. ActionManager.LongPressDelay = 500; // in milliseconds
  33792. return ActionManager;
  33793. })();
  33794. BABYLON.ActionManager = ActionManager;
  33795. })(BABYLON || (BABYLON = {}));
  33796. var BABYLON;
  33797. (function (BABYLON) {
  33798. var InterpolateValueAction = (function (_super) {
  33799. __extends(InterpolateValueAction, _super);
  33800. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  33801. if (duration === void 0) { duration = 1000; }
  33802. _super.call(this, triggerOptions, condition);
  33803. this.propertyPath = propertyPath;
  33804. this.value = value;
  33805. this.duration = duration;
  33806. this.stopOtherAnimations = stopOtherAnimations;
  33807. this.onInterpolationDone = onInterpolationDone;
  33808. this._target = this._effectiveTarget = target;
  33809. }
  33810. InterpolateValueAction.prototype._prepare = function () {
  33811. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33812. this._property = this._getProperty(this.propertyPath);
  33813. };
  33814. InterpolateValueAction.prototype.execute = function () {
  33815. var scene = this._actionManager.getScene();
  33816. var keys = [
  33817. {
  33818. frame: 0,
  33819. value: this._effectiveTarget[this._property]
  33820. }, {
  33821. frame: 100,
  33822. value: this.value
  33823. }
  33824. ];
  33825. var dataType;
  33826. if (typeof this.value === "number") {
  33827. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  33828. }
  33829. else if (this.value instanceof BABYLON.Color3) {
  33830. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  33831. }
  33832. else if (this.value instanceof BABYLON.Vector3) {
  33833. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  33834. }
  33835. else if (this.value instanceof BABYLON.Matrix) {
  33836. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  33837. }
  33838. else if (this.value instanceof BABYLON.Quaternion) {
  33839. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  33840. }
  33841. else {
  33842. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  33843. return;
  33844. }
  33845. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  33846. animation.setKeys(keys);
  33847. if (this.stopOtherAnimations) {
  33848. scene.stopAnimation(this._effectiveTarget);
  33849. }
  33850. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  33851. };
  33852. InterpolateValueAction.prototype.serialize = function (parent) {
  33853. return _super.prototype._serialize.call(this, {
  33854. name: "InterpolateValueAction",
  33855. properties: [
  33856. BABYLON.Action._GetTargetProperty(this._target),
  33857. { name: "propertyPath", value: this.propertyPath },
  33858. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  33859. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  33860. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  33861. ]
  33862. }, parent);
  33863. };
  33864. return InterpolateValueAction;
  33865. })(BABYLON.Action);
  33866. BABYLON.InterpolateValueAction = InterpolateValueAction;
  33867. })(BABYLON || (BABYLON = {}));
  33868. var BABYLON;
  33869. (function (BABYLON) {
  33870. var SwitchBooleanAction = (function (_super) {
  33871. __extends(SwitchBooleanAction, _super);
  33872. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  33873. _super.call(this, triggerOptions, condition);
  33874. this.propertyPath = propertyPath;
  33875. this._target = this._effectiveTarget = target;
  33876. }
  33877. SwitchBooleanAction.prototype._prepare = function () {
  33878. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33879. this._property = this._getProperty(this.propertyPath);
  33880. };
  33881. SwitchBooleanAction.prototype.execute = function () {
  33882. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  33883. };
  33884. SwitchBooleanAction.prototype.serialize = function (parent) {
  33885. return _super.prototype._serialize.call(this, {
  33886. name: "SwitchBooleanAction",
  33887. properties: [
  33888. BABYLON.Action._GetTargetProperty(this._target),
  33889. { name: "propertyPath", value: this.propertyPath }
  33890. ]
  33891. }, parent);
  33892. };
  33893. return SwitchBooleanAction;
  33894. })(BABYLON.Action);
  33895. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  33896. var SetStateAction = (function (_super) {
  33897. __extends(SetStateAction, _super);
  33898. function SetStateAction(triggerOptions, target, value, condition) {
  33899. _super.call(this, triggerOptions, condition);
  33900. this.value = value;
  33901. this._target = target;
  33902. }
  33903. SetStateAction.prototype.execute = function () {
  33904. this._target.state = this.value;
  33905. };
  33906. SetStateAction.prototype.serialize = function (parent) {
  33907. return _super.prototype._serialize.call(this, {
  33908. name: "SetStateAction",
  33909. properties: [
  33910. BABYLON.Action._GetTargetProperty(this._target),
  33911. { name: "value", value: this.value }
  33912. ]
  33913. }, parent);
  33914. };
  33915. return SetStateAction;
  33916. })(BABYLON.Action);
  33917. BABYLON.SetStateAction = SetStateAction;
  33918. var SetValueAction = (function (_super) {
  33919. __extends(SetValueAction, _super);
  33920. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  33921. _super.call(this, triggerOptions, condition);
  33922. this.propertyPath = propertyPath;
  33923. this.value = value;
  33924. this._target = this._effectiveTarget = target;
  33925. }
  33926. SetValueAction.prototype._prepare = function () {
  33927. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33928. this._property = this._getProperty(this.propertyPath);
  33929. };
  33930. SetValueAction.prototype.execute = function () {
  33931. this._effectiveTarget[this._property] = this.value;
  33932. if (this._target.markAsDirty) {
  33933. this._target.markAsDirty(this._property);
  33934. }
  33935. };
  33936. SetValueAction.prototype.serialize = function (parent) {
  33937. return _super.prototype._serialize.call(this, {
  33938. name: "SetValueAction",
  33939. properties: [
  33940. BABYLON.Action._GetTargetProperty(this._target),
  33941. { name: "propertyPath", value: this.propertyPath },
  33942. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  33943. ]
  33944. }, parent);
  33945. };
  33946. return SetValueAction;
  33947. })(BABYLON.Action);
  33948. BABYLON.SetValueAction = SetValueAction;
  33949. var IncrementValueAction = (function (_super) {
  33950. __extends(IncrementValueAction, _super);
  33951. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  33952. _super.call(this, triggerOptions, condition);
  33953. this.propertyPath = propertyPath;
  33954. this.value = value;
  33955. this._target = this._effectiveTarget = target;
  33956. }
  33957. IncrementValueAction.prototype._prepare = function () {
  33958. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33959. this._property = this._getProperty(this.propertyPath);
  33960. if (typeof this._effectiveTarget[this._property] !== "number") {
  33961. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  33962. }
  33963. };
  33964. IncrementValueAction.prototype.execute = function () {
  33965. this._effectiveTarget[this._property] += this.value;
  33966. if (this._target.markAsDirty) {
  33967. this._target.markAsDirty(this._property);
  33968. }
  33969. };
  33970. IncrementValueAction.prototype.serialize = function (parent) {
  33971. return _super.prototype._serialize.call(this, {
  33972. name: "IncrementValueAction",
  33973. properties: [
  33974. BABYLON.Action._GetTargetProperty(this._target),
  33975. { name: "propertyPath", value: this.propertyPath },
  33976. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  33977. ]
  33978. }, parent);
  33979. };
  33980. return IncrementValueAction;
  33981. })(BABYLON.Action);
  33982. BABYLON.IncrementValueAction = IncrementValueAction;
  33983. var PlayAnimationAction = (function (_super) {
  33984. __extends(PlayAnimationAction, _super);
  33985. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  33986. _super.call(this, triggerOptions, condition);
  33987. this.from = from;
  33988. this.to = to;
  33989. this.loop = loop;
  33990. this._target = target;
  33991. }
  33992. PlayAnimationAction.prototype._prepare = function () {
  33993. };
  33994. PlayAnimationAction.prototype.execute = function () {
  33995. var scene = this._actionManager.getScene();
  33996. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  33997. };
  33998. PlayAnimationAction.prototype.serialize = function (parent) {
  33999. return _super.prototype._serialize.call(this, {
  34000. name: "PlayAnimationAction",
  34001. properties: [
  34002. BABYLON.Action._GetTargetProperty(this._target),
  34003. { name: "from", value: String(this.from) },
  34004. { name: "to", value: String(this.to) },
  34005. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  34006. ]
  34007. }, parent);
  34008. };
  34009. return PlayAnimationAction;
  34010. })(BABYLON.Action);
  34011. BABYLON.PlayAnimationAction = PlayAnimationAction;
  34012. var StopAnimationAction = (function (_super) {
  34013. __extends(StopAnimationAction, _super);
  34014. function StopAnimationAction(triggerOptions, target, condition) {
  34015. _super.call(this, triggerOptions, condition);
  34016. this._target = target;
  34017. }
  34018. StopAnimationAction.prototype._prepare = function () {
  34019. };
  34020. StopAnimationAction.prototype.execute = function () {
  34021. var scene = this._actionManager.getScene();
  34022. scene.stopAnimation(this._target);
  34023. };
  34024. StopAnimationAction.prototype.serialize = function (parent) {
  34025. return _super.prototype._serialize.call(this, {
  34026. name: "StopAnimationAction",
  34027. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  34028. }, parent);
  34029. };
  34030. return StopAnimationAction;
  34031. })(BABYLON.Action);
  34032. BABYLON.StopAnimationAction = StopAnimationAction;
  34033. var DoNothingAction = (function (_super) {
  34034. __extends(DoNothingAction, _super);
  34035. function DoNothingAction(triggerOptions, condition) {
  34036. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  34037. _super.call(this, triggerOptions, condition);
  34038. }
  34039. DoNothingAction.prototype.execute = function () {
  34040. };
  34041. DoNothingAction.prototype.serialize = function (parent) {
  34042. return _super.prototype._serialize.call(this, {
  34043. name: "DoNothingAction",
  34044. properties: []
  34045. }, parent);
  34046. };
  34047. return DoNothingAction;
  34048. })(BABYLON.Action);
  34049. BABYLON.DoNothingAction = DoNothingAction;
  34050. var CombineAction = (function (_super) {
  34051. __extends(CombineAction, _super);
  34052. function CombineAction(triggerOptions, children, condition) {
  34053. _super.call(this, triggerOptions, condition);
  34054. this.children = children;
  34055. }
  34056. CombineAction.prototype._prepare = function () {
  34057. for (var index = 0; index < this.children.length; index++) {
  34058. this.children[index]._actionManager = this._actionManager;
  34059. this.children[index]._prepare();
  34060. }
  34061. };
  34062. CombineAction.prototype.execute = function (evt) {
  34063. for (var index = 0; index < this.children.length; index++) {
  34064. this.children[index].execute(evt);
  34065. }
  34066. };
  34067. CombineAction.prototype.serialize = function (parent) {
  34068. var serializationObject = _super.prototype._serialize.call(this, {
  34069. name: "CombineAction",
  34070. properties: [],
  34071. combine: []
  34072. }, parent);
  34073. for (var i = 0; i < this.children.length; i++) {
  34074. serializationObject.combine.push(this.children[i].serialize(null));
  34075. }
  34076. return serializationObject;
  34077. };
  34078. return CombineAction;
  34079. })(BABYLON.Action);
  34080. BABYLON.CombineAction = CombineAction;
  34081. var ExecuteCodeAction = (function (_super) {
  34082. __extends(ExecuteCodeAction, _super);
  34083. function ExecuteCodeAction(triggerOptions, func, condition) {
  34084. _super.call(this, triggerOptions, condition);
  34085. this.func = func;
  34086. }
  34087. ExecuteCodeAction.prototype.execute = function (evt) {
  34088. this.func(evt);
  34089. };
  34090. return ExecuteCodeAction;
  34091. })(BABYLON.Action);
  34092. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  34093. var SetParentAction = (function (_super) {
  34094. __extends(SetParentAction, _super);
  34095. function SetParentAction(triggerOptions, target, parent, condition) {
  34096. _super.call(this, triggerOptions, condition);
  34097. this._target = target;
  34098. this._parent = parent;
  34099. }
  34100. SetParentAction.prototype._prepare = function () {
  34101. };
  34102. SetParentAction.prototype.execute = function () {
  34103. if (this._target.parent === this._parent) {
  34104. return;
  34105. }
  34106. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  34107. invertParentWorldMatrix.invert();
  34108. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  34109. this._target.parent = this._parent;
  34110. };
  34111. SetParentAction.prototype.serialize = function (parent) {
  34112. return _super.prototype._serialize.call(this, {
  34113. name: "SetParentAction",
  34114. properties: [
  34115. BABYLON.Action._GetTargetProperty(this._target),
  34116. BABYLON.Action._GetTargetProperty(this._parent),
  34117. ]
  34118. }, parent);
  34119. };
  34120. return SetParentAction;
  34121. })(BABYLON.Action);
  34122. BABYLON.SetParentAction = SetParentAction;
  34123. var PlaySoundAction = (function (_super) {
  34124. __extends(PlaySoundAction, _super);
  34125. function PlaySoundAction(triggerOptions, sound, condition) {
  34126. _super.call(this, triggerOptions, condition);
  34127. this._sound = sound;
  34128. }
  34129. PlaySoundAction.prototype._prepare = function () {
  34130. };
  34131. PlaySoundAction.prototype.execute = function () {
  34132. if (this._sound !== undefined)
  34133. this._sound.play();
  34134. };
  34135. PlaySoundAction.prototype.serialize = function (parent) {
  34136. return _super.prototype._serialize.call(this, {
  34137. name: "PlaySoundAction",
  34138. properties: [{ name: "sound", value: this._sound.name }]
  34139. }, parent);
  34140. };
  34141. return PlaySoundAction;
  34142. })(BABYLON.Action);
  34143. BABYLON.PlaySoundAction = PlaySoundAction;
  34144. var StopSoundAction = (function (_super) {
  34145. __extends(StopSoundAction, _super);
  34146. function StopSoundAction(triggerOptions, sound, condition) {
  34147. _super.call(this, triggerOptions, condition);
  34148. this._sound = sound;
  34149. }
  34150. StopSoundAction.prototype._prepare = function () {
  34151. };
  34152. StopSoundAction.prototype.execute = function () {
  34153. if (this._sound !== undefined)
  34154. this._sound.stop();
  34155. };
  34156. StopSoundAction.prototype.serialize = function (parent) {
  34157. return _super.prototype._serialize.call(this, {
  34158. name: "StopSoundAction",
  34159. properties: [{ name: "sound", value: this._sound.name }]
  34160. }, parent);
  34161. };
  34162. return StopSoundAction;
  34163. })(BABYLON.Action);
  34164. BABYLON.StopSoundAction = StopSoundAction;
  34165. })(BABYLON || (BABYLON = {}));
  34166. var BABYLON;
  34167. (function (BABYLON) {
  34168. var Geometry = (function () {
  34169. function Geometry(id, scene, vertexData, updatable, mesh) {
  34170. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34171. this._totalVertices = 0;
  34172. this._isDisposed = false;
  34173. this.id = id;
  34174. this._engine = scene.getEngine();
  34175. this._meshes = [];
  34176. this._scene = scene;
  34177. //Init vertex buffer cache
  34178. this._vertexBuffers = {};
  34179. this._indices = [];
  34180. // vertexData
  34181. if (vertexData) {
  34182. this.setAllVerticesData(vertexData, updatable);
  34183. }
  34184. else {
  34185. this._totalVertices = 0;
  34186. this._indices = [];
  34187. }
  34188. // applyToMesh
  34189. if (mesh) {
  34190. if (mesh instanceof BABYLON.LinesMesh) {
  34191. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34192. this.updateExtend();
  34193. }
  34194. this.applyToMesh(mesh);
  34195. mesh.computeWorldMatrix(true);
  34196. }
  34197. }
  34198. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34199. /**
  34200. * 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
  34201. * @returns The Bias Vector
  34202. */
  34203. get: function () {
  34204. return this._boundingBias;
  34205. },
  34206. set: function (value) {
  34207. if (this._boundingBias && this._boundingBias.equals(value)) {
  34208. return;
  34209. }
  34210. this._boundingBias = value.clone();
  34211. this.updateBoundingInfo(true, null);
  34212. },
  34213. enumerable: true,
  34214. configurable: true
  34215. });
  34216. Object.defineProperty(Geometry.prototype, "extend", {
  34217. get: function () {
  34218. return this._extend;
  34219. },
  34220. enumerable: true,
  34221. configurable: true
  34222. });
  34223. Geometry.prototype.getScene = function () {
  34224. return this._scene;
  34225. };
  34226. Geometry.prototype.getEngine = function () {
  34227. return this._engine;
  34228. };
  34229. Geometry.prototype.isReady = function () {
  34230. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34231. };
  34232. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34233. vertexData.applyToGeometry(this, updatable);
  34234. this.notifyUpdate();
  34235. };
  34236. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34237. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34238. this.setVerticesBuffer(buffer);
  34239. };
  34240. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34241. var kind = buffer.getKind();
  34242. if (this._vertexBuffers[kind]) {
  34243. this._vertexBuffers[kind].dispose();
  34244. }
  34245. this._vertexBuffers[kind] = buffer;
  34246. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34247. var data = buffer.getData();
  34248. var stride = buffer.getStrideSize();
  34249. this._totalVertices = data.length / stride;
  34250. this.updateExtend(data, stride);
  34251. var meshes = this._meshes;
  34252. var numOfMeshes = meshes.length;
  34253. for (var index = 0; index < numOfMeshes; index++) {
  34254. var mesh = meshes[index];
  34255. mesh._resetPointsArrayCache();
  34256. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34257. mesh._createGlobalSubMesh();
  34258. mesh.computeWorldMatrix(true);
  34259. }
  34260. }
  34261. this.notifyUpdate(kind);
  34262. };
  34263. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34264. var vertexBuffer = this.getVertexBuffer(kind);
  34265. if (!vertexBuffer) {
  34266. return;
  34267. }
  34268. vertexBuffer.updateDirectly(data, offset);
  34269. this.notifyUpdate(kind);
  34270. };
  34271. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34272. var vertexBuffer = this.getVertexBuffer(kind);
  34273. if (!vertexBuffer) {
  34274. return;
  34275. }
  34276. vertexBuffer.update(data);
  34277. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34278. var stride = vertexBuffer.getStrideSize();
  34279. this._totalVertices = data.length / stride;
  34280. this.updateBoundingInfo(updateExtends, data);
  34281. }
  34282. this.notifyUpdate(kind);
  34283. };
  34284. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34285. if (updateExtends) {
  34286. this.updateExtend(data);
  34287. }
  34288. var meshes = this._meshes;
  34289. var numOfMeshes = meshes.length;
  34290. for (var index = 0; index < numOfMeshes; index++) {
  34291. var mesh = meshes[index];
  34292. mesh._resetPointsArrayCache();
  34293. if (updateExtends) {
  34294. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34295. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34296. var subMesh = mesh.subMeshes[subIndex];
  34297. subMesh.refreshBoundingInfo();
  34298. }
  34299. }
  34300. }
  34301. };
  34302. Geometry.prototype.getTotalVertices = function () {
  34303. if (!this.isReady()) {
  34304. return 0;
  34305. }
  34306. return this._totalVertices;
  34307. };
  34308. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  34309. var vertexBuffer = this.getVertexBuffer(kind);
  34310. if (!vertexBuffer) {
  34311. return null;
  34312. }
  34313. var orig = vertexBuffer.getData();
  34314. if (!copyWhenShared || this._meshes.length === 1) {
  34315. return orig;
  34316. }
  34317. else {
  34318. var len = orig.length;
  34319. var copy = [];
  34320. for (var i = 0; i < len; i++) {
  34321. copy.push(orig[i]);
  34322. }
  34323. return copy;
  34324. }
  34325. };
  34326. Geometry.prototype.getVertexBuffer = function (kind) {
  34327. if (!this.isReady()) {
  34328. return null;
  34329. }
  34330. return this._vertexBuffers[kind];
  34331. };
  34332. Geometry.prototype.getVertexBuffers = function () {
  34333. if (!this.isReady()) {
  34334. return null;
  34335. }
  34336. return this._vertexBuffers;
  34337. };
  34338. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34339. if (!this._vertexBuffers) {
  34340. if (this._delayInfo) {
  34341. return this._delayInfo.indexOf(kind) !== -1;
  34342. }
  34343. return false;
  34344. }
  34345. return this._vertexBuffers[kind] !== undefined;
  34346. };
  34347. Geometry.prototype.getVerticesDataKinds = function () {
  34348. var result = [];
  34349. var kind;
  34350. if (!this._vertexBuffers && this._delayInfo) {
  34351. for (kind in this._delayInfo) {
  34352. result.push(kind);
  34353. }
  34354. }
  34355. else {
  34356. for (kind in this._vertexBuffers) {
  34357. result.push(kind);
  34358. }
  34359. }
  34360. return result;
  34361. };
  34362. Geometry.prototype.setIndices = function (indices, totalVertices) {
  34363. if (this._indexBuffer) {
  34364. this._engine._releaseBuffer(this._indexBuffer);
  34365. }
  34366. this._indices = indices;
  34367. if (this._meshes.length !== 0 && this._indices) {
  34368. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34369. }
  34370. if (totalVertices !== undefined) {
  34371. this._totalVertices = totalVertices;
  34372. }
  34373. var meshes = this._meshes;
  34374. var numOfMeshes = meshes.length;
  34375. for (var index = 0; index < numOfMeshes; index++) {
  34376. meshes[index]._createGlobalSubMesh();
  34377. }
  34378. this.notifyUpdate();
  34379. };
  34380. Geometry.prototype.getTotalIndices = function () {
  34381. if (!this.isReady()) {
  34382. return 0;
  34383. }
  34384. return this._indices.length;
  34385. };
  34386. Geometry.prototype.getIndices = function (copyWhenShared) {
  34387. if (!this.isReady()) {
  34388. return null;
  34389. }
  34390. var orig = this._indices;
  34391. if (!copyWhenShared || this._meshes.length === 1) {
  34392. return orig;
  34393. }
  34394. else {
  34395. var len = orig.length;
  34396. var copy = [];
  34397. for (var i = 0; i < len; i++) {
  34398. copy.push(orig[i]);
  34399. }
  34400. return copy;
  34401. }
  34402. };
  34403. Geometry.prototype.getIndexBuffer = function () {
  34404. if (!this.isReady()) {
  34405. return null;
  34406. }
  34407. return this._indexBuffer;
  34408. };
  34409. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  34410. var meshes = this._meshes;
  34411. var index = meshes.indexOf(mesh);
  34412. if (index === -1) {
  34413. return;
  34414. }
  34415. for (var kind in this._vertexBuffers) {
  34416. this._vertexBuffers[kind].dispose();
  34417. }
  34418. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  34419. this._indexBuffer = null;
  34420. }
  34421. meshes.splice(index, 1);
  34422. mesh._geometry = null;
  34423. if (meshes.length === 0 && shouldDispose) {
  34424. this.dispose();
  34425. }
  34426. };
  34427. Geometry.prototype.applyToMesh = function (mesh) {
  34428. if (mesh._geometry === this) {
  34429. return;
  34430. }
  34431. var previousGeometry = mesh._geometry;
  34432. if (previousGeometry) {
  34433. previousGeometry.releaseForMesh(mesh);
  34434. }
  34435. var meshes = this._meshes;
  34436. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  34437. mesh._geometry = this;
  34438. this._scene.pushGeometry(this);
  34439. meshes.push(mesh);
  34440. if (this.isReady()) {
  34441. this._applyToMesh(mesh);
  34442. }
  34443. else {
  34444. mesh._boundingInfo = this._boundingInfo;
  34445. }
  34446. };
  34447. Geometry.prototype.updateExtend = function (data, stride) {
  34448. if (data === void 0) { data = null; }
  34449. if (!data) {
  34450. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  34451. }
  34452. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  34453. };
  34454. Geometry.prototype._applyToMesh = function (mesh) {
  34455. var numOfMeshes = this._meshes.length;
  34456. // vertexBuffers
  34457. for (var kind in this._vertexBuffers) {
  34458. if (numOfMeshes === 1) {
  34459. this._vertexBuffers[kind].create();
  34460. }
  34461. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  34462. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34463. mesh._resetPointsArrayCache();
  34464. if (!this._extend) {
  34465. this.updateExtend(this._vertexBuffers[kind].getData());
  34466. }
  34467. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34468. mesh._createGlobalSubMesh();
  34469. //bounding info was just created again, world matrix should be applied again.
  34470. mesh._updateBoundingInfo();
  34471. }
  34472. }
  34473. // indexBuffer
  34474. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  34475. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34476. }
  34477. if (this._indexBuffer) {
  34478. this._indexBuffer.references = numOfMeshes;
  34479. }
  34480. };
  34481. Geometry.prototype.notifyUpdate = function (kind) {
  34482. if (this.onGeometryUpdated) {
  34483. this.onGeometryUpdated(this, kind);
  34484. }
  34485. };
  34486. Geometry.prototype.load = function (scene, onLoaded) {
  34487. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  34488. return;
  34489. }
  34490. if (this.isReady()) {
  34491. if (onLoaded) {
  34492. onLoaded();
  34493. }
  34494. return;
  34495. }
  34496. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  34497. this._queueLoad(scene, onLoaded);
  34498. };
  34499. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  34500. var _this = this;
  34501. scene._addPendingData(this);
  34502. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  34503. _this._delayLoadingFunction(JSON.parse(data), _this);
  34504. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34505. _this._delayInfo = [];
  34506. scene._removePendingData(_this);
  34507. var meshes = _this._meshes;
  34508. var numOfMeshes = meshes.length;
  34509. for (var index = 0; index < numOfMeshes; index++) {
  34510. _this._applyToMesh(meshes[index]);
  34511. }
  34512. if (onLoaded) {
  34513. onLoaded();
  34514. }
  34515. }, function () { }, scene.database);
  34516. };
  34517. /**
  34518. * Invert the geometry to move from a right handed system to a left handed one.
  34519. */
  34520. Geometry.prototype.toLeftHanded = function () {
  34521. // Flip faces
  34522. var tIndices = this.getIndices(false);
  34523. if (tIndices != null && tIndices.length > 0) {
  34524. for (var i = 0; i < tIndices.length; i += 3) {
  34525. var tTemp = tIndices[i + 0];
  34526. tIndices[i + 0] = tIndices[i + 2];
  34527. tIndices[i + 2] = tTemp;
  34528. }
  34529. this.setIndices(tIndices);
  34530. }
  34531. // Negate position.z
  34532. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  34533. if (tPositions != null && tPositions.length > 0) {
  34534. for (var i = 0; i < tPositions.length; i += 3) {
  34535. tPositions[i + 2] = -tPositions[i + 2];
  34536. }
  34537. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  34538. }
  34539. // Negate normal.z
  34540. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  34541. if (tNormals != null && tNormals.length > 0) {
  34542. for (var i = 0; i < tNormals.length; i += 3) {
  34543. tNormals[i + 2] = -tNormals[i + 2];
  34544. }
  34545. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  34546. }
  34547. };
  34548. Geometry.prototype.isDisposed = function () {
  34549. return this._isDisposed;
  34550. };
  34551. Geometry.prototype.dispose = function () {
  34552. var meshes = this._meshes;
  34553. var numOfMeshes = meshes.length;
  34554. var index;
  34555. for (index = 0; index < numOfMeshes; index++) {
  34556. this.releaseForMesh(meshes[index]);
  34557. }
  34558. this._meshes = [];
  34559. for (var kind in this._vertexBuffers) {
  34560. this._vertexBuffers[kind].dispose();
  34561. }
  34562. this._vertexBuffers = {};
  34563. this._totalVertices = 0;
  34564. if (this._indexBuffer) {
  34565. this._engine._releaseBuffer(this._indexBuffer);
  34566. }
  34567. this._indexBuffer = null;
  34568. this._indices = [];
  34569. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34570. this.delayLoadingFile = null;
  34571. this._delayLoadingFunction = null;
  34572. this._delayInfo = [];
  34573. this._boundingInfo = null;
  34574. this._scene.removeGeometry(this);
  34575. this._isDisposed = true;
  34576. };
  34577. Geometry.prototype.copy = function (id) {
  34578. var vertexData = new BABYLON.VertexData();
  34579. vertexData.indices = [];
  34580. var indices = this.getIndices();
  34581. for (var index = 0; index < indices.length; index++) {
  34582. vertexData.indices.push(indices[index]);
  34583. }
  34584. var updatable = false;
  34585. var stopChecking = false;
  34586. var kind;
  34587. for (kind in this._vertexBuffers) {
  34588. // using slice() to make a copy of the array and not just reference it
  34589. var data = this.getVerticesData(kind);
  34590. if (data instanceof Float32Array) {
  34591. vertexData.set(new Float32Array(data), kind);
  34592. }
  34593. else {
  34594. vertexData.set(data.slice(0), kind);
  34595. }
  34596. if (!stopChecking) {
  34597. updatable = this.getVertexBuffer(kind).isUpdatable();
  34598. stopChecking = !updatable;
  34599. }
  34600. }
  34601. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  34602. geometry.delayLoadState = this.delayLoadState;
  34603. geometry.delayLoadingFile = this.delayLoadingFile;
  34604. geometry._delayLoadingFunction = this._delayLoadingFunction;
  34605. for (kind in this._delayInfo) {
  34606. geometry._delayInfo = geometry._delayInfo || [];
  34607. geometry._delayInfo.push(kind);
  34608. }
  34609. // Bounding info
  34610. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34611. return geometry;
  34612. };
  34613. Geometry.prototype.serialize = function () {
  34614. var serializationObject = {};
  34615. serializationObject.id = this.id;
  34616. if (BABYLON.Tags.HasTags(this)) {
  34617. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34618. }
  34619. return serializationObject;
  34620. };
  34621. Geometry.prototype.serializeVerticeData = function () {
  34622. var serializationObject = this.serialize();
  34623. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34624. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34625. }
  34626. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34627. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34628. }
  34629. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34630. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34631. }
  34632. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34633. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  34634. }
  34635. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  34636. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  34637. }
  34638. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  34639. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  34640. }
  34641. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  34642. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  34643. }
  34644. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  34645. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  34646. }
  34647. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34648. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  34649. }
  34650. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34651. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34652. serializationObject.matricesIndices._isExpanded = true;
  34653. }
  34654. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34655. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34656. }
  34657. serializationObject.indices = this.getIndices();
  34658. return serializationObject;
  34659. };
  34660. // Statics
  34661. Geometry.ExtractFromMesh = function (mesh, id) {
  34662. var geometry = mesh._geometry;
  34663. if (!geometry) {
  34664. return null;
  34665. }
  34666. return geometry.copy(id);
  34667. };
  34668. /**
  34669. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  34670. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  34671. * Be aware Math.random() could cause collisions, but:
  34672. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  34673. */
  34674. Geometry.RandomId = function () {
  34675. return BABYLON.Tools.RandomId();
  34676. };
  34677. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  34678. var scene = mesh.getScene();
  34679. // Geometry
  34680. var geometryId = parsedGeometry.geometryId;
  34681. if (geometryId) {
  34682. var geometry = scene.getGeometryByID(geometryId);
  34683. if (geometry) {
  34684. geometry.applyToMesh(mesh);
  34685. }
  34686. }
  34687. else if (parsedGeometry instanceof ArrayBuffer) {
  34688. var binaryInfo = mesh._binaryInfo;
  34689. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  34690. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  34691. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  34692. }
  34693. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  34694. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  34695. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  34696. }
  34697. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  34698. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  34699. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  34700. }
  34701. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  34702. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  34703. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  34704. }
  34705. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  34706. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  34707. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  34708. }
  34709. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  34710. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  34711. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  34712. }
  34713. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  34714. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  34715. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  34716. }
  34717. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  34718. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  34719. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  34720. }
  34721. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  34722. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  34723. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  34724. }
  34725. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  34726. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  34727. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  34728. }
  34729. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  34730. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  34731. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  34732. }
  34733. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  34734. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  34735. mesh.setIndices(indicesData);
  34736. }
  34737. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  34738. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  34739. mesh.subMeshes = [];
  34740. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  34741. var materialIndex = subMeshesData[(i * 5) + 0];
  34742. var verticesStart = subMeshesData[(i * 5) + 1];
  34743. var verticesCount = subMeshesData[(i * 5) + 2];
  34744. var indexStart = subMeshesData[(i * 5) + 3];
  34745. var indexCount = subMeshesData[(i * 5) + 4];
  34746. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  34747. }
  34748. }
  34749. }
  34750. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  34751. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  34752. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  34753. if (parsedGeometry.uvs) {
  34754. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  34755. }
  34756. if (parsedGeometry.uvs2) {
  34757. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  34758. }
  34759. if (parsedGeometry.uvs3) {
  34760. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  34761. }
  34762. if (parsedGeometry.uvs4) {
  34763. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  34764. }
  34765. if (parsedGeometry.uvs5) {
  34766. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  34767. }
  34768. if (parsedGeometry.uvs6) {
  34769. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  34770. }
  34771. if (parsedGeometry.colors) {
  34772. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  34773. }
  34774. if (parsedGeometry.matricesIndices) {
  34775. if (!parsedGeometry.matricesIndices._isExpanded) {
  34776. var floatIndices = [];
  34777. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  34778. var matricesIndex = parsedGeometry.matricesIndices[i];
  34779. floatIndices.push(matricesIndex & 0x000000FF);
  34780. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34781. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34782. floatIndices.push(matricesIndex >> 24);
  34783. }
  34784. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  34785. }
  34786. else {
  34787. delete parsedGeometry.matricesIndices._isExpanded;
  34788. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  34789. }
  34790. }
  34791. if (parsedGeometry.matricesIndicesExtra) {
  34792. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  34793. var floatIndices = [];
  34794. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  34795. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  34796. floatIndices.push(matricesIndex & 0x000000FF);
  34797. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34798. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34799. floatIndices.push(matricesIndex >> 24);
  34800. }
  34801. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  34802. }
  34803. else {
  34804. delete parsedGeometry.matricesIndices._isExpanded;
  34805. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  34806. }
  34807. }
  34808. if (parsedGeometry.matricesWeights) {
  34809. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  34810. }
  34811. if (parsedGeometry.matricesWeightsExtra) {
  34812. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  34813. }
  34814. mesh.setIndices(parsedGeometry.indices);
  34815. }
  34816. // SubMeshes
  34817. if (parsedGeometry.subMeshes) {
  34818. mesh.subMeshes = [];
  34819. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  34820. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  34821. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  34822. }
  34823. }
  34824. // Flat shading
  34825. if (mesh._shouldGenerateFlatShading) {
  34826. mesh.convertToFlatShadedMesh();
  34827. delete mesh._shouldGenerateFlatShading;
  34828. }
  34829. // Update
  34830. mesh.computeWorldMatrix(true);
  34831. // Octree
  34832. if (scene['_selectionOctree']) {
  34833. scene['_selectionOctree'].addMesh(mesh);
  34834. }
  34835. };
  34836. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  34837. if (scene.getGeometryByID(parsedVertexData.id)) {
  34838. return null; // null since geometry could be something else than a box...
  34839. }
  34840. var geometry = new Geometry(parsedVertexData.id, scene);
  34841. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  34842. if (parsedVertexData.delayLoadingFile) {
  34843. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  34844. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  34845. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  34846. geometry._delayInfo = [];
  34847. if (parsedVertexData.hasUVs) {
  34848. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  34849. }
  34850. if (parsedVertexData.hasUVs2) {
  34851. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  34852. }
  34853. if (parsedVertexData.hasUVs3) {
  34854. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  34855. }
  34856. if (parsedVertexData.hasUVs4) {
  34857. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  34858. }
  34859. if (parsedVertexData.hasUVs5) {
  34860. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  34861. }
  34862. if (parsedVertexData.hasUVs6) {
  34863. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  34864. }
  34865. if (parsedVertexData.hasColors) {
  34866. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  34867. }
  34868. if (parsedVertexData.hasMatricesIndices) {
  34869. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34870. }
  34871. if (parsedVertexData.hasMatricesWeights) {
  34872. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34873. }
  34874. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  34875. }
  34876. else {
  34877. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  34878. }
  34879. scene.pushGeometry(geometry, true);
  34880. return geometry;
  34881. };
  34882. return Geometry;
  34883. })();
  34884. BABYLON.Geometry = Geometry;
  34885. /////// Primitives //////////////////////////////////////////////
  34886. var Geometry;
  34887. (function (Geometry) {
  34888. var Primitives;
  34889. (function (Primitives) {
  34890. /// Abstract class
  34891. var _Primitive = (function (_super) {
  34892. __extends(_Primitive, _super);
  34893. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  34894. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  34895. this._canBeRegenerated = _canBeRegenerated;
  34896. this._beingRegenerated = true;
  34897. this.regenerate();
  34898. this._beingRegenerated = false;
  34899. }
  34900. _Primitive.prototype.canBeRegenerated = function () {
  34901. return this._canBeRegenerated;
  34902. };
  34903. _Primitive.prototype.regenerate = function () {
  34904. if (!this._canBeRegenerated) {
  34905. return;
  34906. }
  34907. this._beingRegenerated = true;
  34908. this.setAllVerticesData(this._regenerateVertexData(), false);
  34909. this._beingRegenerated = false;
  34910. };
  34911. _Primitive.prototype.asNewGeometry = function (id) {
  34912. return _super.prototype.copy.call(this, id);
  34913. };
  34914. // overrides
  34915. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  34916. if (!this._beingRegenerated) {
  34917. return;
  34918. }
  34919. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  34920. };
  34921. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  34922. if (!this._beingRegenerated) {
  34923. return;
  34924. }
  34925. _super.prototype.setVerticesData.call(this, kind, data, false);
  34926. };
  34927. // to override
  34928. // protected
  34929. _Primitive.prototype._regenerateVertexData = function () {
  34930. throw new Error("Abstract method");
  34931. };
  34932. _Primitive.prototype.copy = function (id) {
  34933. throw new Error("Must be overriden in sub-classes.");
  34934. };
  34935. _Primitive.prototype.serialize = function () {
  34936. var serializationObject = _super.prototype.serialize.call(this);
  34937. serializationObject.canBeRegenerated = this.canBeRegenerated();
  34938. return serializationObject;
  34939. };
  34940. return _Primitive;
  34941. })(Geometry);
  34942. Primitives._Primitive = _Primitive;
  34943. var Ribbon = (function (_super) {
  34944. __extends(Ribbon, _super);
  34945. // Members
  34946. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  34947. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34948. _super.call(this, id, scene, canBeRegenerated, mesh);
  34949. this.pathArray = pathArray;
  34950. this.closeArray = closeArray;
  34951. this.closePath = closePath;
  34952. this.offset = offset;
  34953. this.side = side;
  34954. }
  34955. Ribbon.prototype._regenerateVertexData = function () {
  34956. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  34957. };
  34958. Ribbon.prototype.copy = function (id) {
  34959. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  34960. };
  34961. return Ribbon;
  34962. })(_Primitive);
  34963. Primitives.Ribbon = Ribbon;
  34964. var Box = (function (_super) {
  34965. __extends(Box, _super);
  34966. // Members
  34967. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  34968. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34969. _super.call(this, id, scene, canBeRegenerated, mesh);
  34970. this.size = size;
  34971. this.side = side;
  34972. }
  34973. Box.prototype._regenerateVertexData = function () {
  34974. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  34975. };
  34976. Box.prototype.copy = function (id) {
  34977. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  34978. };
  34979. Box.prototype.serialize = function () {
  34980. var serializationObject = _super.prototype.serialize.call(this);
  34981. serializationObject.size = this.size;
  34982. return serializationObject;
  34983. };
  34984. Box.Parse = function (parsedBox, scene) {
  34985. if (scene.getGeometryByID(parsedBox.id)) {
  34986. return null; // null since geometry could be something else than a box...
  34987. }
  34988. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  34989. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  34990. scene.pushGeometry(box, true);
  34991. return box;
  34992. };
  34993. return Box;
  34994. })(_Primitive);
  34995. Primitives.Box = Box;
  34996. var Sphere = (function (_super) {
  34997. __extends(Sphere, _super);
  34998. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  34999. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35000. _super.call(this, id, scene, canBeRegenerated, mesh);
  35001. this.segments = segments;
  35002. this.diameter = diameter;
  35003. this.side = side;
  35004. }
  35005. Sphere.prototype._regenerateVertexData = function () {
  35006. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35007. };
  35008. Sphere.prototype.copy = function (id) {
  35009. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35010. };
  35011. Sphere.prototype.serialize = function () {
  35012. var serializationObject = _super.prototype.serialize.call(this);
  35013. serializationObject.segments = this.segments;
  35014. serializationObject.diameter = this.diameter;
  35015. return serializationObject;
  35016. };
  35017. Sphere.Parse = function (parsedSphere, scene) {
  35018. if (scene.getGeometryByID(parsedSphere.id)) {
  35019. return null; // null since geometry could be something else than a sphere...
  35020. }
  35021. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35022. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35023. scene.pushGeometry(sphere, true);
  35024. return sphere;
  35025. };
  35026. return Sphere;
  35027. })(_Primitive);
  35028. Primitives.Sphere = Sphere;
  35029. var Disc = (function (_super) {
  35030. __extends(Disc, _super);
  35031. // Members
  35032. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  35033. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35034. _super.call(this, id, scene, canBeRegenerated, mesh);
  35035. this.radius = radius;
  35036. this.tessellation = tessellation;
  35037. this.side = side;
  35038. }
  35039. Disc.prototype._regenerateVertexData = function () {
  35040. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35041. };
  35042. Disc.prototype.copy = function (id) {
  35043. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35044. };
  35045. return Disc;
  35046. })(_Primitive);
  35047. Primitives.Disc = Disc;
  35048. var Cylinder = (function (_super) {
  35049. __extends(Cylinder, _super);
  35050. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  35051. if (subdivisions === void 0) { subdivisions = 1; }
  35052. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35053. _super.call(this, id, scene, canBeRegenerated, mesh);
  35054. this.height = height;
  35055. this.diameterTop = diameterTop;
  35056. this.diameterBottom = diameterBottom;
  35057. this.tessellation = tessellation;
  35058. this.subdivisions = subdivisions;
  35059. this.side = side;
  35060. }
  35061. Cylinder.prototype._regenerateVertexData = function () {
  35062. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  35063. };
  35064. Cylinder.prototype.copy = function (id) {
  35065. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  35066. };
  35067. Cylinder.prototype.serialize = function () {
  35068. var serializationObject = _super.prototype.serialize.call(this);
  35069. serializationObject.height = this.height;
  35070. serializationObject.diameterTop = this.diameterTop;
  35071. serializationObject.diameterBottom = this.diameterBottom;
  35072. serializationObject.tessellation = this.tessellation;
  35073. return serializationObject;
  35074. };
  35075. Cylinder.Parse = function (parsedCylinder, scene) {
  35076. if (scene.getGeometryByID(parsedCylinder.id)) {
  35077. return null; // null since geometry could be something else than a cylinder...
  35078. }
  35079. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  35080. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  35081. scene.pushGeometry(cylinder, true);
  35082. return cylinder;
  35083. };
  35084. return Cylinder;
  35085. })(_Primitive);
  35086. Primitives.Cylinder = Cylinder;
  35087. var Torus = (function (_super) {
  35088. __extends(Torus, _super);
  35089. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  35090. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35091. _super.call(this, id, scene, canBeRegenerated, mesh);
  35092. this.diameter = diameter;
  35093. this.thickness = thickness;
  35094. this.tessellation = tessellation;
  35095. this.side = side;
  35096. }
  35097. Torus.prototype._regenerateVertexData = function () {
  35098. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  35099. };
  35100. Torus.prototype.copy = function (id) {
  35101. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  35102. };
  35103. Torus.prototype.serialize = function () {
  35104. var serializationObject = _super.prototype.serialize.call(this);
  35105. serializationObject.diameter = this.diameter;
  35106. serializationObject.thickness = this.thickness;
  35107. serializationObject.tessellation = this.tessellation;
  35108. return serializationObject;
  35109. };
  35110. Torus.Parse = function (parsedTorus, scene) {
  35111. if (scene.getGeometryByID(parsedTorus.id)) {
  35112. return null; // null since geometry could be something else than a torus...
  35113. }
  35114. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  35115. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  35116. scene.pushGeometry(torus, true);
  35117. return torus;
  35118. };
  35119. return Torus;
  35120. })(_Primitive);
  35121. Primitives.Torus = Torus;
  35122. var Ground = (function (_super) {
  35123. __extends(Ground, _super);
  35124. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  35125. _super.call(this, id, scene, canBeRegenerated, mesh);
  35126. this.width = width;
  35127. this.height = height;
  35128. this.subdivisions = subdivisions;
  35129. }
  35130. Ground.prototype._regenerateVertexData = function () {
  35131. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  35132. };
  35133. Ground.prototype.copy = function (id) {
  35134. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  35135. };
  35136. Ground.prototype.serialize = function () {
  35137. var serializationObject = _super.prototype.serialize.call(this);
  35138. serializationObject.width = this.width;
  35139. serializationObject.height = this.height;
  35140. serializationObject.subdivisions = this.subdivisions;
  35141. return serializationObject;
  35142. };
  35143. Ground.Parse = function (parsedGround, scene) {
  35144. if (scene.getGeometryByID(parsedGround.id)) {
  35145. return null; // null since geometry could be something else than a ground...
  35146. }
  35147. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  35148. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  35149. scene.pushGeometry(ground, true);
  35150. return ground;
  35151. };
  35152. return Ground;
  35153. })(_Primitive);
  35154. Primitives.Ground = Ground;
  35155. var TiledGround = (function (_super) {
  35156. __extends(TiledGround, _super);
  35157. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  35158. _super.call(this, id, scene, canBeRegenerated, mesh);
  35159. this.xmin = xmin;
  35160. this.zmin = zmin;
  35161. this.xmax = xmax;
  35162. this.zmax = zmax;
  35163. this.subdivisions = subdivisions;
  35164. this.precision = precision;
  35165. }
  35166. TiledGround.prototype._regenerateVertexData = function () {
  35167. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  35168. };
  35169. TiledGround.prototype.copy = function (id) {
  35170. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  35171. };
  35172. return TiledGround;
  35173. })(_Primitive);
  35174. Primitives.TiledGround = TiledGround;
  35175. var Plane = (function (_super) {
  35176. __extends(Plane, _super);
  35177. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  35178. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35179. _super.call(this, id, scene, canBeRegenerated, mesh);
  35180. this.size = size;
  35181. this.side = side;
  35182. }
  35183. Plane.prototype._regenerateVertexData = function () {
  35184. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  35185. };
  35186. Plane.prototype.copy = function (id) {
  35187. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35188. };
  35189. Plane.prototype.serialize = function () {
  35190. var serializationObject = _super.prototype.serialize.call(this);
  35191. serializationObject.size = this.size;
  35192. return serializationObject;
  35193. };
  35194. Plane.Parse = function (parsedPlane, scene) {
  35195. if (scene.getGeometryByID(parsedPlane.id)) {
  35196. return null; // null since geometry could be something else than a ground...
  35197. }
  35198. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  35199. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  35200. scene.pushGeometry(plane, true);
  35201. return plane;
  35202. };
  35203. return Plane;
  35204. })(_Primitive);
  35205. Primitives.Plane = Plane;
  35206. var TorusKnot = (function (_super) {
  35207. __extends(TorusKnot, _super);
  35208. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  35209. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35210. _super.call(this, id, scene, canBeRegenerated, mesh);
  35211. this.radius = radius;
  35212. this.tube = tube;
  35213. this.radialSegments = radialSegments;
  35214. this.tubularSegments = tubularSegments;
  35215. this.p = p;
  35216. this.q = q;
  35217. this.side = side;
  35218. }
  35219. TorusKnot.prototype._regenerateVertexData = function () {
  35220. 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 });
  35221. };
  35222. TorusKnot.prototype.copy = function (id) {
  35223. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  35224. };
  35225. TorusKnot.prototype.serialize = function () {
  35226. var serializationObject = _super.prototype.serialize.call(this);
  35227. serializationObject.radius = this.radius;
  35228. serializationObject.tube = this.tube;
  35229. serializationObject.radialSegments = this.radialSegments;
  35230. serializationObject.tubularSegments = this.tubularSegments;
  35231. serializationObject.p = this.p;
  35232. serializationObject.q = this.q;
  35233. return serializationObject;
  35234. };
  35235. ;
  35236. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  35237. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  35238. return null; // null since geometry could be something else than a ground...
  35239. }
  35240. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  35241. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  35242. scene.pushGeometry(torusKnot, true);
  35243. return torusKnot;
  35244. };
  35245. return TorusKnot;
  35246. })(_Primitive);
  35247. Primitives.TorusKnot = TorusKnot;
  35248. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  35249. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  35250. })(BABYLON || (BABYLON = {}));
  35251. var BABYLON;
  35252. (function (BABYLON) {
  35253. var GroundMesh = (function (_super) {
  35254. __extends(GroundMesh, _super);
  35255. function GroundMesh(name, scene) {
  35256. _super.call(this, name, scene);
  35257. this.generateOctree = false;
  35258. this._worldInverse = new BABYLON.Matrix();
  35259. }
  35260. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  35261. get: function () {
  35262. return Math.min(this._subdivisionsX, this._subdivisionsY);
  35263. },
  35264. enumerable: true,
  35265. configurable: true
  35266. });
  35267. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  35268. get: function () {
  35269. return this._subdivisionsX;
  35270. },
  35271. enumerable: true,
  35272. configurable: true
  35273. });
  35274. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  35275. get: function () {
  35276. return this._subdivisionsY;
  35277. },
  35278. enumerable: true,
  35279. configurable: true
  35280. });
  35281. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  35282. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  35283. this._subdivisionsX = chunksCount;
  35284. this._subdivisionsY = chunksCount;
  35285. this.subdivide(chunksCount);
  35286. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  35287. };
  35288. /**
  35289. * Returns a height (y) value in the Worl system :
  35290. * the ground altitude at the coordinates (x, z) expressed in the World system.
  35291. * Returns the ground y position if (x, z) are outside the ground surface.
  35292. * Not pertinent if the ground is rotated.
  35293. */
  35294. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  35295. // express x and y in the ground local system
  35296. x -= this.position.x;
  35297. z -= this.position.z;
  35298. x /= this.scaling.x;
  35299. z /= this.scaling.z;
  35300. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  35301. return this.position.y;
  35302. }
  35303. if (!this._heightQuads || this._heightQuads.length == 0) {
  35304. this._initHeightQuads();
  35305. this._computeHeightQuads();
  35306. }
  35307. var facet = this._getFacetAt(x, z);
  35308. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  35309. // return y in the World system
  35310. return y * this.scaling.y + this.position.y;
  35311. };
  35312. /**
  35313. * Returns a normalized vector (Vector3) orthogonal to the ground
  35314. * at the ground coordinates (x, z) expressed in the World system.
  35315. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  35316. * Not pertinent if the ground is rotated.
  35317. */
  35318. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  35319. var normal = new BABYLON.Vector3(0, 1, 0);
  35320. this.getNormalAtCoordinatesToRef(x, z, normal);
  35321. return normal;
  35322. };
  35323. /**
  35324. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  35325. * at the ground coordinates (x, z) expressed in the World system.
  35326. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  35327. * Not pertinent if the ground is rotated.
  35328. */
  35329. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  35330. // express x and y in the ground local system
  35331. x -= this.position.x;
  35332. z -= this.position.z;
  35333. x /= this.scaling.x;
  35334. z /= this.scaling.z;
  35335. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  35336. return;
  35337. }
  35338. if (!this._heightQuads || this._heightQuads.length == 0) {
  35339. this._initHeightQuads();
  35340. this._computeHeightQuads();
  35341. }
  35342. var facet = this._getFacetAt(x, z);
  35343. ref.x = facet.x;
  35344. ref.y = facet.y;
  35345. ref.z = facet.z;
  35346. };
  35347. /**
  35348. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  35349. * if the ground has been updated.
  35350. * This can be used in the render loop
  35351. */
  35352. GroundMesh.prototype.updateCoordinateHeights = function () {
  35353. if (!this._heightQuads || this._heightQuads.length == 0) {
  35354. this._initHeightQuads();
  35355. }
  35356. this._computeHeightQuads();
  35357. };
  35358. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  35359. GroundMesh.prototype._getFacetAt = function (x, z) {
  35360. // retrieve col and row from x, z coordinates in the ground local system
  35361. var subdivisionsX = this._subdivisionsX;
  35362. var subdivisionsY = this._subdivisionsY;
  35363. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  35364. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  35365. var quad = this._heightQuads[row * this._subdivisionsX + col];
  35366. var facet;
  35367. if (z < quad.slope.x * x + quad.slope.y) {
  35368. facet = quad.facet1;
  35369. }
  35370. else {
  35371. facet = quad.facet2;
  35372. }
  35373. return facet;
  35374. };
  35375. // Creates and populates the heightMap array with "facet" elements :
  35376. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  35377. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  35378. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  35379. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  35380. GroundMesh.prototype._initHeightQuads = function () {
  35381. var subdivisionsX = this._subdivisionsX;
  35382. var subdivisionsY = this._subdivisionsY;
  35383. this._heightQuads = new Array();
  35384. for (var row = 0; row < subdivisionsY; row++) {
  35385. for (var col = 0; col < subdivisionsX; col++) {
  35386. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  35387. this._heightQuads[row * subdivisionsX + col] = quad;
  35388. }
  35389. }
  35390. };
  35391. // Compute each quad element values and update the the heightMap array :
  35392. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  35393. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  35394. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  35395. GroundMesh.prototype._computeHeightQuads = function () {
  35396. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35397. var v1 = BABYLON.Tmp.Vector3[3];
  35398. var v2 = BABYLON.Tmp.Vector3[2];
  35399. var v3 = BABYLON.Tmp.Vector3[1];
  35400. var v4 = BABYLON.Tmp.Vector3[0];
  35401. var v1v2 = BABYLON.Tmp.Vector3[4];
  35402. var v1v3 = BABYLON.Tmp.Vector3[5];
  35403. var v1v4 = BABYLON.Tmp.Vector3[6];
  35404. var norm1 = BABYLON.Tmp.Vector3[7];
  35405. var norm2 = BABYLON.Tmp.Vector3[8];
  35406. var i = 0;
  35407. var j = 0;
  35408. var k = 0;
  35409. var cd = 0; // 2D slope coefficient : z = cd * x + h
  35410. var h = 0;
  35411. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  35412. var d2 = 0;
  35413. var subdivisionsX = this._subdivisionsX;
  35414. var subdivisionsY = this._subdivisionsY;
  35415. for (var row = 0; row < subdivisionsY; row++) {
  35416. for (var col = 0; col < subdivisionsX; col++) {
  35417. i = col * 3;
  35418. j = row * (subdivisionsX + 1) * 3;
  35419. k = (row + 1) * (subdivisionsX + 1) * 3;
  35420. v1.x = positions[j + i];
  35421. v1.y = positions[j + i + 1];
  35422. v1.z = positions[j + i + 2];
  35423. v2.x = positions[j + i + 3];
  35424. v2.y = positions[j + i + 4];
  35425. v2.z = positions[j + i + 5];
  35426. v3.x = positions[k + i];
  35427. v3.y = positions[k + i + 1];
  35428. v3.z = positions[k + i + 2];
  35429. v4.x = positions[k + i + 3];
  35430. v4.y = positions[k + i + 4];
  35431. v4.z = positions[k + i + 5];
  35432. // 2D slope V1V4
  35433. cd = (v4.z - v1.z) / (v4.x - v1.x);
  35434. h = v1.z - cd * v1.x; // v1 belongs to the slope
  35435. // facet equations :
  35436. // we compute each facet normal vector
  35437. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  35438. // we compute the value d by applying the equation to v1 which belongs to the plane
  35439. // then we store the facet equation in a Vector4
  35440. v2.subtractToRef(v1, v1v2);
  35441. v3.subtractToRef(v1, v1v3);
  35442. v4.subtractToRef(v1, v1v4);
  35443. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  35444. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  35445. norm1.normalize();
  35446. norm2.normalize();
  35447. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  35448. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  35449. var quad = this._heightQuads[row * subdivisionsX + col];
  35450. quad.slope.copyFromFloats(cd, h);
  35451. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  35452. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  35453. }
  35454. }
  35455. };
  35456. return GroundMesh;
  35457. })(BABYLON.Mesh);
  35458. BABYLON.GroundMesh = GroundMesh;
  35459. })(BABYLON || (BABYLON = {}));
  35460. var BABYLON;
  35461. (function (BABYLON) {
  35462. var LinesMesh = (function (_super) {
  35463. __extends(LinesMesh, _super);
  35464. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  35465. if (parent === void 0) { parent = null; }
  35466. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  35467. this.color = new BABYLON.Color3(1, 1, 1);
  35468. this.alpha = 1;
  35469. this._positionBuffer = {};
  35470. if (source) {
  35471. this.color = source.color.clone();
  35472. this.alpha = source.alpha;
  35473. }
  35474. this._intersectionThreshold = 0.1;
  35475. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  35476. attributes: [BABYLON.VertexBuffer.PositionKind],
  35477. uniforms: ["worldViewProjection", "color"],
  35478. needAlphaBlending: true
  35479. });
  35480. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  35481. }
  35482. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  35483. /**
  35484. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  35485. * This margin is expressed in world space coordinates, so its value may vary.
  35486. * Default value is 0.1
  35487. * @returns the intersection Threshold value.
  35488. */
  35489. get: function () {
  35490. return this._intersectionThreshold;
  35491. },
  35492. /**
  35493. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  35494. * This margin is expressed in world space coordinates, so its value may vary.
  35495. * @param value the new threshold to apply
  35496. */
  35497. set: function (value) {
  35498. if (this._intersectionThreshold === value) {
  35499. return;
  35500. }
  35501. this._intersectionThreshold = value;
  35502. if (this.geometry) {
  35503. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  35504. }
  35505. },
  35506. enumerable: true,
  35507. configurable: true
  35508. });
  35509. Object.defineProperty(LinesMesh.prototype, "material", {
  35510. get: function () {
  35511. return this._colorShader;
  35512. },
  35513. enumerable: true,
  35514. configurable: true
  35515. });
  35516. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  35517. get: function () {
  35518. return false;
  35519. },
  35520. enumerable: true,
  35521. configurable: true
  35522. });
  35523. LinesMesh.prototype.createInstance = function (name) {
  35524. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  35525. return null;
  35526. };
  35527. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  35528. var engine = this.getScene().getEngine();
  35529. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  35530. // VBOs
  35531. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  35532. // Color
  35533. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  35534. };
  35535. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  35536. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  35537. return;
  35538. }
  35539. var engine = this.getScene().getEngine();
  35540. // Draw order
  35541. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  35542. };
  35543. LinesMesh.prototype.dispose = function (doNotRecurse) {
  35544. this._colorShader.dispose();
  35545. _super.prototype.dispose.call(this, doNotRecurse);
  35546. };
  35547. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  35548. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  35549. };
  35550. return LinesMesh;
  35551. })(BABYLON.Mesh);
  35552. BABYLON.LinesMesh = LinesMesh;
  35553. })(BABYLON || (BABYLON = {}));
  35554. var BABYLON;
  35555. (function (BABYLON) {
  35556. var DefaultLoadingScreen = (function () {
  35557. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  35558. var _this = this;
  35559. if (_loadingText === void 0) { _loadingText = ""; }
  35560. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  35561. this._renderingCanvas = _renderingCanvas;
  35562. this._loadingText = _loadingText;
  35563. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  35564. // Resize
  35565. this._resizeLoadingUI = function () {
  35566. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  35567. _this._loadingDiv.style.position = "absolute";
  35568. _this._loadingDiv.style.left = canvasRect.left + "px";
  35569. _this._loadingDiv.style.top = canvasRect.top + "px";
  35570. _this._loadingDiv.style.width = canvasRect.width + "px";
  35571. _this._loadingDiv.style.height = canvasRect.height + "px";
  35572. };
  35573. }
  35574. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  35575. var _this = this;
  35576. if (this._loadingDiv) {
  35577. // Do not add a loading screen if there is already one
  35578. return;
  35579. }
  35580. this._loadingDiv = document.createElement("div");
  35581. this._loadingDiv.id = "babylonjsLoadingDiv";
  35582. this._loadingDiv.style.opacity = "0";
  35583. this._loadingDiv.style.transition = "opacity 1.5s ease";
  35584. // Loading text
  35585. this._loadingTextDiv = document.createElement("div");
  35586. this._loadingTextDiv.style.position = "absolute";
  35587. this._loadingTextDiv.style.left = "0";
  35588. this._loadingTextDiv.style.top = "50%";
  35589. this._loadingTextDiv.style.marginTop = "80px";
  35590. this._loadingTextDiv.style.width = "100%";
  35591. this._loadingTextDiv.style.height = "20px";
  35592. this._loadingTextDiv.style.fontFamily = "Arial";
  35593. this._loadingTextDiv.style.fontSize = "14px";
  35594. this._loadingTextDiv.style.color = "white";
  35595. this._loadingTextDiv.style.textAlign = "center";
  35596. this._loadingTextDiv.innerHTML = "Loading";
  35597. this._loadingDiv.appendChild(this._loadingTextDiv);
  35598. //set the predefined text
  35599. this._loadingTextDiv.innerHTML = this._loadingText;
  35600. // Loading img
  35601. var imgBack = new Image();
  35602. 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==";
  35603. imgBack.style.position = "absolute";
  35604. imgBack.style.left = "50%";
  35605. imgBack.style.top = "50%";
  35606. imgBack.style.marginLeft = "-50px";
  35607. imgBack.style.marginTop = "-50px";
  35608. imgBack.style.transition = "transform 1.0s ease";
  35609. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  35610. var deg = 360;
  35611. var onTransitionEnd = function () {
  35612. deg += 360;
  35613. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  35614. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  35615. };
  35616. imgBack.addEventListener("transitionend", onTransitionEnd);
  35617. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  35618. this._loadingDiv.appendChild(imgBack);
  35619. // front image
  35620. var imgFront = new Image();
  35621. 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=";
  35622. imgFront.style.position = "absolute";
  35623. imgFront.style.left = "50%";
  35624. imgFront.style.top = "50%";
  35625. imgFront.style.marginLeft = "-50px";
  35626. imgFront.style.marginTop = "-50px";
  35627. this._loadingDiv.appendChild(imgFront);
  35628. this._resizeLoadingUI();
  35629. window.addEventListener("resize", this._resizeLoadingUI);
  35630. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  35631. document.body.appendChild(this._loadingDiv);
  35632. setTimeout(function () {
  35633. _this._loadingDiv.style.opacity = "1";
  35634. imgBack.style.transform = "rotateZ(360deg)";
  35635. imgBack.style.webkitTransform = "rotateZ(360deg)";
  35636. }, 0);
  35637. };
  35638. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  35639. var _this = this;
  35640. if (!this._loadingDiv) {
  35641. return;
  35642. }
  35643. var onTransitionEnd = function () {
  35644. if (!_this._loadingDiv) {
  35645. return;
  35646. }
  35647. document.body.removeChild(_this._loadingDiv);
  35648. window.removeEventListener("resize", _this._resizeLoadingUI);
  35649. _this._loadingDiv = null;
  35650. };
  35651. this._loadingDiv.style.opacity = "0";
  35652. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  35653. };
  35654. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  35655. set: function (text) {
  35656. this._loadingText = text;
  35657. if (this._loadingTextDiv) {
  35658. this._loadingTextDiv.innerHTML = this._loadingText;
  35659. }
  35660. },
  35661. enumerable: true,
  35662. configurable: true
  35663. });
  35664. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  35665. get: function () {
  35666. return this._loadingDivBackgroundColor;
  35667. },
  35668. set: function (color) {
  35669. this._loadingDivBackgroundColor = color;
  35670. if (!this._loadingDiv) {
  35671. return;
  35672. }
  35673. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  35674. },
  35675. enumerable: true,
  35676. configurable: true
  35677. });
  35678. return DefaultLoadingScreen;
  35679. })();
  35680. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  35681. })(BABYLON || (BABYLON = {}));
  35682. var BABYLON;
  35683. (function (BABYLON) {
  35684. var AudioEngine = (function () {
  35685. function AudioEngine() {
  35686. this._audioContext = null;
  35687. this._audioContextInitialized = false;
  35688. this.canUseWebAudio = false;
  35689. this.WarnedWebAudioUnsupported = false;
  35690. this.unlocked = false;
  35691. this.isMP3supported = false;
  35692. this.isOGGsupported = false;
  35693. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  35694. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  35695. this.canUseWebAudio = true;
  35696. }
  35697. var audioElem = document.createElement('audio');
  35698. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  35699. this.isMP3supported = true;
  35700. }
  35701. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  35702. this.isOGGsupported = true;
  35703. }
  35704. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  35705. this._unlockiOSaudio();
  35706. }
  35707. else {
  35708. this.unlocked = true;
  35709. }
  35710. }
  35711. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  35712. get: function () {
  35713. if (!this._audioContextInitialized) {
  35714. this._initializeAudioContext();
  35715. }
  35716. return this._audioContext;
  35717. },
  35718. enumerable: true,
  35719. configurable: true
  35720. });
  35721. AudioEngine.prototype._unlockiOSaudio = function () {
  35722. var _this = this;
  35723. var unlockaudio = function () {
  35724. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  35725. var source = _this.audioContext.createBufferSource();
  35726. source.buffer = buffer;
  35727. source.connect(_this.audioContext.destination);
  35728. source.start(0);
  35729. setTimeout(function () {
  35730. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  35731. _this.unlocked = true;
  35732. window.removeEventListener('touchend', unlockaudio, false);
  35733. if (_this.onAudioUnlocked) {
  35734. _this.onAudioUnlocked();
  35735. }
  35736. }
  35737. }, 0);
  35738. };
  35739. window.addEventListener('touchend', unlockaudio, false);
  35740. };
  35741. AudioEngine.prototype._initializeAudioContext = function () {
  35742. try {
  35743. if (this.canUseWebAudio) {
  35744. this._audioContext = new AudioContext();
  35745. // create a global volume gain node
  35746. this.masterGain = this._audioContext.createGain();
  35747. this.masterGain.gain.value = 1;
  35748. this.masterGain.connect(this._audioContext.destination);
  35749. this._audioContextInitialized = true;
  35750. }
  35751. }
  35752. catch (e) {
  35753. this.canUseWebAudio = false;
  35754. BABYLON.Tools.Error("Web Audio: " + e.message);
  35755. }
  35756. };
  35757. AudioEngine.prototype.dispose = function () {
  35758. if (this.canUseWebAudio && this._audioContextInitialized) {
  35759. if (this._connectedAnalyser) {
  35760. this._connectedAnalyser.stopDebugCanvas();
  35761. this._connectedAnalyser.dispose();
  35762. this.masterGain.disconnect();
  35763. this.masterGain.connect(this._audioContext.destination);
  35764. this._connectedAnalyser = null;
  35765. }
  35766. this.masterGain.gain.value = 1;
  35767. }
  35768. this.WarnedWebAudioUnsupported = false;
  35769. };
  35770. AudioEngine.prototype.getGlobalVolume = function () {
  35771. if (this.canUseWebAudio && this._audioContextInitialized) {
  35772. return this.masterGain.gain.value;
  35773. }
  35774. else {
  35775. return -1;
  35776. }
  35777. };
  35778. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  35779. if (this.canUseWebAudio && this._audioContextInitialized) {
  35780. this.masterGain.gain.value = newVolume;
  35781. }
  35782. };
  35783. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  35784. if (this._connectedAnalyser) {
  35785. this._connectedAnalyser.stopDebugCanvas();
  35786. }
  35787. if (this.canUseWebAudio && this._audioContextInitialized) {
  35788. this._connectedAnalyser = analyser;
  35789. this.masterGain.disconnect();
  35790. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  35791. }
  35792. };
  35793. return AudioEngine;
  35794. })();
  35795. BABYLON.AudioEngine = AudioEngine;
  35796. })(BABYLON || (BABYLON = {}));
  35797. var BABYLON;
  35798. (function (BABYLON) {
  35799. var Sound = (function () {
  35800. /**
  35801. * Create a sound and attach it to a scene
  35802. * @param name Name of your sound
  35803. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  35804. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  35805. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  35806. */
  35807. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  35808. var _this = this;
  35809. this.autoplay = false;
  35810. this.loop = false;
  35811. this.useCustomAttenuation = false;
  35812. this.spatialSound = false;
  35813. this.refDistance = 1;
  35814. this.rolloffFactor = 1;
  35815. this.maxDistance = 100;
  35816. this.distanceModel = "linear";
  35817. this._panningModel = "equalpower";
  35818. this._playbackRate = 1;
  35819. this._streaming = false;
  35820. this._startTime = 0;
  35821. this._startOffset = 0;
  35822. this._position = BABYLON.Vector3.Zero();
  35823. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  35824. this._volume = 1;
  35825. this._isLoaded = false;
  35826. this._isReadyToPlay = false;
  35827. this.isPlaying = false;
  35828. this.isPaused = false;
  35829. this._isDirectional = false;
  35830. // Used if you'd like to create a directional sound.
  35831. // If not set, the sound will be omnidirectional
  35832. this._coneInnerAngle = 360;
  35833. this._coneOuterAngle = 360;
  35834. this._coneOuterGain = 0;
  35835. this._isOutputConnected = false;
  35836. this._urlType = "Unknown";
  35837. this.name = name;
  35838. this._scene = scene;
  35839. this._readyToPlayCallback = readyToPlayCallback;
  35840. // Default custom attenuation function is a linear attenuation
  35841. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  35842. if (currentDistance < maxDistance) {
  35843. return currentVolume * (1 - currentDistance / maxDistance);
  35844. }
  35845. else {
  35846. return 0;
  35847. }
  35848. };
  35849. if (options) {
  35850. this.autoplay = options.autoplay || false;
  35851. this.loop = options.loop || false;
  35852. // if volume === 0, we need another way to check this option
  35853. if (options.volume !== undefined) {
  35854. this._volume = options.volume;
  35855. }
  35856. this.spatialSound = options.spatialSound || false;
  35857. this.maxDistance = options.maxDistance || 100;
  35858. this.useCustomAttenuation = options.useCustomAttenuation || false;
  35859. this.rolloffFactor = options.rolloffFactor || 1;
  35860. this.refDistance = options.refDistance || 1;
  35861. this.distanceModel = options.distanceModel || "linear";
  35862. this._playbackRate = options.playbackRate || 1;
  35863. this._streaming = options.streaming || false;
  35864. }
  35865. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35866. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  35867. this._soundGain.gain.value = this._volume;
  35868. this._inputAudioNode = this._soundGain;
  35869. this._ouputAudioNode = this._soundGain;
  35870. if (this.spatialSound) {
  35871. this._createSpatialParameters();
  35872. }
  35873. this._scene.mainSoundTrack.AddSound(this);
  35874. var validParameter = true;
  35875. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  35876. if (urlOrArrayBuffer) {
  35877. if (typeof (urlOrArrayBuffer) === "string")
  35878. this._urlType = "String";
  35879. if (Array.isArray(urlOrArrayBuffer))
  35880. this._urlType = "Array";
  35881. if (urlOrArrayBuffer instanceof ArrayBuffer)
  35882. this._urlType = "ArrayBuffer";
  35883. var urls = [];
  35884. var codecSupportedFound = false;
  35885. switch (this._urlType) {
  35886. case "ArrayBuffer":
  35887. if (urlOrArrayBuffer.byteLength > 0) {
  35888. codecSupportedFound = true;
  35889. this._soundLoaded(urlOrArrayBuffer);
  35890. }
  35891. break;
  35892. case "String":
  35893. urls.push(urlOrArrayBuffer);
  35894. case "Array":
  35895. if (urls.length === 0)
  35896. urls = urlOrArrayBuffer;
  35897. // If we found a supported format, we load it immediately and stop the loop
  35898. for (var i = 0; i < urls.length; i++) {
  35899. var url = urls[i];
  35900. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  35901. codecSupportedFound = true;
  35902. }
  35903. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  35904. codecSupportedFound = true;
  35905. }
  35906. if (url.indexOf(".wav", url.length - 4) !== -1) {
  35907. codecSupportedFound = true;
  35908. }
  35909. if (codecSupportedFound) {
  35910. // Loading sound using XHR2
  35911. if (!this._streaming) {
  35912. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  35913. }
  35914. else {
  35915. this._htmlAudioElement = new Audio(url);
  35916. this._htmlAudioElement.controls = false;
  35917. this._htmlAudioElement.loop = this.loop;
  35918. this._htmlAudioElement.crossOrigin = "anonymous";
  35919. this._htmlAudioElement.preload = "auto";
  35920. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  35921. _this._isReadyToPlay = true;
  35922. if (_this.autoplay) {
  35923. _this.play();
  35924. }
  35925. if (_this._readyToPlayCallback) {
  35926. _this._readyToPlayCallback();
  35927. }
  35928. });
  35929. document.body.appendChild(this._htmlAudioElement);
  35930. }
  35931. break;
  35932. }
  35933. }
  35934. break;
  35935. default:
  35936. validParameter = false;
  35937. break;
  35938. }
  35939. if (!validParameter) {
  35940. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  35941. }
  35942. else {
  35943. if (!codecSupportedFound) {
  35944. // Simulating a ready to play event to avoid breaking code path
  35945. if (this._readyToPlayCallback) {
  35946. window.setTimeout(function () {
  35947. _this._readyToPlayCallback();
  35948. }, 1000);
  35949. }
  35950. }
  35951. }
  35952. }
  35953. }
  35954. else {
  35955. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  35956. this._scene.mainSoundTrack.AddSound(this);
  35957. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  35958. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  35959. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  35960. }
  35961. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  35962. if (this._readyToPlayCallback) {
  35963. window.setTimeout(function () {
  35964. _this._readyToPlayCallback();
  35965. }, 1000);
  35966. }
  35967. }
  35968. }
  35969. Sound.prototype.dispose = function () {
  35970. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  35971. if (this.isPlaying) {
  35972. this.stop();
  35973. }
  35974. this._isReadyToPlay = false;
  35975. if (this.soundTrackId === -1) {
  35976. this._scene.mainSoundTrack.RemoveSound(this);
  35977. }
  35978. else {
  35979. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  35980. }
  35981. if (this._soundGain) {
  35982. this._soundGain.disconnect();
  35983. this._soundGain = null;
  35984. }
  35985. if (this._soundPanner) {
  35986. this._soundPanner.disconnect();
  35987. this._soundPanner = null;
  35988. }
  35989. if (this._soundSource) {
  35990. this._soundSource.disconnect();
  35991. this._soundSource = null;
  35992. }
  35993. this._audioBuffer = null;
  35994. if (this._htmlAudioElement) {
  35995. this._htmlAudioElement.pause();
  35996. this._htmlAudioElement.src = "";
  35997. document.body.removeChild(this._htmlAudioElement);
  35998. }
  35999. if (this._connectedMesh) {
  36000. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  36001. this._connectedMesh = null;
  36002. }
  36003. }
  36004. };
  36005. Sound.prototype._soundLoaded = function (audioData) {
  36006. var _this = this;
  36007. this._isLoaded = true;
  36008. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  36009. _this._audioBuffer = buffer;
  36010. _this._isReadyToPlay = true;
  36011. if (_this.autoplay) {
  36012. _this.play();
  36013. }
  36014. if (_this._readyToPlayCallback) {
  36015. _this._readyToPlayCallback();
  36016. }
  36017. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  36018. };
  36019. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  36020. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36021. this._audioBuffer = audioBuffer;
  36022. this._isReadyToPlay = true;
  36023. }
  36024. };
  36025. Sound.prototype.updateOptions = function (options) {
  36026. if (options) {
  36027. this.loop = options.loop || this.loop;
  36028. this.maxDistance = options.maxDistance || this.maxDistance;
  36029. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  36030. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  36031. this.refDistance = options.refDistance || this.refDistance;
  36032. this.distanceModel = options.distanceModel || this.distanceModel;
  36033. this._playbackRate = options.playbackRate || this._playbackRate;
  36034. this._updateSpatialParameters();
  36035. if (this.isPlaying) {
  36036. if (this._streaming) {
  36037. this._htmlAudioElement.playbackRate = this._playbackRate;
  36038. }
  36039. else {
  36040. this._soundSource.playbackRate.value = this._playbackRate;
  36041. }
  36042. }
  36043. }
  36044. };
  36045. Sound.prototype._createSpatialParameters = function () {
  36046. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36047. if (this._scene.headphone) {
  36048. this._panningModel = "HRTF";
  36049. }
  36050. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  36051. this._updateSpatialParameters();
  36052. this._soundPanner.connect(this._ouputAudioNode);
  36053. this._inputAudioNode = this._soundPanner;
  36054. }
  36055. };
  36056. Sound.prototype._updateSpatialParameters = function () {
  36057. if (this.spatialSound) {
  36058. if (this.useCustomAttenuation) {
  36059. // Tricks to disable in a way embedded Web Audio attenuation
  36060. this._soundPanner.distanceModel = "linear";
  36061. this._soundPanner.maxDistance = Number.MAX_VALUE;
  36062. this._soundPanner.refDistance = 1;
  36063. this._soundPanner.rolloffFactor = 1;
  36064. this._soundPanner.panningModel = this._panningModel;
  36065. }
  36066. else {
  36067. this._soundPanner.distanceModel = this.distanceModel;
  36068. this._soundPanner.maxDistance = this.maxDistance;
  36069. this._soundPanner.refDistance = this.refDistance;
  36070. this._soundPanner.rolloffFactor = this.rolloffFactor;
  36071. this._soundPanner.panningModel = this._panningModel;
  36072. }
  36073. }
  36074. };
  36075. Sound.prototype.switchPanningModelToHRTF = function () {
  36076. this._panningModel = "HRTF";
  36077. this._switchPanningModel();
  36078. };
  36079. Sound.prototype.switchPanningModelToEqualPower = function () {
  36080. this._panningModel = "equalpower";
  36081. this._switchPanningModel();
  36082. };
  36083. Sound.prototype._switchPanningModel = function () {
  36084. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  36085. this._soundPanner.panningModel = this._panningModel;
  36086. }
  36087. };
  36088. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  36089. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36090. if (this._isOutputConnected) {
  36091. this._ouputAudioNode.disconnect();
  36092. }
  36093. this._ouputAudioNode.connect(soundTrackAudioNode);
  36094. this._isOutputConnected = true;
  36095. }
  36096. };
  36097. /**
  36098. * Transform this sound into a directional source
  36099. * @param coneInnerAngle Size of the inner cone in degree
  36100. * @param coneOuterAngle Size of the outer cone in degree
  36101. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  36102. */
  36103. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  36104. if (coneOuterAngle < coneInnerAngle) {
  36105. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  36106. return;
  36107. }
  36108. this._coneInnerAngle = coneInnerAngle;
  36109. this._coneOuterAngle = coneOuterAngle;
  36110. this._coneOuterGain = coneOuterGain;
  36111. this._isDirectional = true;
  36112. if (this.isPlaying && this.loop) {
  36113. this.stop();
  36114. this.play();
  36115. }
  36116. };
  36117. Sound.prototype.setPosition = function (newPosition) {
  36118. this._position = newPosition;
  36119. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  36120. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  36121. }
  36122. };
  36123. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  36124. this._localDirection = newLocalDirection;
  36125. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  36126. this._updateDirection();
  36127. }
  36128. };
  36129. Sound.prototype._updateDirection = function () {
  36130. var mat = this._connectedMesh.getWorldMatrix();
  36131. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  36132. direction.normalize();
  36133. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  36134. };
  36135. Sound.prototype.updateDistanceFromListener = function () {
  36136. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  36137. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  36138. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  36139. }
  36140. };
  36141. Sound.prototype.setAttenuationFunction = function (callback) {
  36142. this._customAttenuationFunction = callback;
  36143. };
  36144. /**
  36145. * Play the sound
  36146. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  36147. * @param offset (optional) Start the sound setting it at a specific time
  36148. */
  36149. Sound.prototype.play = function (time, offset) {
  36150. var _this = this;
  36151. if (this._isReadyToPlay && this._scene.audioEnabled) {
  36152. try {
  36153. if (this._startOffset < 0) {
  36154. time = -this._startOffset;
  36155. this._startOffset = 0;
  36156. }
  36157. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  36158. if (!this._soundSource || !this._streamingSource) {
  36159. if (this.spatialSound) {
  36160. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  36161. if (this._isDirectional) {
  36162. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  36163. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  36164. this._soundPanner.coneOuterGain = this._coneOuterGain;
  36165. if (this._connectedMesh) {
  36166. this._updateDirection();
  36167. }
  36168. else {
  36169. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  36170. }
  36171. }
  36172. }
  36173. }
  36174. if (this._streaming) {
  36175. if (!this._streamingSource) {
  36176. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  36177. this._htmlAudioElement.onended = function () { _this._onended(); };
  36178. this._htmlAudioElement.playbackRate = this._playbackRate;
  36179. }
  36180. this._streamingSource.disconnect();
  36181. this._streamingSource.connect(this._inputAudioNode);
  36182. this._htmlAudioElement.play();
  36183. }
  36184. else {
  36185. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  36186. this._soundSource.buffer = this._audioBuffer;
  36187. this._soundSource.connect(this._inputAudioNode);
  36188. this._soundSource.loop = this.loop;
  36189. this._soundSource.playbackRate.value = this._playbackRate;
  36190. this._soundSource.onended = function () { _this._onended(); };
  36191. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  36192. }
  36193. this._startTime = startTime;
  36194. this.isPlaying = true;
  36195. this.isPaused = false;
  36196. }
  36197. catch (ex) {
  36198. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  36199. }
  36200. }
  36201. };
  36202. Sound.prototype._onended = function () {
  36203. this.isPlaying = false;
  36204. if (this.onended) {
  36205. this.onended();
  36206. }
  36207. };
  36208. /**
  36209. * Stop the sound
  36210. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  36211. */
  36212. Sound.prototype.stop = function (time) {
  36213. if (this.isPlaying) {
  36214. if (this._streaming) {
  36215. this._htmlAudioElement.pause();
  36216. // Test needed for Firefox or it will generate an Invalid State Error
  36217. if (this._htmlAudioElement.currentTime > 0) {
  36218. this._htmlAudioElement.currentTime = 0;
  36219. }
  36220. }
  36221. else {
  36222. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  36223. this._soundSource.stop(stopTime);
  36224. this._soundSource.onended = null;
  36225. if (!this.isPaused) {
  36226. this._startOffset = 0;
  36227. }
  36228. }
  36229. this.isPlaying = false;
  36230. }
  36231. };
  36232. Sound.prototype.pause = function () {
  36233. if (this.isPlaying) {
  36234. this.isPaused = true;
  36235. if (this._streaming) {
  36236. this._htmlAudioElement.pause();
  36237. }
  36238. else {
  36239. this.stop(0);
  36240. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  36241. }
  36242. }
  36243. };
  36244. Sound.prototype.setVolume = function (newVolume, time) {
  36245. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36246. if (time) {
  36247. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  36248. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  36249. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  36250. }
  36251. else {
  36252. this._soundGain.gain.value = newVolume;
  36253. }
  36254. }
  36255. this._volume = newVolume;
  36256. };
  36257. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  36258. this._playbackRate = newPlaybackRate;
  36259. if (this.isPlaying) {
  36260. if (this._streaming) {
  36261. this._htmlAudioElement.playbackRate = this._playbackRate;
  36262. }
  36263. else {
  36264. this._soundSource.playbackRate.value = this._playbackRate;
  36265. }
  36266. }
  36267. };
  36268. Sound.prototype.getVolume = function () {
  36269. return this._volume;
  36270. };
  36271. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  36272. var _this = this;
  36273. if (this._connectedMesh) {
  36274. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  36275. this._registerFunc = null;
  36276. }
  36277. this._connectedMesh = meshToConnectTo;
  36278. if (!this.spatialSound) {
  36279. this.spatialSound = true;
  36280. this._createSpatialParameters();
  36281. if (this.isPlaying && this.loop) {
  36282. this.stop();
  36283. this.play();
  36284. }
  36285. }
  36286. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  36287. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  36288. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  36289. };
  36290. Sound.prototype.detachFromMesh = function () {
  36291. if (this._connectedMesh) {
  36292. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  36293. this._registerFunc = null;
  36294. this._connectedMesh = null;
  36295. }
  36296. };
  36297. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  36298. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  36299. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  36300. this._updateDirection();
  36301. }
  36302. };
  36303. Sound.prototype.clone = function () {
  36304. var _this = this;
  36305. if (!this._streaming) {
  36306. var setBufferAndRun = function () {
  36307. if (_this._isReadyToPlay) {
  36308. clonedSound._audioBuffer = _this.getAudioBuffer();
  36309. clonedSound._isReadyToPlay = true;
  36310. if (clonedSound.autoplay) {
  36311. clonedSound.play();
  36312. }
  36313. }
  36314. else {
  36315. window.setTimeout(setBufferAndRun, 300);
  36316. }
  36317. };
  36318. var currentOptions = {
  36319. autoplay: this.autoplay, loop: this.loop,
  36320. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  36321. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  36322. refDistance: this.refDistance, distanceModel: this.distanceModel
  36323. };
  36324. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  36325. if (this.useCustomAttenuation) {
  36326. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  36327. }
  36328. clonedSound.setPosition(this._position);
  36329. clonedSound.setPlaybackRate(this._playbackRate);
  36330. setBufferAndRun();
  36331. return clonedSound;
  36332. }
  36333. else {
  36334. return null;
  36335. }
  36336. };
  36337. Sound.prototype.getAudioBuffer = function () {
  36338. return this._audioBuffer;
  36339. };
  36340. Sound.prototype.serialize = function () {
  36341. var serializationObject = {
  36342. name: this.name,
  36343. url: this.name,
  36344. autoplay: this.autoplay,
  36345. loop: this.loop,
  36346. volume: this._volume,
  36347. spatialSound: this.spatialSound,
  36348. maxDistance: this.maxDistance,
  36349. rolloffFactor: this.rolloffFactor,
  36350. refDistance: this.refDistance,
  36351. distanceModel: this.distanceModel,
  36352. playbackRate: this._playbackRate,
  36353. panningModel: this._panningModel,
  36354. soundTrackId: this.soundTrackId
  36355. };
  36356. if (this.spatialSound) {
  36357. if (this._connectedMesh)
  36358. serializationObject.connectedMeshId = this._connectedMesh.id;
  36359. serializationObject.position = this._position.asArray();
  36360. serializationObject.refDistance = this.refDistance;
  36361. serializationObject.distanceModel = this.distanceModel;
  36362. serializationObject.isDirectional = this._isDirectional;
  36363. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  36364. serializationObject.coneInnerAngle = this._coneInnerAngle;
  36365. serializationObject.coneOuterAngle = this._coneOuterAngle;
  36366. serializationObject.coneOuterGain = this._coneOuterGain;
  36367. }
  36368. return serializationObject;
  36369. };
  36370. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  36371. var soundName = parsedSound.name;
  36372. var soundUrl;
  36373. if (parsedSound.url) {
  36374. soundUrl = rootUrl + parsedSound.url;
  36375. }
  36376. else {
  36377. soundUrl = rootUrl + soundName;
  36378. }
  36379. var options = {
  36380. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  36381. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  36382. rolloffFactor: parsedSound.rolloffFactor,
  36383. refDistance: parsedSound.refDistance,
  36384. distanceModel: parsedSound.distanceModel,
  36385. playbackRate: parsedSound.playbackRate
  36386. };
  36387. var newSound;
  36388. if (!sourceSound) {
  36389. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  36390. scene._addPendingData(newSound);
  36391. }
  36392. else {
  36393. var setBufferAndRun = function () {
  36394. if (sourceSound._isReadyToPlay) {
  36395. newSound._audioBuffer = sourceSound.getAudioBuffer();
  36396. newSound._isReadyToPlay = true;
  36397. if (newSound.autoplay) {
  36398. newSound.play();
  36399. }
  36400. }
  36401. else {
  36402. window.setTimeout(setBufferAndRun, 300);
  36403. }
  36404. };
  36405. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  36406. setBufferAndRun();
  36407. }
  36408. if (parsedSound.position) {
  36409. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  36410. newSound.setPosition(soundPosition);
  36411. }
  36412. if (parsedSound.isDirectional) {
  36413. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  36414. if (parsedSound.localDirectionToMesh) {
  36415. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  36416. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  36417. }
  36418. }
  36419. if (parsedSound.connectedMeshId) {
  36420. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  36421. if (connectedMesh) {
  36422. newSound.attachToMesh(connectedMesh);
  36423. }
  36424. }
  36425. return newSound;
  36426. };
  36427. return Sound;
  36428. })();
  36429. BABYLON.Sound = Sound;
  36430. })(BABYLON || (BABYLON = {}));
  36431. var BABYLON;
  36432. (function (BABYLON) {
  36433. var SoundTrack = (function () {
  36434. function SoundTrack(scene, options) {
  36435. this.id = -1;
  36436. this._isMainTrack = false;
  36437. this._isInitialized = false;
  36438. this._scene = scene;
  36439. this.soundCollection = new Array();
  36440. this._options = options;
  36441. if (!this._isMainTrack) {
  36442. this._scene.soundTracks.push(this);
  36443. this.id = this._scene.soundTracks.length - 1;
  36444. }
  36445. }
  36446. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  36447. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36448. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  36449. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  36450. if (this._options) {
  36451. if (this._options.volume) {
  36452. this._outputAudioNode.gain.value = this._options.volume;
  36453. }
  36454. if (this._options.mainTrack) {
  36455. this._isMainTrack = this._options.mainTrack;
  36456. }
  36457. }
  36458. this._isInitialized = true;
  36459. }
  36460. };
  36461. SoundTrack.prototype.dispose = function () {
  36462. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36463. if (this._connectedAnalyser) {
  36464. this._connectedAnalyser.stopDebugCanvas();
  36465. }
  36466. while (this.soundCollection.length) {
  36467. this.soundCollection[0].dispose();
  36468. }
  36469. if (this._outputAudioNode) {
  36470. this._outputAudioNode.disconnect();
  36471. }
  36472. this._outputAudioNode = null;
  36473. }
  36474. };
  36475. SoundTrack.prototype.AddSound = function (sound) {
  36476. if (!this._isInitialized) {
  36477. this._initializeSoundTrackAudioGraph();
  36478. }
  36479. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36480. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  36481. }
  36482. if (sound.soundTrackId) {
  36483. if (sound.soundTrackId === -1) {
  36484. this._scene.mainSoundTrack.RemoveSound(sound);
  36485. }
  36486. else {
  36487. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  36488. }
  36489. }
  36490. this.soundCollection.push(sound);
  36491. sound.soundTrackId = this.id;
  36492. };
  36493. SoundTrack.prototype.RemoveSound = function (sound) {
  36494. var index = this.soundCollection.indexOf(sound);
  36495. if (index !== -1) {
  36496. this.soundCollection.splice(index, 1);
  36497. }
  36498. };
  36499. SoundTrack.prototype.setVolume = function (newVolume) {
  36500. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36501. this._outputAudioNode.gain.value = newVolume;
  36502. }
  36503. };
  36504. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  36505. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36506. for (var i = 0; i < this.soundCollection.length; i++) {
  36507. this.soundCollection[i].switchPanningModelToHRTF();
  36508. }
  36509. }
  36510. };
  36511. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  36512. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36513. for (var i = 0; i < this.soundCollection.length; i++) {
  36514. this.soundCollection[i].switchPanningModelToEqualPower();
  36515. }
  36516. }
  36517. };
  36518. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  36519. if (this._connectedAnalyser) {
  36520. this._connectedAnalyser.stopDebugCanvas();
  36521. }
  36522. this._connectedAnalyser = analyser;
  36523. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36524. this._outputAudioNode.disconnect();
  36525. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  36526. }
  36527. };
  36528. return SoundTrack;
  36529. })();
  36530. BABYLON.SoundTrack = SoundTrack;
  36531. })(BABYLON || (BABYLON = {}));
  36532. var BABYLON;
  36533. (function (BABYLON) {
  36534. var DebugLayer = (function () {
  36535. function DebugLayer(scene) {
  36536. var _this = this;
  36537. this._transformationMatrix = BABYLON.Matrix.Identity();
  36538. this._enabled = false;
  36539. this._labelsEnabled = false;
  36540. this._displayStatistics = true;
  36541. this._displayTree = false;
  36542. this._displayLogs = false;
  36543. this._skeletonViewers = new Array();
  36544. this._identityMatrix = BABYLON.Matrix.Identity();
  36545. this.axisRatio = 0.02;
  36546. this.accentColor = "orange";
  36547. this._scene = scene;
  36548. this._syncPositions = function () {
  36549. var engine = _this._scene.getEngine();
  36550. var canvasRect = engine.getRenderingCanvasClientRect();
  36551. if (_this._showUI) {
  36552. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  36553. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  36554. _this._statsDiv.style.width = "400px";
  36555. _this._statsDiv.style.height = "auto";
  36556. _this._statsSubsetDiv.style.maxHeight = "240px";
  36557. _this._optionsDiv.style.left = "0px";
  36558. _this._optionsDiv.style.top = "10px";
  36559. _this._optionsDiv.style.width = "200px";
  36560. _this._optionsDiv.style.height = "auto";
  36561. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  36562. _this._logDiv.style.left = "0px";
  36563. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  36564. _this._logDiv.style.width = "600px";
  36565. _this._logDiv.style.height = "160px";
  36566. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  36567. _this._treeDiv.style.top = "10px";
  36568. _this._treeDiv.style.width = "300px";
  36569. _this._treeDiv.style.height = "auto";
  36570. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  36571. }
  36572. _this._globalDiv.style.left = canvasRect.left + "px";
  36573. _this._globalDiv.style.top = canvasRect.top + "px";
  36574. _this._drawingCanvas.style.left = "0px";
  36575. _this._drawingCanvas.style.top = "0px";
  36576. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  36577. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  36578. var devicePixelRatio = window.devicePixelRatio || 1;
  36579. var context = _this._drawingContext;
  36580. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  36581. context.mozBackingStorePixelRatio ||
  36582. context.msBackingStorePixelRatio ||
  36583. context.oBackingStorePixelRatio ||
  36584. context.backingStorePixelRatio || 1;
  36585. _this._ratio = devicePixelRatio / backingStoreRatio;
  36586. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  36587. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  36588. };
  36589. this._onCanvasClick = function (evt) {
  36590. _this._clickPosition = {
  36591. x: evt.clientX * _this._ratio,
  36592. y: evt.clientY * _this._ratio
  36593. };
  36594. };
  36595. this._syncUI = function () {
  36596. if (_this._showUI) {
  36597. if (_this._displayStatistics) {
  36598. _this._displayStats();
  36599. _this._statsDiv.style.display = "";
  36600. }
  36601. else {
  36602. _this._statsDiv.style.display = "none";
  36603. }
  36604. if (_this._displayLogs) {
  36605. _this._logDiv.style.display = "";
  36606. }
  36607. else {
  36608. _this._logDiv.style.display = "none";
  36609. }
  36610. if (_this._displayTree) {
  36611. _this._treeDiv.style.display = "";
  36612. if (_this._needToRefreshMeshesTree) {
  36613. _this._needToRefreshMeshesTree = false;
  36614. _this._refreshMeshesTreeContent();
  36615. }
  36616. }
  36617. else {
  36618. _this._treeDiv.style.display = "none";
  36619. }
  36620. }
  36621. };
  36622. this._syncData = function () {
  36623. if (_this._labelsEnabled || !_this._showUI) {
  36624. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  36625. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  36626. var engine = _this._scene.getEngine();
  36627. var viewport = _this._camera.viewport;
  36628. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  36629. // Meshes
  36630. var meshes = _this._camera.getActiveMeshes();
  36631. var index;
  36632. var projectedPosition;
  36633. for (index = 0; index < meshes.length; index++) {
  36634. var mesh = meshes.data[index];
  36635. var position = mesh.getBoundingInfo().boundingSphere.center;
  36636. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  36637. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  36638. _this._renderAxis(projectedPosition, mesh, globalViewport);
  36639. }
  36640. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  36641. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  36642. }
  36643. }
  36644. // Cameras
  36645. var cameras = _this._scene.cameras;
  36646. for (index = 0; index < cameras.length; index++) {
  36647. var camera = cameras[index];
  36648. if (camera === _this._camera) {
  36649. continue;
  36650. }
  36651. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  36652. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  36653. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  36654. _this._camera.detachControl(engine.getRenderingCanvas());
  36655. _this._camera = camera;
  36656. _this._camera.attachControl(engine.getRenderingCanvas());
  36657. }, function () { return "purple"; });
  36658. }
  36659. }
  36660. // Lights
  36661. var lights = _this._scene.lights;
  36662. for (index = 0; index < lights.length; index++) {
  36663. var light = lights[index];
  36664. if (light.position) {
  36665. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  36666. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  36667. _this._renderLabel(light.name, projectedPosition, -20, function () {
  36668. light.setEnabled(!light.isEnabled());
  36669. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  36670. }
  36671. }
  36672. }
  36673. }
  36674. _this._clickPosition = undefined;
  36675. };
  36676. }
  36677. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  36678. while (this._treeSubsetDiv.hasChildNodes()) {
  36679. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  36680. }
  36681. // Add meshes
  36682. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  36683. sortedArray.sort(function (a, b) {
  36684. if (a.name === b.name) {
  36685. return 0;
  36686. }
  36687. return (a.name > b.name) ? 1 : -1;
  36688. });
  36689. for (var index = 0; index < sortedArray.length; index++) {
  36690. var mesh = sortedArray[index];
  36691. if (!mesh.isEnabled()) {
  36692. continue;
  36693. }
  36694. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  36695. m.isVisible = element.checked;
  36696. }, mesh);
  36697. }
  36698. };
  36699. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  36700. this._drawingContext.beginPath();
  36701. this._drawingContext.moveTo(zero.x, zero.y);
  36702. this._drawingContext.lineTo(unit.x, unit.y);
  36703. this._drawingContext.strokeStyle = color;
  36704. this._drawingContext.lineWidth = 4;
  36705. this._drawingContext.stroke();
  36706. this._drawingContext.font = "normal 14px Segoe UI";
  36707. this._drawingContext.fillStyle = color;
  36708. this._drawingContext.fillText(label, unitText.x, unitText.y);
  36709. };
  36710. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  36711. var position = mesh.getBoundingInfo().boundingSphere.center;
  36712. var worldMatrix = mesh.getWorldMatrix();
  36713. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  36714. var unit = (unprojectedVector.subtract(position)).length();
  36715. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  36716. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  36717. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  36718. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  36719. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  36720. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  36721. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  36722. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  36723. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  36724. };
  36725. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  36726. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  36727. this._drawingContext.font = "normal 12px Segoe UI";
  36728. var textMetrics = this._drawingContext.measureText(text);
  36729. var centerX = projectedPosition.x - textMetrics.width / 2;
  36730. var centerY = projectedPosition.y;
  36731. var clientRect = this._drawingCanvas.getBoundingClientRect();
  36732. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  36733. onClick();
  36734. }
  36735. this._drawingContext.beginPath();
  36736. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  36737. this._drawingContext.fillStyle = getFillStyle();
  36738. this._drawingContext.globalAlpha = 0.5;
  36739. this._drawingContext.fill();
  36740. this._drawingContext.globalAlpha = 1.0;
  36741. this._drawingContext.strokeStyle = '#FFFFFF';
  36742. this._drawingContext.lineWidth = 1;
  36743. this._drawingContext.stroke();
  36744. this._drawingContext.fillStyle = "#FFFFFF";
  36745. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  36746. this._drawingContext.beginPath();
  36747. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  36748. this._drawingContext.fill();
  36749. }
  36750. };
  36751. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  36752. if (!this._clickPosition) {
  36753. return false;
  36754. }
  36755. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  36756. return false;
  36757. }
  36758. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  36759. return false;
  36760. }
  36761. return true;
  36762. };
  36763. DebugLayer.prototype.isVisible = function () {
  36764. return this._enabled;
  36765. };
  36766. DebugLayer.prototype.hide = function () {
  36767. if (!this._enabled) {
  36768. return;
  36769. }
  36770. this._enabled = false;
  36771. var engine = this._scene.getEngine();
  36772. this._scene.unregisterBeforeRender(this._syncData);
  36773. this._scene.unregisterAfterRender(this._syncUI);
  36774. this._rootElement.removeChild(this._globalDiv);
  36775. this._scene.forceShowBoundingBoxes = false;
  36776. this._scene.forceWireframe = false;
  36777. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  36778. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  36779. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  36780. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  36781. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  36782. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  36783. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  36784. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  36785. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  36786. BABYLON.StandardMaterial.ColorGradingTextureEnabled = true;
  36787. this._scene.shadowsEnabled = true;
  36788. this._scene.particlesEnabled = true;
  36789. this._scene.postProcessesEnabled = true;
  36790. this._scene.collisionsEnabled = true;
  36791. this._scene.lightsEnabled = true;
  36792. this._scene.texturesEnabled = true;
  36793. this._scene.lensFlaresEnabled = true;
  36794. this._scene.proceduralTexturesEnabled = true;
  36795. this._scene.renderTargetsEnabled = true;
  36796. this._scene.probesEnabled = true;
  36797. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  36798. this._clearSkeletonViewers();
  36799. };
  36800. DebugLayer.prototype._clearSkeletonViewers = function () {
  36801. for (var index = 0; index < this._skeletonViewers.length; index++) {
  36802. this._skeletonViewers[index].dispose();
  36803. }
  36804. this._skeletonViewers = [];
  36805. };
  36806. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  36807. if (showUI === void 0) { showUI = true; }
  36808. if (camera === void 0) { camera = null; }
  36809. if (rootElement === void 0) { rootElement = null; }
  36810. if (this._enabled) {
  36811. return;
  36812. }
  36813. this._enabled = true;
  36814. if (camera) {
  36815. this._camera = camera;
  36816. }
  36817. else {
  36818. this._camera = this._scene.activeCamera;
  36819. }
  36820. this._showUI = showUI;
  36821. var engine = this._scene.getEngine();
  36822. this._globalDiv = document.createElement("div");
  36823. this._rootElement = rootElement || document.body;
  36824. this._rootElement.appendChild(this._globalDiv);
  36825. this._generateDOMelements();
  36826. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  36827. this._syncPositions();
  36828. this._scene.registerBeforeRender(this._syncData);
  36829. this._scene.registerAfterRender(this._syncUI);
  36830. };
  36831. DebugLayer.prototype._clearLabels = function () {
  36832. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  36833. for (var index = 0; index < this._scene.meshes.length; index++) {
  36834. var mesh = this._scene.meshes[index];
  36835. mesh.renderOverlay = false;
  36836. }
  36837. };
  36838. DebugLayer.prototype._generateheader = function (root, text) {
  36839. var header = document.createElement("div");
  36840. header.innerHTML = text + "&nbsp;";
  36841. header.style.textAlign = "right";
  36842. header.style.width = "100%";
  36843. header.style.color = "white";
  36844. header.style.backgroundColor = "Black";
  36845. header.style.padding = "5px 5px 4px 0px";
  36846. header.style.marginLeft = "-5px";
  36847. header.style.fontWeight = "bold";
  36848. root.appendChild(header);
  36849. };
  36850. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  36851. var label = document.createElement("label");
  36852. label.style.display = "inline";
  36853. label.innerHTML = title;
  36854. label.style.color = color;
  36855. root.appendChild(label);
  36856. root.appendChild(document.createElement("br"));
  36857. };
  36858. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  36859. if (tag === void 0) { tag = null; }
  36860. var label = document.createElement("label");
  36861. label.style.display = "inline";
  36862. var boundingBoxesCheckbox = document.createElement("input");
  36863. boundingBoxesCheckbox.type = "checkbox";
  36864. boundingBoxesCheckbox.checked = initialState;
  36865. boundingBoxesCheckbox.style.display = "inline";
  36866. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  36867. boundingBoxesCheckbox.style.verticalAlign = "sub";
  36868. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  36869. task(evt.target, tag);
  36870. });
  36871. label.appendChild(boundingBoxesCheckbox);
  36872. var container = document.createElement("span");
  36873. var leftPart = document.createElement("span");
  36874. var rightPart = document.createElement("span");
  36875. rightPart.style.cssFloat = "right";
  36876. leftPart.innerHTML = leftTitle;
  36877. rightPart.innerHTML = rightTitle;
  36878. rightPart.style.fontSize = "12px";
  36879. rightPart.style.maxWidth = "200px";
  36880. container.appendChild(leftPart);
  36881. container.appendChild(rightPart);
  36882. label.appendChild(container);
  36883. root.appendChild(label);
  36884. root.appendChild(document.createElement("br"));
  36885. };
  36886. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  36887. if (tag === void 0) { tag = null; }
  36888. var label = document.createElement("label");
  36889. label.style.display = "inline";
  36890. var checkBox = document.createElement("input");
  36891. checkBox.type = "checkbox";
  36892. checkBox.checked = initialState;
  36893. checkBox.style.display = "inline";
  36894. checkBox.style.margin = "0px 5px 0px 0px";
  36895. checkBox.style.verticalAlign = "sub";
  36896. checkBox.addEventListener("change", function (evt) {
  36897. task(evt.target, tag);
  36898. });
  36899. label.appendChild(checkBox);
  36900. label.appendChild(document.createTextNode(title));
  36901. root.appendChild(label);
  36902. root.appendChild(document.createElement("br"));
  36903. };
  36904. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  36905. if (tag === void 0) { tag = null; }
  36906. var button = document.createElement("button");
  36907. button.innerHTML = title;
  36908. button.style.height = "24px";
  36909. button.style.width = "150px";
  36910. button.style.marginBottom = "5px";
  36911. button.style.color = "#444444";
  36912. button.style.border = "1px solid white";
  36913. button.className = "debugLayerButton";
  36914. button.addEventListener("click", function (evt) {
  36915. task(evt.target, tag);
  36916. });
  36917. root.appendChild(button);
  36918. root.appendChild(document.createElement("br"));
  36919. };
  36920. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  36921. if (tag === void 0) { tag = null; }
  36922. var label = document.createElement("label");
  36923. label.style.display = "inline";
  36924. var boundingBoxesRadio = document.createElement("input");
  36925. boundingBoxesRadio.type = "radio";
  36926. boundingBoxesRadio.name = name;
  36927. boundingBoxesRadio.checked = initialState;
  36928. boundingBoxesRadio.style.display = "inline";
  36929. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  36930. boundingBoxesRadio.style.verticalAlign = "sub";
  36931. boundingBoxesRadio.addEventListener("change", function (evt) {
  36932. task(evt.target, tag);
  36933. });
  36934. label.appendChild(boundingBoxesRadio);
  36935. label.appendChild(document.createTextNode(title));
  36936. root.appendChild(label);
  36937. root.appendChild(document.createElement("br"));
  36938. };
  36939. DebugLayer.prototype._generateDOMelements = function () {
  36940. var _this = this;
  36941. this._globalDiv.id = "DebugLayer";
  36942. this._globalDiv.style.position = "absolute";
  36943. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  36944. this._globalDiv.style.fontSize = "14px";
  36945. this._globalDiv.style.color = "white";
  36946. // Drawing canvas
  36947. this._drawingCanvas = document.createElement("canvas");
  36948. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  36949. this._drawingCanvas.style.position = "absolute";
  36950. this._drawingCanvas.style.pointerEvents = "none";
  36951. this._drawingCanvas.style.backgroundColor = "transparent";
  36952. this._drawingContext = this._drawingCanvas.getContext("2d");
  36953. this._globalDiv.appendChild(this._drawingCanvas);
  36954. if (this._showUI) {
  36955. var background = "rgba(128, 128, 128, 0.4)";
  36956. var border = "rgb(180, 180, 180) solid 1px";
  36957. // Stats
  36958. this._statsDiv = document.createElement("div");
  36959. this._statsDiv.id = "DebugLayerStats";
  36960. this._statsDiv.style.border = border;
  36961. this._statsDiv.style.position = "absolute";
  36962. this._statsDiv.style.background = background;
  36963. this._statsDiv.style.padding = "0px 0px 0px 5px";
  36964. this._generateheader(this._statsDiv, "STATISTICS");
  36965. this._statsSubsetDiv = document.createElement("div");
  36966. this._statsSubsetDiv.style.paddingTop = "5px";
  36967. this._statsSubsetDiv.style.paddingBottom = "5px";
  36968. this._statsSubsetDiv.style.overflowY = "auto";
  36969. this._statsDiv.appendChild(this._statsSubsetDiv);
  36970. // Tree
  36971. this._treeDiv = document.createElement("div");
  36972. this._treeDiv.id = "DebugLayerTree";
  36973. this._treeDiv.style.border = border;
  36974. this._treeDiv.style.position = "absolute";
  36975. this._treeDiv.style.background = background;
  36976. this._treeDiv.style.padding = "0px 0px 0px 5px";
  36977. this._treeDiv.style.display = "none";
  36978. this._generateheader(this._treeDiv, "MESHES TREE");
  36979. this._treeSubsetDiv = document.createElement("div");
  36980. this._treeSubsetDiv.style.paddingTop = "5px";
  36981. this._treeSubsetDiv.style.paddingRight = "5px";
  36982. this._treeSubsetDiv.style.overflowY = "auto";
  36983. this._treeSubsetDiv.style.maxHeight = "300px";
  36984. this._treeDiv.appendChild(this._treeSubsetDiv);
  36985. this._needToRefreshMeshesTree = true;
  36986. // Logs
  36987. this._logDiv = document.createElement("div");
  36988. this._logDiv.style.border = border;
  36989. this._logDiv.id = "DebugLayerLogs";
  36990. this._logDiv.style.position = "absolute";
  36991. this._logDiv.style.background = background;
  36992. this._logDiv.style.padding = "0px 0px 0px 5px";
  36993. this._logDiv.style.display = "none";
  36994. this._generateheader(this._logDiv, "LOGS");
  36995. this._logSubsetDiv = document.createElement("div");
  36996. this._logSubsetDiv.style.height = "127px";
  36997. this._logSubsetDiv.style.paddingTop = "5px";
  36998. this._logSubsetDiv.style.overflowY = "auto";
  36999. this._logSubsetDiv.style.fontSize = "12px";
  37000. this._logSubsetDiv.style.fontFamily = "consolas";
  37001. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  37002. this._logDiv.appendChild(this._logSubsetDiv);
  37003. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  37004. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  37005. };
  37006. // Options
  37007. this._optionsDiv = document.createElement("div");
  37008. this._optionsDiv.id = "DebugLayerOptions";
  37009. this._optionsDiv.style.border = border;
  37010. this._optionsDiv.style.position = "absolute";
  37011. this._optionsDiv.style.background = background;
  37012. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  37013. this._optionsDiv.style.overflowY = "auto";
  37014. this._generateheader(this._optionsDiv, "OPTIONS");
  37015. this._optionsSubsetDiv = document.createElement("div");
  37016. this._optionsSubsetDiv.style.paddingTop = "5px";
  37017. this._optionsSubsetDiv.style.paddingBottom = "5px";
  37018. this._optionsSubsetDiv.style.overflowY = "auto";
  37019. this._optionsSubsetDiv.style.maxHeight = "200px";
  37020. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  37021. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  37022. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  37023. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  37024. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  37025. _this._displayTree = element.checked;
  37026. _this._needToRefreshMeshesTree = true;
  37027. });
  37028. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  37029. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  37030. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  37031. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  37032. _this._labelsEnabled = element.checked;
  37033. if (!_this._labelsEnabled) {
  37034. _this._clearLabels();
  37035. }
  37036. });
  37037. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  37038. if (element.checked) {
  37039. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  37040. }
  37041. else {
  37042. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  37043. }
  37044. });
  37045. ;
  37046. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  37047. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  37048. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  37049. if (element.checked) {
  37050. _this._scene.forceWireframe = false;
  37051. _this._scene.forcePointsCloud = false;
  37052. }
  37053. });
  37054. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  37055. if (element.checked) {
  37056. _this._scene.forceWireframe = true;
  37057. _this._scene.forcePointsCloud = false;
  37058. }
  37059. });
  37060. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  37061. if (element.checked) {
  37062. _this._scene.forceWireframe = false;
  37063. _this._scene.forcePointsCloud = true;
  37064. }
  37065. });
  37066. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  37067. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  37068. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  37069. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  37070. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  37071. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  37072. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  37073. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  37074. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  37075. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  37076. this._generateCheckBox(this._optionsSubsetDiv, "ColorGrading", BABYLON.StandardMaterial.ColorGradingTextureEnabled, function (element) { BABYLON.StandardMaterial.ColorGradingTextureEnabled = element.checked; });
  37077. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  37078. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  37079. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  37080. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  37081. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  37082. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  37083. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  37084. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  37085. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  37086. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  37087. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  37088. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  37089. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  37090. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  37091. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  37092. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  37093. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  37094. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  37095. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  37096. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  37097. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  37098. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  37099. if (element.checked) {
  37100. _this._scene.headphone = true;
  37101. }
  37102. });
  37103. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  37104. if (element.checked) {
  37105. _this._scene.headphone = false;
  37106. }
  37107. });
  37108. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  37109. _this._scene.audioEnabled = !element.checked;
  37110. });
  37111. }
  37112. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  37113. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  37114. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  37115. if (!element.checked) {
  37116. _this._clearSkeletonViewers();
  37117. return;
  37118. }
  37119. for (var index = 0; index < _this._scene.meshes.length; index++) {
  37120. var mesh = _this._scene.meshes[index];
  37121. if (mesh.skeleton) {
  37122. var found = false;
  37123. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  37124. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  37125. found = true;
  37126. break;
  37127. }
  37128. }
  37129. if (found) {
  37130. continue;
  37131. }
  37132. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  37133. viewer.isEnabled = true;
  37134. _this._skeletonViewers.push(viewer);
  37135. }
  37136. }
  37137. });
  37138. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  37139. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  37140. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  37141. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  37142. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  37143. if (_this._camera) {
  37144. console.log(_this._camera);
  37145. }
  37146. else {
  37147. console.warn("No camera defined, or debug layer created before camera creation!");
  37148. }
  37149. });
  37150. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  37151. this._globalDiv.appendChild(this._statsDiv);
  37152. this._globalDiv.appendChild(this._logDiv);
  37153. this._globalDiv.appendChild(this._optionsDiv);
  37154. this._globalDiv.appendChild(this._treeDiv);
  37155. }
  37156. };
  37157. DebugLayer.prototype._displayStats = function () {
  37158. var scene = this._scene;
  37159. var engine = scene.getEngine();
  37160. var glInfo = engine.getGlInfo();
  37161. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  37162. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  37163. + "<b>Count</b><br>"
  37164. + "Total meshes: " + scene.meshes.length + "<br>"
  37165. + "Total lights: " + scene.lights.length + "<br>"
  37166. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  37167. + "Total materials: " + scene.materials.length + "<br>"
  37168. + "Total textures: " + scene.textures.length + "<br>"
  37169. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  37170. + "Active indices: " + scene.getActiveIndices() + "<br>"
  37171. + "Active bones: " + scene.getActiveBones() + "<br>"
  37172. + "Active particles: " + scene.getActiveParticles() + "<br>"
  37173. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  37174. + "<b>Duration</b><br>"
  37175. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  37176. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  37177. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  37178. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  37179. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  37180. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  37181. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  37182. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  37183. + "</div>"
  37184. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  37185. + "<b>Extensions</b><br>"
  37186. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  37187. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  37188. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  37189. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  37190. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  37191. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  37192. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  37193. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  37194. + "</div><br>"
  37195. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  37196. + "<b>Caps.</b><br>"
  37197. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  37198. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  37199. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  37200. + "<b>Info</b><br>"
  37201. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  37202. + glInfo.version + "<br>"
  37203. + "</div><br>"
  37204. + glInfo.renderer + "<br>";
  37205. if (this.customStatsFunction) {
  37206. this._statsSubsetDiv.innerHTML += this.customStatsFunction();
  37207. }
  37208. };
  37209. return DebugLayer;
  37210. })();
  37211. BABYLON.DebugLayer = DebugLayer;
  37212. })(BABYLON || (BABYLON = {}));
  37213. var BABYLON;
  37214. (function (BABYLON) {
  37215. var SIMDVector3 = (function () {
  37216. function SIMDVector3() {
  37217. }
  37218. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  37219. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  37220. };
  37221. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  37222. var m = transformation.m;
  37223. var m0 = SIMD.Float32x4.load(m, 0);
  37224. var m1 = SIMD.Float32x4.load(m, 4);
  37225. var m2 = SIMD.Float32x4.load(m, 8);
  37226. var m3 = SIMD.Float32x4.load(m, 12);
  37227. var r = SIMD.Float32x4.add(SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(x), m0), SIMD.Float32x4.mul(SIMD.Float32x4.splat(y), m1)), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(z), m2), m3));
  37228. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  37229. result.x = SIMD.Float32x4.extractLane(r, 0);
  37230. result.y = SIMD.Float32x4.extractLane(r, 1);
  37231. result.z = SIMD.Float32x4.extractLane(r, 2);
  37232. };
  37233. return SIMDVector3;
  37234. })();
  37235. var SIMDMatrix = (function () {
  37236. function SIMDMatrix() {
  37237. }
  37238. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  37239. var tm = this.m;
  37240. var om = other.m;
  37241. var m0 = SIMD.Float32x4.load(om, 0);
  37242. var m1 = SIMD.Float32x4.load(om, 4);
  37243. var m2 = SIMD.Float32x4.load(om, 8);
  37244. var m3 = SIMD.Float32x4.load(om, 12);
  37245. for (var i = 0; i < 16; i += 4) {
  37246. SIMD.Float32x4.store(result, i + offset, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i]), m0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 1]), m1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 2]), m2), SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 3]), m3)))));
  37247. }
  37248. return this;
  37249. };
  37250. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  37251. var src = this.m;
  37252. var dest = other.m;
  37253. // Load the 4 rows
  37254. var src0 = SIMD.Float32x4.load(src, 0);
  37255. var src1 = SIMD.Float32x4.load(src, 4);
  37256. var src2 = SIMD.Float32x4.load(src, 8);
  37257. var src3 = SIMD.Float32x4.load(src, 12);
  37258. // Transpose the source matrix. Sort of. Not a true transpose operation
  37259. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  37260. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  37261. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  37262. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  37263. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  37264. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  37265. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  37266. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  37267. // This is a true transposition, but it will lead to an incorrect result
  37268. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  37269. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  37270. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  37271. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  37272. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  37273. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  37274. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  37275. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  37276. // ----
  37277. tmp1 = SIMD.Float32x4.mul(row2, row3);
  37278. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37279. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  37280. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  37281. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37282. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  37283. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  37284. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  37285. // ----
  37286. tmp1 = SIMD.Float32x4.mul(row1, row2);
  37287. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37288. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  37289. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  37290. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37291. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  37292. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  37293. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  37294. // ----
  37295. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  37296. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37297. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  37298. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  37299. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  37300. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37301. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  37302. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  37303. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  37304. // ----
  37305. tmp1 = SIMD.Float32x4.mul(row0, row1);
  37306. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37307. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  37308. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  37309. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37310. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  37311. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  37312. // ----
  37313. tmp1 = SIMD.Float32x4.mul(row0, row3);
  37314. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37315. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  37316. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  37317. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37318. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  37319. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  37320. // ----
  37321. tmp1 = SIMD.Float32x4.mul(row0, row2);
  37322. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37323. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  37324. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  37325. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37326. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  37327. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  37328. // Compute determinant
  37329. var det = SIMD.Float32x4.mul(row0, minor0);
  37330. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  37331. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  37332. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  37333. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  37334. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  37335. // These shuffles aren't necessary if the faulty transposition is done
  37336. // up at the top of this function.
  37337. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  37338. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  37339. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  37340. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  37341. // Compute final values by multiplying with 1/det
  37342. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  37343. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  37344. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  37345. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  37346. return this;
  37347. };
  37348. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  37349. var out = result.m;
  37350. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  37351. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  37352. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  37353. // cc.kmVec3Subtract(f, pCenter, pEye);
  37354. var f = SIMD.Float32x4.sub(center, eye);
  37355. // cc.kmVec3Normalize(f, f);
  37356. var tmp = SIMD.Float32x4.mul(f, f);
  37357. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  37358. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  37359. // cc.kmVec3Assign(up, pUp);
  37360. // cc.kmVec3Normalize(up, up);
  37361. tmp = SIMD.Float32x4.mul(up, up);
  37362. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  37363. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  37364. // cc.kmVec3Cross(s, f, up);
  37365. 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)));
  37366. // cc.kmVec3Normalize(s, s);
  37367. tmp = SIMD.Float32x4.mul(s, s);
  37368. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  37369. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  37370. // cc.kmVec3Cross(u, s, f);
  37371. 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)));
  37372. // cc.kmVec3Normalize(s, s);
  37373. tmp = SIMD.Float32x4.mul(s, s);
  37374. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  37375. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  37376. var zero = SIMD.Float32x4.splat(0.0);
  37377. s = SIMD.Float32x4.neg(s);
  37378. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  37379. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  37380. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  37381. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  37382. var a2 = SIMD.Float32x4.shuffle(SIMD.Float32x4.shuffle(s, u, 2, 3, 6, 7), SIMD.Float32x4.shuffle(f, zero, 2, 3, 6, 7), 0, 2, 4, 6);
  37383. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  37384. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  37385. SIMD.Float32x4.store(out, 0, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  37386. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  37387. SIMD.Float32x4.store(out, 4, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  37388. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  37389. SIMD.Float32x4.store(out, 8, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  37390. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  37391. SIMD.Float32x4.store(out, 12, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  37392. };
  37393. return SIMDMatrix;
  37394. })();
  37395. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  37396. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  37397. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  37398. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  37399. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  37400. var SIMDHelper = (function () {
  37401. function SIMDHelper() {
  37402. }
  37403. Object.defineProperty(SIMDHelper, "IsEnabled", {
  37404. get: function () {
  37405. return SIMDHelper._isEnabled;
  37406. },
  37407. enumerable: true,
  37408. configurable: true
  37409. });
  37410. SIMDHelper.DisableSIMD = function () {
  37411. // Replace functions
  37412. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  37413. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  37414. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  37415. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  37416. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  37417. SIMDHelper._isEnabled = false;
  37418. };
  37419. SIMDHelper.EnableSIMD = function () {
  37420. if (self.SIMD === undefined) {
  37421. return;
  37422. }
  37423. // check if polyfills needed
  37424. if (!self.Math.fround) {
  37425. self.Math.fround = (function (array) { return function (x) {
  37426. return array[0] = x, array[0];
  37427. }; })(new Float32Array(1));
  37428. }
  37429. if (!self.Math.imul) {
  37430. self.Math.imul = function (a, b) {
  37431. var ah = (a >>> 16) & 0xffff;
  37432. var al = a & 0xffff;
  37433. var bh = (b >>> 16) & 0xffff;
  37434. var bl = b & 0xffff;
  37435. // the shift by 0 fixes the sign on the high part
  37436. // the final |0 converts the unsigned value into a signed value
  37437. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  37438. };
  37439. }
  37440. // Replace functions
  37441. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  37442. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  37443. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  37444. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  37445. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  37446. SIMDHelper._isEnabled = true;
  37447. };
  37448. SIMDHelper._isEnabled = false;
  37449. return SIMDHelper;
  37450. })();
  37451. BABYLON.SIMDHelper = SIMDHelper;
  37452. })(BABYLON || (BABYLON = {}));
  37453. var BABYLON;
  37454. (function (BABYLON) {
  37455. /**
  37456. * This class describe a rectangle that were added to the map.
  37457. * You have access to its coordinates either in pixel or normalized (UV)
  37458. */
  37459. var PackedRect = (function () {
  37460. function PackedRect(root, parent, pos, size) {
  37461. this._pos = pos;
  37462. this._size = size;
  37463. this._root = root;
  37464. this._parent = parent;
  37465. }
  37466. Object.defineProperty(PackedRect.prototype, "pos", {
  37467. /**
  37468. * @returns the position of this node into the map
  37469. */
  37470. get: function () {
  37471. return this._pos;
  37472. },
  37473. enumerable: true,
  37474. configurable: true
  37475. });
  37476. Object.defineProperty(PackedRect.prototype, "contentSize", {
  37477. /**
  37478. * @returns the size of the rectangle this node handles
  37479. */
  37480. get: function () {
  37481. return this._contentSize;
  37482. },
  37483. enumerable: true,
  37484. configurable: true
  37485. });
  37486. Object.defineProperty(PackedRect.prototype, "UVs", {
  37487. /**
  37488. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  37489. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  37490. */
  37491. get: function () {
  37492. return this.getUVsForCustomSize(this._root._size);
  37493. },
  37494. enumerable: true,
  37495. configurable: true
  37496. });
  37497. /**
  37498. * 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.
  37499. * This method will return the UVs for this part by given the custom size of what you really use
  37500. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  37501. */
  37502. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  37503. var mainWidth = this._root._size.width;
  37504. var mainHeight = this._root._size.height;
  37505. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  37506. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  37507. var uvs = new Array();
  37508. uvs.push(topLeft);
  37509. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  37510. uvs.push(rightBottom);
  37511. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  37512. return uvs;
  37513. };
  37514. /**
  37515. * Free this rectangle from the map.
  37516. * Call this method when you no longer need the rectangle to be in the map.
  37517. */
  37518. PackedRect.prototype.freeContent = function () {
  37519. if (!this.contentSize) {
  37520. return;
  37521. }
  37522. this._contentSize = null;
  37523. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  37524. this.attemptDefrag();
  37525. };
  37526. Object.defineProperty(PackedRect.prototype, "isUsed", {
  37527. get: function () {
  37528. return this._contentSize != null || this._leftNode != null;
  37529. },
  37530. enumerable: true,
  37531. configurable: true
  37532. });
  37533. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  37534. var node = this.findNode(contentSize);
  37535. // Not enough space...
  37536. if (!node) {
  37537. return null;
  37538. }
  37539. node.splitNode(contentSize);
  37540. return node;
  37541. };
  37542. PackedRect.prototype.findNode = function (size) {
  37543. var resNode = null;
  37544. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  37545. if (this.isUsed) {
  37546. if (this._leftNode) {
  37547. resNode = this._leftNode.findNode(size);
  37548. }
  37549. if (!resNode && this._rightNode) {
  37550. resNode = this._rightNode.findNode(size);
  37551. }
  37552. if (!resNode && this._bottomNode) {
  37553. resNode = this._bottomNode.findNode(size);
  37554. }
  37555. }
  37556. else if (this._initialSize && (size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  37557. resNode = this;
  37558. }
  37559. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  37560. resNode = this;
  37561. }
  37562. return resNode;
  37563. };
  37564. PackedRect.prototype.splitNode = function (contentSize) {
  37565. // 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)
  37566. if (!this._contentSize && this._initialSize) {
  37567. 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));
  37568. return this._leftNode.splitNode(contentSize);
  37569. }
  37570. else {
  37571. this._contentSize = contentSize.clone();
  37572. this._initialSize = contentSize.clone();
  37573. if (contentSize.width !== this._size.width) {
  37574. 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));
  37575. }
  37576. if (contentSize.height !== this._size.height) {
  37577. 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));
  37578. }
  37579. return this;
  37580. }
  37581. };
  37582. PackedRect.prototype.attemptDefrag = function () {
  37583. if (!this.isUsed && this.isRecursiveFree) {
  37584. this.clearNode();
  37585. if (this._parent) {
  37586. this._parent.attemptDefrag();
  37587. }
  37588. }
  37589. };
  37590. PackedRect.prototype.clearNode = function () {
  37591. this._initialSize = null;
  37592. this._rightNode = null;
  37593. this._bottomNode = null;
  37594. };
  37595. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  37596. get: function () {
  37597. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  37598. },
  37599. enumerable: true,
  37600. configurable: true
  37601. });
  37602. PackedRect.prototype.evalFreeSize = function (size) {
  37603. var levelSize = 0;
  37604. if (!this.isUsed) {
  37605. if (this._initialSize) {
  37606. levelSize = this._initialSize.surface;
  37607. }
  37608. else {
  37609. levelSize = this._size.surface;
  37610. }
  37611. }
  37612. if (this._rightNode) {
  37613. levelSize += this._rightNode.evalFreeSize(0);
  37614. }
  37615. if (this._bottomNode) {
  37616. levelSize += this._bottomNode.evalFreeSize(0);
  37617. }
  37618. return levelSize + size;
  37619. };
  37620. return PackedRect;
  37621. })();
  37622. BABYLON.PackedRect = PackedRect;
  37623. /**
  37624. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  37625. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  37626. * 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.
  37627. */
  37628. var RectPackingMap = (function (_super) {
  37629. __extends(RectPackingMap, _super);
  37630. /**
  37631. * Create an instance of the object with a dimension using the given size
  37632. * @param size The dimension of the rectangle that will contain all the sub ones.
  37633. */
  37634. function RectPackingMap(size) {
  37635. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  37636. this._root = this;
  37637. }
  37638. /**
  37639. * Add a rectangle, finding the best location to store it into the map
  37640. * @param size the dimension of the rectangle to store
  37641. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  37642. */
  37643. RectPackingMap.prototype.addRect = function (size) {
  37644. var node = this.findAndSplitNode(size);
  37645. return node;
  37646. };
  37647. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  37648. /**
  37649. * Return the current space free normalized between [0;1]
  37650. * @returns {}
  37651. */
  37652. get: function () {
  37653. var freeSize = 0;
  37654. freeSize = this.evalFreeSize(freeSize);
  37655. return freeSize / (this._size.width * this._size.height);
  37656. },
  37657. enumerable: true,
  37658. configurable: true
  37659. });
  37660. return RectPackingMap;
  37661. })(PackedRect);
  37662. BABYLON.RectPackingMap = RectPackingMap;
  37663. })(BABYLON || (BABYLON = {}));
  37664. var BABYLON;
  37665. (function (BABYLON) {
  37666. var DynamicFloatArrayElementInfo = (function () {
  37667. function DynamicFloatArrayElementInfo() {
  37668. }
  37669. return DynamicFloatArrayElementInfo;
  37670. })();
  37671. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  37672. /**
  37673. * 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.
  37674. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  37675. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  37676. * 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.
  37677. * 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.
  37678. * 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".
  37679. */
  37680. var DynamicFloatArray = (function () {
  37681. /**
  37682. * Construct an instance of the dynamic float array
  37683. * @param stride size of one element in float (i.e. not bytes!)
  37684. * @param initialElementCount the number of available entries at construction
  37685. */
  37686. function DynamicFloatArray(stride, initialElementCount) {
  37687. this.compareValueOffset = null;
  37688. this.sortingAscending = true;
  37689. this._stride = stride;
  37690. this.buffer = new Float32Array(stride * initialElementCount);
  37691. this._lastUsed = 0;
  37692. this._firstFree = 0;
  37693. this._allEntries = new Array(initialElementCount);
  37694. this._freeEntries = new Array(initialElementCount);
  37695. for (var i = 0; i < initialElementCount; i++) {
  37696. var element = new DynamicFloatArrayElementInfo();
  37697. element.offset = i * stride;
  37698. this._allEntries[i] = element;
  37699. this._freeEntries[initialElementCount - i - 1] = element;
  37700. }
  37701. }
  37702. /**
  37703. * Allocate an element in the array.
  37704. * @return the element info instance that contains the offset into the main buffer of the element's location.
  37705. * Beware, this offset may change when you call pack()
  37706. */
  37707. DynamicFloatArray.prototype.allocElement = function () {
  37708. if (this._freeEntries.length === 0) {
  37709. this._growBuffer();
  37710. }
  37711. var el = this._freeEntries.pop();
  37712. this._lastUsed = Math.max(el.offset, this._lastUsed);
  37713. if (el.offset === this._firstFree) {
  37714. if (this._freeEntries.length > 0) {
  37715. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  37716. }
  37717. else {
  37718. this._firstFree += this._stride;
  37719. }
  37720. }
  37721. return el;
  37722. };
  37723. /**
  37724. * Free the element corresponding to the given element info
  37725. * @param elInfo the element that describe the allocated element
  37726. */
  37727. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  37728. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  37729. this._freeEntries.push(elInfo);
  37730. };
  37731. /**
  37732. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  37733. * 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().
  37734. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  37735. */
  37736. DynamicFloatArray.prototype.pack = function () {
  37737. // no free slot? no need to pack
  37738. if (this._freeEntries.length === 0) {
  37739. return this.buffer;
  37740. }
  37741. // If the buffer is already packed the last used will always be lower than the first free
  37742. // 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.
  37743. if (this._lastUsed < this._firstFree) {
  37744. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  37745. return elementsBuffer_1;
  37746. }
  37747. var s = this._stride;
  37748. // 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
  37749. var lastFree = new DynamicFloatArrayElementInfo();
  37750. lastFree.offset = this.totalElementCount * s;
  37751. this._freeEntries.push(lastFree);
  37752. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  37753. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  37754. var firstFreeSlotOffset = sortedFree[0].offset;
  37755. var freeZoneSize = 1;
  37756. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  37757. var prevOffset = sortedFree[0].offset;
  37758. for (var i = 1; i < sortedFree.length; i++) {
  37759. // 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
  37760. if (firstFreeSlotOffset >= occupiedZoneSize) {
  37761. break;
  37762. }
  37763. var curFree = sortedFree[i];
  37764. var curOffset = curFree.offset;
  37765. // Compute the distance between this offset and the previous
  37766. var distance = curOffset - prevOffset;
  37767. // If the distance is the stride size, they are adjacent, it good, move to the next
  37768. if (distance === s) {
  37769. // Free zone is one element bigger
  37770. ++freeZoneSize;
  37771. // as we're about to iterate to the next, the cur becomes the previous...
  37772. prevOffset = curOffset;
  37773. continue;
  37774. }
  37775. // Distance is bigger, which means there's x element between the previous free and this one
  37776. var usedRange = (distance / s) - 1;
  37777. // Two cases the free zone is smaller than the data to move or bigger
  37778. // Copy what can fit in the free zone
  37779. var curMoveOffset = curOffset - s;
  37780. var copyCount = Math.min(freeZoneSize, usedRange);
  37781. for (var j = 0; j < copyCount; j++) {
  37782. var freeI = firstFreeSlotOffset / s;
  37783. var curI = curMoveOffset / s;
  37784. var moveEl = sortedAll[curI];
  37785. this._moveElement(moveEl, firstFreeSlotOffset);
  37786. var replacedEl = sortedAll[freeI];
  37787. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  37788. replacedEl.offset = curMoveOffset;
  37789. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  37790. sortedAll[freeI] = moveEl;
  37791. sortedAll[curI] = replacedEl;
  37792. curMoveOffset -= s;
  37793. firstFreeSlotOffset += s;
  37794. }
  37795. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  37796. if (freeZoneSize <= usedRange) {
  37797. firstFreeSlotOffset = curMoveOffset + s;
  37798. freeZoneSize = 1 + copyCount;
  37799. }
  37800. else {
  37801. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  37802. }
  37803. // as we're about to iterate to the next, the cur becomes the previous...
  37804. prevOffset = curOffset;
  37805. }
  37806. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  37807. this._lastUsed = firstFreeSlotOffset - s;
  37808. this._firstFree = firstFreeSlotOffset;
  37809. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  37810. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  37811. this._allEntries = sortedAll;
  37812. return elementsBuffer;
  37813. };
  37814. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  37815. for (var i = 0; i < this._stride; i++) {
  37816. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  37817. }
  37818. element.offset = destOffset;
  37819. };
  37820. DynamicFloatArray.prototype._growBuffer = function () {
  37821. // Allocate the new buffer with 50% more entries, copy the content of the current one
  37822. var newElCount = Math.floor(this.totalElementCount * 1.5);
  37823. var newBuffer = new Float32Array(newElCount * this._stride);
  37824. newBuffer.set(this.buffer);
  37825. var curCount = this.totalElementCount;
  37826. var addedCount = newElCount - this.totalElementCount;
  37827. for (var i = 0; i < addedCount; i++) {
  37828. var element = new DynamicFloatArrayElementInfo();
  37829. element.offset = (curCount + i) * this.stride;
  37830. this._allEntries.push(element);
  37831. this._freeEntries[addedCount - i - 1] = element;
  37832. }
  37833. this._firstFree = curCount * this.stride;
  37834. this.buffer = newBuffer;
  37835. };
  37836. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  37837. /**
  37838. * Get the total count of entries that can fit in the current buffer
  37839. * @returns the elements count
  37840. */
  37841. get: function () {
  37842. return this._allEntries.length;
  37843. },
  37844. enumerable: true,
  37845. configurable: true
  37846. });
  37847. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  37848. /**
  37849. * Get the count of free entries that can still be allocated without resizing the buffer
  37850. * @returns the free elements count
  37851. */
  37852. get: function () {
  37853. return this._freeEntries.length;
  37854. },
  37855. enumerable: true,
  37856. configurable: true
  37857. });
  37858. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  37859. /**
  37860. * Get the count of allocated elements
  37861. * @returns the allocated elements count
  37862. */
  37863. get: function () {
  37864. return this._allEntries.length - this._freeEntries.length;
  37865. },
  37866. enumerable: true,
  37867. configurable: true
  37868. });
  37869. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  37870. /**
  37871. * Return the size of one element in float
  37872. * @returns the size in float
  37873. */
  37874. get: function () {
  37875. return this._stride;
  37876. },
  37877. enumerable: true,
  37878. configurable: true
  37879. });
  37880. DynamicFloatArray.prototype.sort = function () {
  37881. var _this = this;
  37882. if (!this.compareValueOffset) {
  37883. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  37884. }
  37885. var count = this.usedElementCount;
  37886. // Do we have to (re)create the sort table?
  37887. if (!this._sortTable || this._sortTable.length < count) {
  37888. // 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...
  37889. var newCount = Math.min(this.totalElementCount, count * 2);
  37890. this._sortTable = new Array(newCount);
  37891. }
  37892. if (!this._sortedTable || this._sortedTable.length !== count) {
  37893. this._sortedTable = new Array(count);
  37894. }
  37895. // Because, you know...
  37896. this.pack();
  37897. //let stride = this.stride;
  37898. //for (let i = 0; i < count; i++) {
  37899. // let si = this._sortTable[i];
  37900. // if (!si) {
  37901. // si = new SortInfo();
  37902. // this._sortTable[i] = si;
  37903. // }
  37904. // si.entry = this._allEntries[i];
  37905. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  37906. // si.swapedOffset = null;
  37907. // this._sortedTable[i] = si;
  37908. //}
  37909. var curOffset = 0;
  37910. var stride = this.stride;
  37911. for (var i = 0; i < count; i++, curOffset += stride) {
  37912. var si = this._sortTable[i];
  37913. if (!si) {
  37914. si = new SortInfo();
  37915. this._sortTable[i] = si;
  37916. }
  37917. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  37918. si.offset = curOffset;
  37919. si.swapedOffset = null;
  37920. this._sortedTable[i] = si;
  37921. }
  37922. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  37923. if (this.sortingAscending) {
  37924. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  37925. }
  37926. else {
  37927. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  37928. }
  37929. var swapElements = function (src, dst) {
  37930. for (var i = 0; i < stride; i++) {
  37931. var tps = _this.buffer[dst + i];
  37932. _this.buffer[dst + i] = _this.buffer[src + i];
  37933. _this.buffer[src + i] = tps;
  37934. }
  37935. };
  37936. // 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:
  37937. // 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),
  37938. // and I still want something with a good algorithm complexity.
  37939. // 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,
  37940. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  37941. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  37942. // 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
  37943. // until we find a SortInfo object without a swapedOffset which means we got the right location
  37944. // 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
  37945. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  37946. for (var i = 0; i < count; i++) {
  37947. // Get the element to move
  37948. var sourceSI = this._sortedTable[i];
  37949. var destSI = this._sortTable[i];
  37950. var sourceOff = sourceSI.offset;
  37951. // If the source changed location, find the new one
  37952. if (sourceSI.swapedOffset) {
  37953. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  37954. var curSI = sourceSI;
  37955. while (curSI.swapedOffset) {
  37956. curSI = this._sortTable[curSI.swapedOffset / stride];
  37957. }
  37958. // Finally get the right location
  37959. sourceOff = curSI.offset;
  37960. }
  37961. // Tag the element being replaced with its new location
  37962. destSI.swapedOffset = sourceOff;
  37963. // Swap elements (only if needed)
  37964. if (sourceOff !== destSI.offset) {
  37965. swapElements(sourceOff, destSI.offset);
  37966. }
  37967. // Update the offset in the corresponding DFAE
  37968. //sourceSI.entry.offset = destSI.entry.offset;
  37969. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  37970. }
  37971. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  37972. return true;
  37973. };
  37974. return DynamicFloatArray;
  37975. })();
  37976. BABYLON.DynamicFloatArray = DynamicFloatArray;
  37977. var SortInfo = (function () {
  37978. function SortInfo() {
  37979. this.compareData = this.offset = this.swapedOffset = null;
  37980. }
  37981. return SortInfo;
  37982. })();
  37983. })(BABYLON || (BABYLON = {}));
  37984. var BABYLON;
  37985. (function (BABYLON) {
  37986. /**
  37987. * This class given information about a given character.
  37988. */
  37989. var CharInfo = (function () {
  37990. function CharInfo() {
  37991. }
  37992. return CharInfo;
  37993. })();
  37994. BABYLON.CharInfo = CharInfo;
  37995. var FontTexture = (function (_super) {
  37996. __extends(FontTexture, _super);
  37997. /**
  37998. * Create a new instance of the FontTexture class
  37999. * @param name the name of the texture
  38000. * @param font the font to use, use the W3C CSS notation
  38001. * @param scene the scene that owns the texture
  38002. * @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
  38003. * @param samplingMode the texture sampling mode
  38004. * @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.
  38005. */
  38006. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample) {
  38007. if (maxCharCount === void 0) { maxCharCount = 200; }
  38008. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38009. if (superSample === void 0) { superSample = false; }
  38010. _super.call(this, null, scene, true, false, samplingMode);
  38011. this._charInfos = {};
  38012. this._curCharCount = 0;
  38013. this._lastUpdateCharCount = -1;
  38014. this._usedCounter = 1;
  38015. this.name = name;
  38016. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38017. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38018. this._superSample = false;
  38019. if (superSample) {
  38020. var sfont = this.getSuperSampleFont(font);
  38021. if (sfont) {
  38022. this._superSample = true;
  38023. font = sfont;
  38024. }
  38025. }
  38026. // First canvas creation to determine the size of the texture to create
  38027. this._canvas = document.createElement("canvas");
  38028. this._context = this._canvas.getContext("2d");
  38029. this._context.font = font;
  38030. this._context.fillStyle = "white";
  38031. this._cachedFontId = null;
  38032. var res = this.getFontHeight(font);
  38033. this._lineHeightSuper = res.height;
  38034. this._lineHeight = this._superSample ? (this._lineHeightSuper / 2) : this._lineHeightSuper;
  38035. this._offset = res.offset - 1;
  38036. var maxCharWidth = this._context.measureText("W").width;
  38037. this._spaceWidthSuper = this._context.measureText(" ").width;
  38038. this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
  38039. // This is an approximate size, but should always be able to fit at least the maxCharCount
  38040. var totalEstSurface = this._lineHeightSuper * maxCharWidth * maxCharCount;
  38041. var edge = Math.sqrt(totalEstSurface);
  38042. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  38043. // Create the texture that will store the font characters
  38044. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  38045. var textureSize = this.getSize();
  38046. this.hasAlpha = true;
  38047. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  38048. this._canvas = document.createElement("canvas");
  38049. this._canvas.width = textureSize.width;
  38050. this._canvas.height = textureSize.height;
  38051. this._context = this._canvas.getContext("2d");
  38052. this._context.textBaseline = "top";
  38053. this._context.font = font;
  38054. this._context.fillStyle = "white";
  38055. this._context.imageSmoothingEnabled = false;
  38056. this._currentFreePosition = BABYLON.Vector2.Zero();
  38057. // Add the basic ASCII based characters
  38058. for (var i = 0x20; i < 0x7F; i++) {
  38059. var c = String.fromCharCode(i);
  38060. this.getChar(c);
  38061. }
  38062. this.update();
  38063. }
  38064. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  38065. get: function () {
  38066. return this._superSample;
  38067. },
  38068. enumerable: true,
  38069. configurable: true
  38070. });
  38071. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  38072. get: function () {
  38073. return this._spaceWidth;
  38074. },
  38075. enumerable: true,
  38076. configurable: true
  38077. });
  38078. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  38079. get: function () {
  38080. return this._lineHeight;
  38081. },
  38082. enumerable: true,
  38083. configurable: true
  38084. });
  38085. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample) {
  38086. if (supersample === void 0) { supersample = false; }
  38087. var s = scene;
  38088. if (!s.__fontTextureCache__) {
  38089. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  38090. }
  38091. var dic = s.__fontTextureCache__;
  38092. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  38093. var ft = dic.get(lfn);
  38094. if (ft) {
  38095. ++ft._usedCounter;
  38096. return ft;
  38097. }
  38098. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample);
  38099. ft._cachedFontId = lfn;
  38100. dic.add(lfn, ft);
  38101. return ft;
  38102. };
  38103. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample) {
  38104. if (supersample === void 0) { supersample = false; }
  38105. var s = scene;
  38106. var dic = s.__fontTextureCache__;
  38107. if (!dic) {
  38108. return;
  38109. }
  38110. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  38111. var font = dic.get(lfn);
  38112. if (--font._usedCounter === 0) {
  38113. dic.remove(lfn);
  38114. font.dispose();
  38115. }
  38116. };
  38117. /**
  38118. * Make sure the given char is present in the font map.
  38119. * @param char the character to get or add
  38120. * @return the CharInfo instance corresponding to the given character
  38121. */
  38122. FontTexture.prototype.getChar = function (char) {
  38123. if (char.length !== 1) {
  38124. return null;
  38125. }
  38126. var info = this._charInfos[char];
  38127. if (info) {
  38128. return info;
  38129. }
  38130. info = new CharInfo();
  38131. var measure = this._context.measureText(char);
  38132. var textureSize = this.getSize();
  38133. // we reached the end of the current line?
  38134. var width = Math.round(measure.width);
  38135. var xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  38136. var yMargin = xMargin;
  38137. if (this._currentFreePosition.x + width + xMargin > textureSize.width) {
  38138. this._currentFreePosition.x = 0;
  38139. this._currentFreePosition.y += this._lineHeightSuper + yMargin;
  38140. // No more room?
  38141. if (this._currentFreePosition.y > textureSize.height) {
  38142. return this.getChar("!");
  38143. }
  38144. }
  38145. // Draw the character in the texture
  38146. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  38147. // Fill the CharInfo object
  38148. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  38149. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  38150. info.charWidth = this._superSample ? (width / 2) : width;
  38151. // Add the info structure
  38152. this._charInfos[char] = info;
  38153. this._curCharCount++;
  38154. // Set the next position
  38155. this._currentFreePosition.x += width + xMargin;
  38156. return info;
  38157. };
  38158. FontTexture.prototype.measureText = function (text, tabulationSize) {
  38159. if (tabulationSize === void 0) { tabulationSize = 4; }
  38160. var maxWidth = 0;
  38161. var curWidth = 0;
  38162. var lineCount = 1;
  38163. var charxpos = 0;
  38164. // Parse each char of the string
  38165. for (var _i = 0; _i < text.length; _i++) {
  38166. var char = text[_i];
  38167. // Next line feed?
  38168. if (char === "\n") {
  38169. maxWidth = Math.max(maxWidth, curWidth);
  38170. charxpos = 0;
  38171. curWidth = 0;
  38172. ++lineCount;
  38173. continue;
  38174. }
  38175. // Tabulation ?
  38176. if (char === "\t") {
  38177. var nextPos = charxpos + tabulationSize;
  38178. nextPos = nextPos - (nextPos % tabulationSize);
  38179. curWidth += (nextPos - charxpos) * this.spaceWidth;
  38180. charxpos = nextPos;
  38181. continue;
  38182. }
  38183. if (char < " ") {
  38184. continue;
  38185. }
  38186. curWidth += this.getChar(char).charWidth;
  38187. ++charxpos;
  38188. }
  38189. maxWidth = Math.max(maxWidth, curWidth);
  38190. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  38191. };
  38192. FontTexture.prototype.getSuperSampleFont = function (font) {
  38193. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  38194. 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*$/;
  38195. var res = font.toLocaleLowerCase().match(regex);
  38196. if (res == null) {
  38197. return null;
  38198. }
  38199. var size = parseInt(res[4]);
  38200. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  38201. var newFont = "";
  38202. for (var j = 1; j < res.length; j++) {
  38203. if (res[j] != null) {
  38204. newFont += res[j] + " ";
  38205. }
  38206. }
  38207. return newFont;
  38208. };
  38209. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  38210. FontTexture.prototype.getFontHeight = function (font) {
  38211. var fontDraw = document.createElement("canvas");
  38212. var ctx = fontDraw.getContext('2d');
  38213. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  38214. ctx.textBaseline = 'top';
  38215. ctx.fillStyle = 'white';
  38216. ctx.font = font;
  38217. ctx.fillText('jH|', 0, 0);
  38218. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  38219. var start = -1;
  38220. var end = -1;
  38221. for (var row = 0; row < fontDraw.height; row++) {
  38222. for (var column = 0; column < fontDraw.width; column++) {
  38223. var index = (row * fontDraw.width + column) * 4;
  38224. if (pixels[index] === 0) {
  38225. if (column === fontDraw.width - 1 && start !== -1) {
  38226. end = row;
  38227. row = fontDraw.height;
  38228. break;
  38229. }
  38230. continue;
  38231. }
  38232. else {
  38233. if (start === -1) {
  38234. start = row;
  38235. }
  38236. break;
  38237. }
  38238. }
  38239. }
  38240. return { height: (end - start) + 1, offset: start - 1 };
  38241. };
  38242. Object.defineProperty(FontTexture.prototype, "canRescale", {
  38243. get: function () {
  38244. return false;
  38245. },
  38246. enumerable: true,
  38247. configurable: true
  38248. });
  38249. FontTexture.prototype.getContext = function () {
  38250. return this._context;
  38251. };
  38252. /**
  38253. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  38254. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  38255. */
  38256. FontTexture.prototype.update = function () {
  38257. // Update only if there's new char added since the previous update
  38258. if (this._lastUpdateCharCount < this._curCharCount) {
  38259. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  38260. this._lastUpdateCharCount = this._curCharCount;
  38261. }
  38262. };
  38263. // cloning should be prohibited, there's no point to duplicate this texture at all
  38264. FontTexture.prototype.clone = function () {
  38265. return null;
  38266. };
  38267. /**
  38268. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  38269. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  38270. */
  38271. FontTexture.prototype.incCachedFontTextureCounter = function () {
  38272. ++this._usedCounter;
  38273. };
  38274. /**
  38275. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  38276. */
  38277. FontTexture.prototype.decCachedFontTextureCounter = function () {
  38278. var s = this.getScene();
  38279. var dic = s.__fontTextureCache__;
  38280. if (!dic) {
  38281. return;
  38282. }
  38283. if (--this._usedCounter === 0) {
  38284. dic.remove(this._cachedFontId);
  38285. this.dispose();
  38286. }
  38287. };
  38288. return FontTexture;
  38289. })(BABYLON.Texture);
  38290. BABYLON.FontTexture = FontTexture;
  38291. })(BABYLON || (BABYLON = {}));
  38292. var BABYLON;
  38293. (function (BABYLON) {
  38294. var MapTexture = (function (_super) {
  38295. __extends(MapTexture, _super);
  38296. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  38297. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38298. if (useMipMap === void 0) { useMipMap = false; }
  38299. _super.call(this, null, scene, !useMipMap, false, samplingMode);
  38300. this.name = name;
  38301. this._size = size;
  38302. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38303. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38304. // Create the rectPackMap that will allocate portion of the texture
  38305. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  38306. // Create the texture that will store the content
  38307. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  38308. }
  38309. /**
  38310. * Allocate a rectangle of a given size in the texture map
  38311. * @param size the size of the rectangle to allocation
  38312. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  38313. */
  38314. MapTexture.prototype.allocateRect = function (size) {
  38315. return this._rectPackingMap.addRect(size);
  38316. };
  38317. /**
  38318. * Free a given rectangle from the texture map
  38319. * @param rectInfo the instance corresponding to the rect to free.
  38320. */
  38321. MapTexture.prototype.freeRect = function (rectInfo) {
  38322. if (rectInfo) {
  38323. rectInfo.freeContent();
  38324. }
  38325. };
  38326. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  38327. /**
  38328. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  38329. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  38330. * @returns {}
  38331. */
  38332. get: function () {
  38333. return this._rectPackingMap.freeSpace;
  38334. },
  38335. enumerable: true,
  38336. configurable: true
  38337. });
  38338. /**
  38339. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  38340. * 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.
  38341. * Don't forget to call unbindTexture when you're done rendering
  38342. * @param rect the zone to render to
  38343. * @param clear true to clear the portion's color/depth data
  38344. */
  38345. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  38346. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  38347. };
  38348. /**
  38349. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  38350. * 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.
  38351. * Don't forget to call unbindTexture when you're done rendering
  38352. * @param pos the position into the texture
  38353. * @param size the portion to fit the clip space to
  38354. * @param clear true to clear the portion's color/depth data
  38355. */
  38356. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  38357. var engine = this.getScene().getEngine();
  38358. engine.bindFramebuffer(this._texture);
  38359. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  38360. if (clear) {
  38361. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  38362. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  38363. }
  38364. };
  38365. /**
  38366. * Unbind the texture map from the rendering engine.
  38367. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  38368. * @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.
  38369. */
  38370. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  38371. // Dump ?
  38372. if (dumpForDebug) {
  38373. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  38374. }
  38375. var engine = this.getScene().getEngine();
  38376. if (this._replacedViewport) {
  38377. engine.setViewport(this._replacedViewport);
  38378. this._replacedViewport = null;
  38379. }
  38380. engine.unBindFramebuffer(this._texture);
  38381. };
  38382. Object.defineProperty(MapTexture.prototype, "canRescale", {
  38383. get: function () {
  38384. return false;
  38385. },
  38386. enumerable: true,
  38387. configurable: true
  38388. });
  38389. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  38390. // Anyway, there's not much point to use this method for this kind of texture I guess
  38391. MapTexture.prototype.clone = function () {
  38392. return null;
  38393. };
  38394. return MapTexture;
  38395. })(BABYLON.Texture);
  38396. BABYLON.MapTexture = MapTexture;
  38397. })(BABYLON || (BABYLON = {}));
  38398. var BABYLON;
  38399. (function (BABYLON) {
  38400. /**
  38401. * Stores 2D Bounding Information.
  38402. * This class handles a circle area and a bounding rectangle one.
  38403. */
  38404. var BoundingInfo2D = (function () {
  38405. function BoundingInfo2D() {
  38406. this.radius = 0;
  38407. this.center = BABYLON.Vector2.Zero();
  38408. this.extent = BABYLON.Vector2.Zero();
  38409. }
  38410. /**
  38411. * Create a BoundingInfo2D object from a given size
  38412. * @param size the size that will be used to set the extend, radius will be computed from it.
  38413. */
  38414. BoundingInfo2D.CreateFromSize = function (size) {
  38415. var r = new BoundingInfo2D();
  38416. BoundingInfo2D.CreateFromSizeToRef(size, r);
  38417. return r;
  38418. };
  38419. /**
  38420. * Create a BoundingInfo2D object from a given radius
  38421. * @param radius the radius to use, the extent will be computed from it.
  38422. */
  38423. BoundingInfo2D.CreateFromRadius = function (radius) {
  38424. var r = new BoundingInfo2D();
  38425. BoundingInfo2D.CreateFromRadiusToRef(radius, r);
  38426. return r;
  38427. };
  38428. /**
  38429. * Create a BoundingInfo2D object from a list of points.
  38430. * The resulted object will be the smallest bounding area that includes all the given points.
  38431. * @param points an array of points to compute the bounding object from.
  38432. */
  38433. BoundingInfo2D.CreateFromPoints = function (points) {
  38434. var r = new BoundingInfo2D();
  38435. BoundingInfo2D.CreateFromPointsToRef(points, r);
  38436. return r;
  38437. };
  38438. /**
  38439. * Update a BoundingInfo2D object using the given Size as input
  38440. * @param size the bounding data will be computed from this size.
  38441. * @param b must be a valid/allocated object, it will contain the result of the operation
  38442. */
  38443. BoundingInfo2D.CreateFromSizeToRef = function (size, b) {
  38444. if (!size) {
  38445. size = BABYLON.Size.Zero();
  38446. }
  38447. b.center.x = +size.width / 2;
  38448. b.center.y = +size.height / 2;
  38449. b.extent.x = b.center.x;
  38450. b.extent.y = b.center.y;
  38451. b.radius = b.extent.length();
  38452. };
  38453. /**
  38454. * Update a BoundingInfo2D object using the given radius as input
  38455. * @param radius the bounding data will be computed from this radius
  38456. * @param b must be a valid/allocated object, it will contain the result of the operation
  38457. */
  38458. BoundingInfo2D.CreateFromRadiusToRef = function (radius, b) {
  38459. b.center.x = b.center.y = 0;
  38460. var r = +radius;
  38461. b.extent.x = r;
  38462. b.extent.y = r;
  38463. b.radius = r;
  38464. };
  38465. /**
  38466. * Update a BoundingInfo2D object using the given points array as input
  38467. * @param points the point array to use to update the bounding data
  38468. * @param b must be a valid/allocated object, it will contain the result of the operation
  38469. */
  38470. BoundingInfo2D.CreateFromPointsToRef = function (points, b) {
  38471. var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
  38472. for (var _i = 0; _i < points.length; _i++) {
  38473. var p = points[_i];
  38474. xmin = Math.min(p.x, xmin);
  38475. xmax = Math.max(p.x, xmax);
  38476. ymin = Math.min(p.y, ymin);
  38477. ymax = Math.max(p.y, ymax);
  38478. }
  38479. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b);
  38480. };
  38481. /**
  38482. * Update a BoundingInfo2D object using the given min/max values as input
  38483. * @param xmin the smallest x coordinate
  38484. * @param xmax the biggest x coordinate
  38485. * @param ymin the smallest y coordinate
  38486. * @param ymax the buggest y coordinate
  38487. * @param b must be a valid/allocated object, it will contain the result of the operation
  38488. */
  38489. BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b) {
  38490. var w = xmax - xmin;
  38491. var h = ymax - ymin;
  38492. b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
  38493. b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
  38494. b.radius = b.extent.length();
  38495. };
  38496. /**
  38497. * Duplicate this instance and return a new one
  38498. * @return the duplicated instance
  38499. */
  38500. BoundingInfo2D.prototype.clone = function () {
  38501. var r = new BoundingInfo2D();
  38502. r.center = this.center.clone();
  38503. r.radius = this.radius;
  38504. r.extent = this.extent.clone();
  38505. return r;
  38506. };
  38507. BoundingInfo2D.prototype.clear = function () {
  38508. this.center.copyFromFloats(0, 0);
  38509. this.radius = 0;
  38510. this.extent.copyFromFloats(0, 0);
  38511. };
  38512. BoundingInfo2D.prototype.copyFrom = function (src) {
  38513. this.center.copyFrom(src.center);
  38514. this.radius = src.radius;
  38515. this.extent.copyFrom(src.extent);
  38516. };
  38517. /**
  38518. * return the max extend of the bounding info
  38519. */
  38520. BoundingInfo2D.prototype.max = function () {
  38521. var r = BABYLON.Vector2.Zero();
  38522. this.maxToRef(r);
  38523. return r;
  38524. };
  38525. /**
  38526. * Update a vector2 with the max extend of the bounding info
  38527. * @param result must be a valid/allocated vector2 that will contain the result of the operation
  38528. */
  38529. BoundingInfo2D.prototype.maxToRef = function (result) {
  38530. result.x = this.center.x + this.extent.x;
  38531. result.y = this.center.y + this.extent.y;
  38532. };
  38533. /**
  38534. * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
  38535. * @param matrix the transformation matrix to apply
  38536. * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
  38537. */
  38538. BoundingInfo2D.prototype.transform = function (matrix) {
  38539. var r = new BoundingInfo2D();
  38540. this.transformToRef(matrix, r);
  38541. return r;
  38542. };
  38543. /**
  38544. * Compute the union of this BoundingInfo2D with a given one, returns a new BoundingInfo2D as a result
  38545. * @param other the second BoundingInfo2D to compute the union with this one
  38546. * @return a new instance containing the result of the union
  38547. */
  38548. BoundingInfo2D.prototype.union = function (other) {
  38549. var r = new BoundingInfo2D();
  38550. this.unionToRef(other, r);
  38551. return r;
  38552. };
  38553. /**
  38554. * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
  38555. * 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.
  38556. * @param matrix The matrix to use to compute the transformation
  38557. * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
  38558. */
  38559. BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
  38560. // Construct a bounding box based on the extent values
  38561. var p = BoundingInfo2D._transform;
  38562. p[0].x = this.center.x + this.extent.x;
  38563. p[0].y = this.center.y + this.extent.y;
  38564. p[1].x = this.center.x + this.extent.x;
  38565. p[1].y = this.center.y - this.extent.y;
  38566. p[2].x = this.center.x - this.extent.x;
  38567. p[2].y = this.center.y - this.extent.y;
  38568. p[3].x = this.center.x - this.extent.x;
  38569. p[3].y = this.center.y + this.extent.y;
  38570. // Transform the four points of the bounding box with the matrix
  38571. for (var i = 0; i < 4; i++) {
  38572. BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
  38573. }
  38574. BoundingInfo2D.CreateFromPointsToRef(p, result);
  38575. };
  38576. /**
  38577. * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
  38578. * 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.
  38579. * @param other the second object used to compute the union
  38580. * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
  38581. */
  38582. BoundingInfo2D.prototype.unionToRef = function (other, result) {
  38583. var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
  38584. var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
  38585. var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
  38586. var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
  38587. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
  38588. };
  38589. /**
  38590. * Check if the given point is inside the BoundingInfo.
  38591. * The test is first made on the radius, then inside the rectangle described by the extent
  38592. * @param pickPosition the position to test
  38593. * @return true if the point is inside, false otherwise
  38594. */
  38595. BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
  38596. // is it inside the radius?
  38597. var pickLocal = pickPosition.subtract(this.center);
  38598. if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
  38599. // is it inside the rectangle?
  38600. return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
  38601. }
  38602. return false;
  38603. };
  38604. BoundingInfo2D._transform = new Array(BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero());
  38605. return BoundingInfo2D;
  38606. })();
  38607. BABYLON.BoundingInfo2D = BoundingInfo2D;
  38608. })(BABYLON || (BABYLON = {}));
  38609. var BABYLON;
  38610. (function (BABYLON) {
  38611. /**
  38612. * Base class implementing the ILocable interface.
  38613. * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
  38614. */
  38615. var LockableBase = (function () {
  38616. function LockableBase() {
  38617. }
  38618. LockableBase.prototype.isLocked = function () {
  38619. return this._isLocked;
  38620. };
  38621. LockableBase.prototype.lock = function () {
  38622. if (this._isLocked) {
  38623. return true;
  38624. }
  38625. this.onLock();
  38626. this._isLocked = true;
  38627. return false;
  38628. };
  38629. /**
  38630. * Protected handler that will be called when the instance is about to be locked.
  38631. */
  38632. LockableBase.prototype.onLock = function () {
  38633. };
  38634. return LockableBase;
  38635. })();
  38636. BABYLON.LockableBase = LockableBase;
  38637. var SolidColorBrush2D = (function (_super) {
  38638. __extends(SolidColorBrush2D, _super);
  38639. function SolidColorBrush2D(color, lock) {
  38640. if (lock === void 0) { lock = false; }
  38641. _super.call(this);
  38642. this._color = color;
  38643. if (lock) {
  38644. {
  38645. this.lock();
  38646. }
  38647. }
  38648. }
  38649. /**
  38650. * Return true if the brush is transparent, false if it's totally opaque
  38651. */
  38652. SolidColorBrush2D.prototype.isTransparent = function () {
  38653. return this._color && this._color.a < 1.0;
  38654. };
  38655. Object.defineProperty(SolidColorBrush2D.prototype, "color", {
  38656. /**
  38657. * The color used by this instance to render
  38658. * @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.
  38659. */
  38660. get: function () {
  38661. return this._color;
  38662. },
  38663. set: function (value) {
  38664. if (this.isLocked()) {
  38665. return;
  38666. }
  38667. this._color = value;
  38668. },
  38669. enumerable: true,
  38670. configurable: true
  38671. });
  38672. /**
  38673. * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
  38674. */
  38675. SolidColorBrush2D.prototype.toString = function () {
  38676. return this._color.toHexString();
  38677. };
  38678. SolidColorBrush2D = __decorate([
  38679. BABYLON.className("SolidColorBrush2D")
  38680. ], SolidColorBrush2D);
  38681. return SolidColorBrush2D;
  38682. })(LockableBase);
  38683. BABYLON.SolidColorBrush2D = SolidColorBrush2D;
  38684. var GradientColorBrush2D = (function (_super) {
  38685. __extends(GradientColorBrush2D, _super);
  38686. function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
  38687. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  38688. if (rotation === void 0) { rotation = 0; }
  38689. if (scale === void 0) { scale = 1; }
  38690. if (lock === void 0) { lock = false; }
  38691. _super.call(this);
  38692. this._color1 = color1;
  38693. this._color2 = color2;
  38694. this._translation = translation;
  38695. this._rotation = rotation;
  38696. this._scale = scale;
  38697. if (lock) {
  38698. this.lock();
  38699. }
  38700. }
  38701. /**
  38702. * Return true if the brush is transparent, false if it's totally opaque
  38703. */
  38704. GradientColorBrush2D.prototype.isTransparent = function () {
  38705. return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
  38706. };
  38707. Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
  38708. /**
  38709. * First color, the blend will start from this color
  38710. */
  38711. get: function () {
  38712. return this._color1;
  38713. },
  38714. set: function (value) {
  38715. if (this.isLocked()) {
  38716. return;
  38717. }
  38718. this._color1 = value;
  38719. },
  38720. enumerable: true,
  38721. configurable: true
  38722. });
  38723. Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
  38724. /**
  38725. * Second color, the blend will end to this color
  38726. */
  38727. get: function () {
  38728. return this._color2;
  38729. },
  38730. set: function (value) {
  38731. if (this.isLocked()) {
  38732. return;
  38733. }
  38734. this._color2 = value;
  38735. },
  38736. enumerable: true,
  38737. configurable: true
  38738. });
  38739. Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
  38740. /**
  38741. * Translation vector to apply on the blend
  38742. * Default is [0;0]
  38743. */
  38744. get: function () {
  38745. return this._translation;
  38746. },
  38747. set: function (value) {
  38748. if (this.isLocked()) {
  38749. return;
  38750. }
  38751. this._translation = value;
  38752. },
  38753. enumerable: true,
  38754. configurable: true
  38755. });
  38756. Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
  38757. /**
  38758. * Rotation in radian to apply to the brush
  38759. * Default direction of the brush is vertical, you can change this using this property.
  38760. * Default is 0.
  38761. */
  38762. get: function () {
  38763. return this._rotation;
  38764. },
  38765. set: function (value) {
  38766. if (this.isLocked()) {
  38767. return;
  38768. }
  38769. this._rotation = value;
  38770. },
  38771. enumerable: true,
  38772. configurable: true
  38773. });
  38774. Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
  38775. /**
  38776. * Scale factor to apply to the gradient.
  38777. * Default is 1: no scale.
  38778. */
  38779. get: function () {
  38780. return this._scale;
  38781. },
  38782. set: function (value) {
  38783. if (this.isLocked()) {
  38784. return;
  38785. }
  38786. this._scale = value;
  38787. },
  38788. enumerable: true,
  38789. configurable: true
  38790. });
  38791. /**
  38792. * Return a string describing the brush
  38793. */
  38794. GradientColorBrush2D.prototype.toString = function () {
  38795. return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
  38796. };
  38797. /**
  38798. * Build a unique key string for the given parameters
  38799. */
  38800. GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
  38801. return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
  38802. };
  38803. GradientColorBrush2D = __decorate([
  38804. BABYLON.className("GradientColorBrush2D")
  38805. ], GradientColorBrush2D);
  38806. return GradientColorBrush2D;
  38807. })(LockableBase);
  38808. BABYLON.GradientColorBrush2D = GradientColorBrush2D;
  38809. })(BABYLON || (BABYLON = {}));
  38810. var BABYLON;
  38811. (function (BABYLON) {
  38812. var Prim2DClassInfo = (function () {
  38813. function Prim2DClassInfo() {
  38814. }
  38815. return Prim2DClassInfo;
  38816. })();
  38817. BABYLON.Prim2DClassInfo = Prim2DClassInfo;
  38818. var Prim2DPropInfo = (function () {
  38819. function Prim2DPropInfo() {
  38820. }
  38821. Prim2DPropInfo.PROPKIND_MODEL = 1;
  38822. Prim2DPropInfo.PROPKIND_INSTANCE = 2;
  38823. Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
  38824. return Prim2DPropInfo;
  38825. })();
  38826. BABYLON.Prim2DPropInfo = Prim2DPropInfo;
  38827. /**
  38828. * Custom type of the propertyChanged observable
  38829. */
  38830. var PropertyChangedInfo = (function () {
  38831. function PropertyChangedInfo() {
  38832. }
  38833. return PropertyChangedInfo;
  38834. })();
  38835. BABYLON.PropertyChangedInfo = PropertyChangedInfo;
  38836. var ClassTreeInfo = (function () {
  38837. function ClassTreeInfo(baseClass, type, classContentFactory) {
  38838. this._baseClass = baseClass;
  38839. this._type = type;
  38840. this._subClasses = new Array();
  38841. this._levelContent = new BABYLON.StringDictionary();
  38842. this._classContentFactory = classContentFactory;
  38843. }
  38844. Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
  38845. get: function () {
  38846. if (!this._classContent) {
  38847. this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
  38848. }
  38849. return this._classContent;
  38850. },
  38851. enumerable: true,
  38852. configurable: true
  38853. });
  38854. Object.defineProperty(ClassTreeInfo.prototype, "type", {
  38855. get: function () {
  38856. return this._type;
  38857. },
  38858. enumerable: true,
  38859. configurable: true
  38860. });
  38861. Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
  38862. get: function () {
  38863. return this._levelContent;
  38864. },
  38865. enumerable: true,
  38866. configurable: true
  38867. });
  38868. Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
  38869. get: function () {
  38870. if (!this._fullContent) {
  38871. var dic = new BABYLON.StringDictionary();
  38872. var curLevel = this;
  38873. while (curLevel) {
  38874. curLevel.levelContent.forEach(function (k, v) { return dic.add(k, v); });
  38875. curLevel = curLevel._baseClass;
  38876. }
  38877. this._fullContent = dic;
  38878. }
  38879. return this._fullContent;
  38880. },
  38881. enumerable: true,
  38882. configurable: true
  38883. });
  38884. ClassTreeInfo.prototype.getLevelOf = function (type) {
  38885. // Are we already there?
  38886. if (type === this._type) {
  38887. return this;
  38888. }
  38889. var baseProto = Object.getPrototypeOf(type);
  38890. var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
  38891. if (!curProtoContent) {
  38892. this.getLevelOf(baseProto);
  38893. }
  38894. return this.getOrAddType(baseProto, type);
  38895. };
  38896. ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
  38897. // Are we at the level corresponding to the baseType?
  38898. // If so, get or add the level we're looking for
  38899. if (baseType === this._type) {
  38900. for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
  38901. var subType = _a[_i];
  38902. if (subType.type === type) {
  38903. return subType.node;
  38904. }
  38905. }
  38906. var node = new ClassTreeInfo(this, type, this._classContentFactory);
  38907. var info = { type: type, node: node };
  38908. this._subClasses.push(info);
  38909. return info.node;
  38910. }
  38911. // Recurse down to keep looking for the node corresponding to the baseTypeName
  38912. for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
  38913. var subType = _c[_b];
  38914. var info = subType.node.getOrAddType(baseType, type);
  38915. if (info) {
  38916. return info;
  38917. }
  38918. }
  38919. return null;
  38920. };
  38921. ClassTreeInfo.get = function (type) {
  38922. var dic = type["__classTreeInfo"];
  38923. if (!dic) {
  38924. return null;
  38925. }
  38926. return dic.getLevelOf(type);
  38927. };
  38928. ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
  38929. var dic = type["__classTreeInfo"];
  38930. if (!dic) {
  38931. dic = new ClassTreeInfo(null, type, classContentFactory);
  38932. type["__classTreeInfo"] = dic;
  38933. }
  38934. return dic;
  38935. };
  38936. return ClassTreeInfo;
  38937. })();
  38938. BABYLON.ClassTreeInfo = ClassTreeInfo;
  38939. var SmartPropertyPrim = (function () {
  38940. function SmartPropertyPrim() {
  38941. this._flags = 0;
  38942. this._modelKey = null;
  38943. this._instanceDirtyFlags = 0;
  38944. this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
  38945. this.animations = new Array();
  38946. }
  38947. Object.defineProperty(SmartPropertyPrim.prototype, "isDisposed", {
  38948. /**
  38949. * Check if the object is disposed or not.
  38950. * @returns true if the object is dispose, false otherwise.
  38951. */
  38952. get: function () {
  38953. return this._isFlagSet(SmartPropertyPrim.flagIsDisposed);
  38954. },
  38955. enumerable: true,
  38956. configurable: true
  38957. });
  38958. /**
  38959. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  38960. * @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.
  38961. */
  38962. SmartPropertyPrim.prototype.dispose = function () {
  38963. if (this.isDisposed) {
  38964. return false;
  38965. }
  38966. // Don't set to null, it may upset somebody...
  38967. this.animations.splice(0);
  38968. this._setFlags(SmartPropertyPrim.flagIsDisposed);
  38969. return true;
  38970. };
  38971. /**
  38972. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  38973. * Look at Sprite2D for more information
  38974. */
  38975. SmartPropertyPrim.prototype.getAnimatables = function () {
  38976. return new Array();
  38977. };
  38978. Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
  38979. /**
  38980. * Property giving the Model Key associated to the property.
  38981. * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
  38982. * @returns the model key string.
  38983. */
  38984. get: function () {
  38985. var _this = this;
  38986. // No need to compute it?
  38987. if (!this._isFlagSet(SmartPropertyPrim.flagModelDirty) && this._modelKey) {
  38988. return this._modelKey;
  38989. }
  38990. var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
  38991. var propDic = this.propDic;
  38992. propDic.forEach(function (k, v) {
  38993. if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  38994. var propVal = _this[v.name];
  38995. // 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
  38996. if (propVal && propVal.constructor === Array) {
  38997. var firstVal = propVal[0];
  38998. if (!firstVal) {
  38999. propVal = 0;
  39000. }
  39001. else {
  39002. propVal = BABYLON.Tools.hashCodeFromStream(BABYLON.Tools.arrayOrStringFeeder(propVal));
  39003. }
  39004. }
  39005. modelKey += v.name + ":" + ((propVal != null) ? ((v.typeLevelCompare) ? BABYLON.Tools.getClassName(propVal) : propVal.toString()) : "[null]") + ";";
  39006. }
  39007. });
  39008. this._clearFlags(SmartPropertyPrim.flagModelDirty);
  39009. this._modelKey = modelKey;
  39010. return modelKey;
  39011. },
  39012. enumerable: true,
  39013. configurable: true
  39014. });
  39015. Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
  39016. /**
  39017. * States if the Primitive is dirty and should be rendered again next time.
  39018. * @returns true is dirty, false otherwise
  39019. */
  39020. get: function () {
  39021. return (this._instanceDirtyFlags !== 0) || this._areSomeFlagsSet(SmartPropertyPrim.flagModelDirty | SmartPropertyPrim.flagPositioningDirty | SmartPropertyPrim.flagLayoutDirty);
  39022. },
  39023. enumerable: true,
  39024. configurable: true
  39025. });
  39026. Object.defineProperty(SmartPropertyPrim.prototype, "propDic", {
  39027. /**
  39028. * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
  39029. * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
  39030. */
  39031. get: function () {
  39032. if (!this._propInfo) {
  39033. var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
  39034. if (!cti) {
  39035. throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
  39036. }
  39037. this._propInfo = cti.fullContent;
  39038. }
  39039. return this._propInfo;
  39040. },
  39041. enumerable: true,
  39042. configurable: true
  39043. });
  39044. SmartPropertyPrim._createPropInfo = function (target, propName, propId, dirtyBoundingInfo, dirtyParentBoundingBox, typeLevelCompare, kind) {
  39045. var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
  39046. var node = dic.getLevelOf(target);
  39047. var propInfo = node.levelContent.get(propId.toString());
  39048. if (propInfo) {
  39049. throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
  39050. }
  39051. // Create, setup and add the PropInfo object to our prop dictionary
  39052. propInfo = new Prim2DPropInfo();
  39053. propInfo.id = propId;
  39054. propInfo.flagId = Math.pow(2, propId);
  39055. propInfo.kind = kind;
  39056. propInfo.name = propName;
  39057. propInfo.dirtyBoundingInfo = dirtyBoundingInfo;
  39058. propInfo.dirtyParentBoundingInfo = dirtyParentBoundingBox;
  39059. propInfo.typeLevelCompare = typeLevelCompare;
  39060. node.levelContent.add(propName, propInfo);
  39061. return propInfo;
  39062. };
  39063. SmartPropertyPrim._checkUnchanged = function (curValue, newValue) {
  39064. // Nothing to nothing: nothing to do!
  39065. if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
  39066. return true;
  39067. }
  39068. // Check value unchanged
  39069. if ((curValue != null) && (newValue != null)) {
  39070. if (typeof (curValue.equals) == "function") {
  39071. if (curValue.equals(newValue)) {
  39072. return true;
  39073. }
  39074. }
  39075. else {
  39076. if (curValue === newValue) {
  39077. return true;
  39078. }
  39079. }
  39080. }
  39081. return false;
  39082. };
  39083. SmartPropertyPrim.prototype._triggerPropertyChanged = function (propInfo, newValue) {
  39084. if (this.isDisposed) {
  39085. return;
  39086. }
  39087. if (!propInfo) {
  39088. return;
  39089. }
  39090. this._handlePropChanged(undefined, newValue, propInfo.name, propInfo, propInfo.typeLevelCompare);
  39091. };
  39092. SmartPropertyPrim.prototype._boundingBoxDirty = function () {
  39093. this._setFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  39094. // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
  39095. if (this instanceof BABYLON.Prim2DBase) {
  39096. var curprim = this;
  39097. while (curprim) {
  39098. curprim._setFlags(SmartPropertyPrim.flagBoundingInfoDirty);
  39099. if (curprim.isSizeAuto) {
  39100. curprim.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  39101. curprim._setFlags(SmartPropertyPrim.flagPositioningDirty);
  39102. }
  39103. if (curprim instanceof BABYLON.Group2D) {
  39104. if (curprim.isRenderableGroup) {
  39105. break;
  39106. }
  39107. }
  39108. curprim = curprim.parent;
  39109. }
  39110. }
  39111. };
  39112. SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  39113. // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
  39114. if (propInfo.dirtyBoundingInfo) {
  39115. this._boundingBoxDirty();
  39116. }
  39117. else if (propInfo.dirtyParentBoundingInfo) {
  39118. var p = this._parent;
  39119. if (p != null) {
  39120. p._boundingBoxDirty();
  39121. }
  39122. }
  39123. // Trigger property changed
  39124. var info = SmartPropertyPrim.propChangedInfo;
  39125. info.oldValue = curValue;
  39126. info.newValue = newValue;
  39127. info.propertyName = propName;
  39128. var propMask = propInfo.flagId;
  39129. this.propertyChanged.notifyObservers(info, propMask);
  39130. // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
  39131. if (this instanceof BABYLON.Group2D) {
  39132. this.handleGroupChanged(propInfo);
  39133. }
  39134. // Check for parent layout dirty
  39135. if (this instanceof BABYLON.Prim2DBase) {
  39136. var p = this._parent;
  39137. if (p != null && p.layoutEngine && (p.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
  39138. p._setLayoutDirty();
  39139. }
  39140. }
  39141. // For type level compare, if there's a change of type it's a change of model, otherwise we issue an instance change
  39142. var instanceDirty = false;
  39143. if (typeLevelCompare && curValue != null && newValue != null) {
  39144. var cvProto = curValue.__proto__;
  39145. var nvProto = newValue.__proto__;
  39146. instanceDirty = (cvProto === nvProto);
  39147. }
  39148. // Set the dirty flags
  39149. if (!instanceDirty && (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL)) {
  39150. if (!this.isDirty) {
  39151. this._setFlags(SmartPropertyPrim.flagModelDirty);
  39152. }
  39153. }
  39154. else if (instanceDirty || (propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
  39155. this.onPrimitivePropertyDirty(propMask);
  39156. }
  39157. };
  39158. SmartPropertyPrim.prototype.onPrimitivePropertyDirty = function (propFlagId) {
  39159. this.onPrimBecomesDirty();
  39160. this._instanceDirtyFlags |= propFlagId;
  39161. };
  39162. SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
  39163. };
  39164. /**
  39165. * Check if a given set of properties are dirty or not.
  39166. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  39167. * @return true if at least one property is dirty, false if none of them are.
  39168. */
  39169. SmartPropertyPrim.prototype.checkPropertiesDirty = function (flags) {
  39170. return (this._instanceDirtyFlags & flags) !== 0;
  39171. };
  39172. /**
  39173. * Clear a given set of properties.
  39174. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  39175. * @return the new set of property still marked as dirty
  39176. */
  39177. SmartPropertyPrim.prototype.clearPropertiesDirty = function (flags) {
  39178. this._instanceDirtyFlags &= ~flags;
  39179. return this._instanceDirtyFlags;
  39180. };
  39181. SmartPropertyPrim.prototype._resetPropertiesDirty = function () {
  39182. this._instanceDirtyFlags = 0;
  39183. this._clearFlags(SmartPropertyPrim.flagPrimInDirtyList | SmartPropertyPrim.flagNeedRefresh);
  39184. };
  39185. Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
  39186. /**
  39187. * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
  39188. */
  39189. get: function () {
  39190. if (this._isFlagSet(SmartPropertyPrim.flagLevelBoundingInfoDirty)) {
  39191. this.updateLevelBoundingInfo();
  39192. this._clearFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  39193. }
  39194. return this._levelBoundingInfo;
  39195. },
  39196. enumerable: true,
  39197. configurable: true
  39198. });
  39199. /**
  39200. * This method must be overridden by a given Primitive implementation to compute its boundingInfo
  39201. */
  39202. SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
  39203. };
  39204. /**
  39205. * Property method called when the Primitive becomes dirty
  39206. */
  39207. SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
  39208. };
  39209. SmartPropertyPrim._hookProperty = function (propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, kind) {
  39210. return function (target, propName, descriptor) {
  39211. var propInfo = SmartPropertyPrim._createPropInfo(target, propName, propId, dirtyBoundingInfo, dirtyParentBoundingBox, typeLevelCompare, kind);
  39212. if (piStore) {
  39213. piStore(propInfo);
  39214. }
  39215. var getter = descriptor.get, setter = descriptor.set;
  39216. // Overload the property setter implementation to add our own logic
  39217. descriptor.set = function (val) {
  39218. // check for disposed first, do nothing
  39219. if (this.isDisposed) {
  39220. return;
  39221. }
  39222. var curVal = getter.call(this);
  39223. if (SmartPropertyPrim._checkUnchanged(curVal, val)) {
  39224. return;
  39225. }
  39226. // Cast the object we're working one
  39227. var prim = this;
  39228. // Change the value
  39229. setter.call(this, val);
  39230. // Notify change, dirty flags update
  39231. prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
  39232. };
  39233. };
  39234. };
  39235. /**
  39236. * Add an externally attached data from its key.
  39237. * This method call will fail and return false, if such key already exists.
  39238. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  39239. * @param key the unique key that identifies the data
  39240. * @param data the data object to associate to the key for this Engine instance
  39241. * @return true if no such key were already present and the data was added successfully, false otherwise
  39242. */
  39243. SmartPropertyPrim.prototype.addExternalData = function (key, data) {
  39244. if (!this._externalData) {
  39245. this._externalData = new BABYLON.StringDictionary();
  39246. }
  39247. return this._externalData.add(key, data);
  39248. };
  39249. /**
  39250. * Get an externally attached data from its key
  39251. * @param key the unique key that identifies the data
  39252. * @return the associated data, if present (can be null), or undefined if not present
  39253. */
  39254. SmartPropertyPrim.prototype.getExternalData = function (key) {
  39255. if (!this._externalData) {
  39256. return null;
  39257. }
  39258. return this._externalData.get(key);
  39259. };
  39260. /**
  39261. * Get an externally attached data from its key, create it using a factory if it's not already present
  39262. * @param key the unique key that identifies the data
  39263. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  39264. * @return the associated data, can be null if the factory returned null.
  39265. */
  39266. SmartPropertyPrim.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  39267. if (!this._externalData) {
  39268. this._externalData = new BABYLON.StringDictionary();
  39269. }
  39270. return this._externalData.getOrAddWithFactory(key, factory);
  39271. };
  39272. /**
  39273. * Remove an externally attached data from the Engine instance
  39274. * @param key the unique key that identifies the data
  39275. * @return true if the data was successfully removed, false if it doesn't exist
  39276. */
  39277. SmartPropertyPrim.prototype.removeExternalData = function (key) {
  39278. if (!this._externalData) {
  39279. return false;
  39280. }
  39281. return this._externalData.remove(key);
  39282. };
  39283. /**
  39284. * Check if a given flag is set
  39285. * @param flag the flag value
  39286. * @return true if set, false otherwise
  39287. */
  39288. SmartPropertyPrim.prototype._isFlagSet = function (flag) {
  39289. return (this._flags & flag) !== 0;
  39290. };
  39291. /**
  39292. * Check if all given flags are set
  39293. * @param flags the flags ORed
  39294. * @return true if all the flags are set, false otherwise
  39295. */
  39296. SmartPropertyPrim.prototype._areAllFlagsSet = function (flags) {
  39297. return (this._flags & flags) === flags;
  39298. };
  39299. /**
  39300. * Check if at least one flag of the given flags is set
  39301. * @param flags the flags ORed
  39302. * @return true if at least one flag is set, false otherwise
  39303. */
  39304. SmartPropertyPrim.prototype._areSomeFlagsSet = function (flags) {
  39305. return (this._flags & flags) !== 0;
  39306. };
  39307. /**
  39308. * Clear the given flags
  39309. * @param flags the flags to clear
  39310. */
  39311. SmartPropertyPrim.prototype._clearFlags = function (flags) {
  39312. this._flags &= ~flags;
  39313. };
  39314. /**
  39315. * Set the given flags to true state
  39316. * @param flags the flags ORed to set
  39317. * @return the flags state before this call
  39318. */
  39319. SmartPropertyPrim.prototype._setFlags = function (flags) {
  39320. var cur = this._flags;
  39321. this._flags |= flags;
  39322. return cur;
  39323. };
  39324. /**
  39325. * Change the state of the given flags
  39326. * @param flags the flags ORed to change
  39327. * @param state true to set them, false to clear them
  39328. */
  39329. SmartPropertyPrim.prototype._changeFlags = function (flags, state) {
  39330. if (state) {
  39331. this._flags |= flags;
  39332. }
  39333. else {
  39334. this._flags &= ~flags;
  39335. }
  39336. };
  39337. SmartPropertyPrim.propChangedInfo = new PropertyChangedInfo();
  39338. SmartPropertyPrim.flagIsDisposed = 0x0000001; // set if the object is already disposed
  39339. SmartPropertyPrim.flagLevelBoundingInfoDirty = 0x0000002; // set if the primitive's level bounding box (not including children) is dirty
  39340. SmartPropertyPrim.flagModelDirty = 0x0000004; // set if the model must be changed
  39341. SmartPropertyPrim.flagLayoutDirty = 0x0000008; // set if the layout must be computed
  39342. SmartPropertyPrim.flagLevelVisible = 0x0000010; // set if the primitive is set as visible for its level only
  39343. SmartPropertyPrim.flagBoundingInfoDirty = 0x0000020; // set if the primitive's overall bounding box (including children) is dirty
  39344. SmartPropertyPrim.flagIsPickable = 0x0000040; // set if the primitive can be picked during interaction
  39345. SmartPropertyPrim.flagIsVisible = 0x0000080; // set if the primitive is concretely visible (use the levelVisible of parents)
  39346. SmartPropertyPrim.flagVisibilityChanged = 0x0000100; // set if there was a transition between visible/hidden status
  39347. SmartPropertyPrim.flagPositioningDirty = 0x0000200; // set if the primitive positioning must be computed
  39348. SmartPropertyPrim.flagTrackedGroup = 0x0000400; // set if the group2D is tracking a scene node
  39349. SmartPropertyPrim.flagWorldCacheChanged = 0x0000800; // set if the cached bitmap of a world space canvas changed
  39350. SmartPropertyPrim.flagChildrenFlatZOrder = 0x0001000; // set if all the children (direct and indirect) will share the same Z-Order
  39351. SmartPropertyPrim.flagZOrderDirty = 0x0002000; // set if the Z-Order for this prim and its children must be recomputed
  39352. SmartPropertyPrim.flagActualOpacityDirty = 0x0004000; // set if the actualOpactity should be recomputed
  39353. SmartPropertyPrim.flagPrimInDirtyList = 0x0008000; // set if the primitive is in the primDirtyList
  39354. SmartPropertyPrim.flagIsContainer = 0x0010000; // set if the primitive is a container
  39355. SmartPropertyPrim.flagNeedRefresh = 0x0020000; // set if the primitive wasn't successful at refresh
  39356. SmartPropertyPrim.flagActualScaleDirty = 0x0040000; // set if the actualScale property needs to be recomputed
  39357. SmartPropertyPrim.flagDontInheritParentScale = 0x0080000; // set if the actualScale must not use its parent's scale to be computed
  39358. SmartPropertyPrim.flagGlobalTransformDirty = 0x0100000; // set if the global transform must be recomputed due to a local transform change
  39359. SmartPropertyPrim.flagLayoutBoundingInfoDirty = 0x0100000; // set if the layout bounding info is dirty
  39360. SmartPropertyPrim = __decorate([
  39361. BABYLON.className("SmartPropertyPrim")
  39362. ], SmartPropertyPrim);
  39363. return SmartPropertyPrim;
  39364. })();
  39365. BABYLON.SmartPropertyPrim = SmartPropertyPrim;
  39366. function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  39367. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  39368. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  39369. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  39370. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_MODEL);
  39371. }
  39372. BABYLON.modelLevelProperty = modelLevelProperty;
  39373. function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  39374. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  39375. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  39376. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  39377. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_INSTANCE);
  39378. }
  39379. BABYLON.instanceLevelProperty = instanceLevelProperty;
  39380. function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  39381. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  39382. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  39383. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  39384. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_DYNAMIC);
  39385. }
  39386. BABYLON.dynamicLevelProperty = dynamicLevelProperty;
  39387. })(BABYLON || (BABYLON = {}));
  39388. var BABYLON;
  39389. (function (BABYLON) {
  39390. var PrepareRender2DContext = (function () {
  39391. function PrepareRender2DContext() {
  39392. this.forceRefreshPrimitive = false;
  39393. }
  39394. return PrepareRender2DContext;
  39395. })();
  39396. BABYLON.PrepareRender2DContext = PrepareRender2DContext;
  39397. var Render2DContext = (function () {
  39398. function Render2DContext(renderMode) {
  39399. this._renderMode = renderMode;
  39400. this.useInstancing = false;
  39401. this.groupInfoPartData = null;
  39402. this.partDataStartIndex = this.partDataEndIndex = null;
  39403. this.instancedBuffers = null;
  39404. }
  39405. Object.defineProperty(Render2DContext.prototype, "renderMode", {
  39406. /**
  39407. * Define which render Mode should be used to render the primitive: one of Render2DContext.RenderModeXxxx property
  39408. */
  39409. get: function () {
  39410. return this._renderMode;
  39411. },
  39412. enumerable: true,
  39413. configurable: true
  39414. });
  39415. Object.defineProperty(Render2DContext, "RenderModeOpaque", {
  39416. /**
  39417. * The set of primitives to render is opaque.
  39418. * This is the first rendering pass. All Opaque primitives are rendered. Depth Compare and Write are both enabled.
  39419. */
  39420. get: function () {
  39421. return Render2DContext._renderModeOpaque;
  39422. },
  39423. enumerable: true,
  39424. configurable: true
  39425. });
  39426. Object.defineProperty(Render2DContext, "RenderModeAlphaTest", {
  39427. /**
  39428. * The set of primitives to render is using Alpha Test (aka masking).
  39429. * 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.
  39430. */
  39431. get: function () {
  39432. return Render2DContext._renderModeAlphaTest;
  39433. },
  39434. enumerable: true,
  39435. configurable: true
  39436. });
  39437. Object.defineProperty(Render2DContext, "RenderModeTransparent", {
  39438. /**
  39439. * The set of primitives to render is transparent.
  39440. * 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.
  39441. */
  39442. get: function () {
  39443. return Render2DContext._renderModeTransparent;
  39444. },
  39445. enumerable: true,
  39446. configurable: true
  39447. });
  39448. Render2DContext._renderModeOpaque = 1;
  39449. Render2DContext._renderModeAlphaTest = 2;
  39450. Render2DContext._renderModeTransparent = 3;
  39451. return Render2DContext;
  39452. })();
  39453. BABYLON.Render2DContext = Render2DContext;
  39454. /**
  39455. * This class store information for the pointerEventObservable Observable.
  39456. * 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.
  39457. */
  39458. var PrimitivePointerInfo = (function () {
  39459. function PrimitivePointerInfo() {
  39460. this.primitivePointerPos = BABYLON.Vector2.Zero();
  39461. this.tilt = BABYLON.Vector2.Zero();
  39462. this.cancelBubble = false;
  39463. }
  39464. Object.defineProperty(PrimitivePointerInfo, "PointerOver", {
  39465. // 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.
  39466. /**
  39467. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  39468. * Bubbles: yes
  39469. */
  39470. get: function () {
  39471. return PrimitivePointerInfo._pointerOver;
  39472. },
  39473. enumerable: true,
  39474. configurable: true
  39475. });
  39476. Object.defineProperty(PrimitivePointerInfo, "PointerEnter", {
  39477. /**
  39478. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  39479. * Bubbles: no
  39480. */
  39481. get: function () {
  39482. return PrimitivePointerInfo._pointerEnter;
  39483. },
  39484. enumerable: true,
  39485. configurable: true
  39486. });
  39487. Object.defineProperty(PrimitivePointerInfo, "PointerDown", {
  39488. /**
  39489. * 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.
  39490. * Bubbles: yes
  39491. */
  39492. get: function () {
  39493. return PrimitivePointerInfo._pointerDown;
  39494. },
  39495. enumerable: true,
  39496. configurable: true
  39497. });
  39498. Object.defineProperty(PrimitivePointerInfo, "PointerMouseWheel", {
  39499. /**
  39500. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  39501. * Bubbles: yes
  39502. */
  39503. get: function () {
  39504. return PrimitivePointerInfo._pointerMouseWheel;
  39505. },
  39506. enumerable: true,
  39507. configurable: true
  39508. });
  39509. Object.defineProperty(PrimitivePointerInfo, "PointerMove", {
  39510. /**
  39511. * 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.
  39512. * Bubbles: yes
  39513. */
  39514. get: function () {
  39515. return PrimitivePointerInfo._pointerMove;
  39516. },
  39517. enumerable: true,
  39518. configurable: true
  39519. });
  39520. Object.defineProperty(PrimitivePointerInfo, "PointerUp", {
  39521. /**
  39522. * 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.
  39523. * Bubbles: yes
  39524. */
  39525. get: function () {
  39526. return PrimitivePointerInfo._pointerUp;
  39527. },
  39528. enumerable: true,
  39529. configurable: true
  39530. });
  39531. Object.defineProperty(PrimitivePointerInfo, "PointerOut", {
  39532. /**
  39533. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  39534. * Bubbles: yes
  39535. */
  39536. get: function () {
  39537. return PrimitivePointerInfo._pointerOut;
  39538. },
  39539. enumerable: true,
  39540. configurable: true
  39541. });
  39542. Object.defineProperty(PrimitivePointerInfo, "PointerLeave", {
  39543. /**
  39544. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  39545. * Bubbles: no
  39546. */
  39547. get: function () {
  39548. return PrimitivePointerInfo._pointerLeave;
  39549. },
  39550. enumerable: true,
  39551. configurable: true
  39552. });
  39553. Object.defineProperty(PrimitivePointerInfo, "PointerGotCapture", {
  39554. /**
  39555. * 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.
  39556. * Bubbles: yes
  39557. */
  39558. get: function () {
  39559. return PrimitivePointerInfo._pointerGotCapture;
  39560. },
  39561. enumerable: true,
  39562. configurable: true
  39563. });
  39564. Object.defineProperty(PrimitivePointerInfo, "PointerLostCapture", {
  39565. /**
  39566. * This event type is raised after pointer capture is released for a pointer.
  39567. * Bubbles: yes
  39568. */
  39569. get: function () {
  39570. return PrimitivePointerInfo._pointerLostCapture;
  39571. },
  39572. enumerable: true,
  39573. configurable: true
  39574. });
  39575. Object.defineProperty(PrimitivePointerInfo, "MouseWheelPrecision", {
  39576. get: function () {
  39577. return PrimitivePointerInfo._mouseWheelPrecision;
  39578. },
  39579. enumerable: true,
  39580. configurable: true
  39581. });
  39582. PrimitivePointerInfo.prototype.updateRelatedTarget = function (prim, primPointerPos) {
  39583. this.relatedTarget = prim;
  39584. this.relatedTargetPointerPos = primPointerPos;
  39585. };
  39586. PrimitivePointerInfo.getEventTypeName = function (mask) {
  39587. switch (mask) {
  39588. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  39589. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  39590. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  39591. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  39592. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  39593. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  39594. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  39595. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  39596. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  39597. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  39598. }
  39599. };
  39600. PrimitivePointerInfo._pointerOver = 0x0001;
  39601. PrimitivePointerInfo._pointerEnter = 0x0002;
  39602. PrimitivePointerInfo._pointerDown = 0x0004;
  39603. PrimitivePointerInfo._pointerMouseWheel = 0x0008;
  39604. PrimitivePointerInfo._pointerMove = 0x0010;
  39605. PrimitivePointerInfo._pointerUp = 0x0020;
  39606. PrimitivePointerInfo._pointerOut = 0x0040;
  39607. PrimitivePointerInfo._pointerLeave = 0x0080;
  39608. PrimitivePointerInfo._pointerGotCapture = 0x0100;
  39609. PrimitivePointerInfo._pointerLostCapture = 0x0200;
  39610. PrimitivePointerInfo._mouseWheelPrecision = 3.0;
  39611. return PrimitivePointerInfo;
  39612. })();
  39613. BABYLON.PrimitivePointerInfo = PrimitivePointerInfo;
  39614. /**
  39615. * Defines the horizontal and vertical alignment information for a Primitive.
  39616. */
  39617. var PrimitiveAlignment = (function () {
  39618. function PrimitiveAlignment(changeCallback) {
  39619. this._changedCallback = changeCallback;
  39620. this._horizontal = PrimitiveAlignment.AlignLeft;
  39621. this._vertical = PrimitiveAlignment.AlignBottom;
  39622. }
  39623. Object.defineProperty(PrimitiveAlignment, "AlignLeft", {
  39624. /**
  39625. * Alignment is made relative to the left edge of the Primitive. Valid for horizontal alignment only.
  39626. */
  39627. get: function () { return PrimitiveAlignment._AlignLeft; },
  39628. enumerable: true,
  39629. configurable: true
  39630. });
  39631. Object.defineProperty(PrimitiveAlignment, "AlignTop", {
  39632. /**
  39633. * Alignment is made relative to the top edge of the Primitive. Valid for vertical alignment only.
  39634. */
  39635. get: function () { return PrimitiveAlignment._AlignTop; },
  39636. enumerable: true,
  39637. configurable: true
  39638. });
  39639. Object.defineProperty(PrimitiveAlignment, "AlignRight", {
  39640. /**
  39641. * Alignment is made relative to the right edge of the Primitive. Valid for horizontal alignment only.
  39642. */
  39643. get: function () { return PrimitiveAlignment._AlignRight; },
  39644. enumerable: true,
  39645. configurable: true
  39646. });
  39647. Object.defineProperty(PrimitiveAlignment, "AlignBottom", {
  39648. /**
  39649. * Alignment is made relative to the bottom edge of the Primitive. Valid for vertical alignment only.
  39650. */
  39651. get: function () { return PrimitiveAlignment._AlignBottom; },
  39652. enumerable: true,
  39653. configurable: true
  39654. });
  39655. Object.defineProperty(PrimitiveAlignment, "AlignCenter", {
  39656. /**
  39657. * Alignment is made to center the content from equal distance to the opposite edges of the Primitive
  39658. */
  39659. get: function () { return PrimitiveAlignment._AlignCenter; },
  39660. enumerable: true,
  39661. configurable: true
  39662. });
  39663. Object.defineProperty(PrimitiveAlignment, "AlignStretch", {
  39664. /**
  39665. * The content is stretched toward the opposite edges of the Primitive
  39666. */
  39667. get: function () { return PrimitiveAlignment._AlignStretch; },
  39668. enumerable: true,
  39669. configurable: true
  39670. });
  39671. Object.defineProperty(PrimitiveAlignment.prototype, "horizontal", {
  39672. /**
  39673. * Get/set the horizontal alignment. Use one of the AlignXXX static properties of this class
  39674. */
  39675. get: function () {
  39676. return this._horizontal;
  39677. },
  39678. set: function (value) {
  39679. if (this._horizontal === value) {
  39680. return;
  39681. }
  39682. this._horizontal = value;
  39683. this._changedCallback();
  39684. },
  39685. enumerable: true,
  39686. configurable: true
  39687. });
  39688. Object.defineProperty(PrimitiveAlignment.prototype, "vertical", {
  39689. /**
  39690. * Get/set the vertical alignment. Use one of the AlignXXX static properties of this class
  39691. */
  39692. get: function () {
  39693. return this._vertical;
  39694. },
  39695. set: function (value) {
  39696. if (this._vertical === value) {
  39697. return;
  39698. }
  39699. this._vertical = value;
  39700. this._changedCallback();
  39701. },
  39702. enumerable: true,
  39703. configurable: true
  39704. });
  39705. /**
  39706. * Set the horizontal alignment from a string value.
  39707. * @param text can be either: 'left','right','center','stretch'
  39708. */
  39709. PrimitiveAlignment.prototype.setHorizontal = function (text) {
  39710. var v = text.trim().toLocaleLowerCase();
  39711. switch (v) {
  39712. case "left":
  39713. this.horizontal = PrimitiveAlignment.AlignLeft;
  39714. return;
  39715. case "right":
  39716. this.horizontal = PrimitiveAlignment.AlignRight;
  39717. return;
  39718. case "center":
  39719. this.horizontal = PrimitiveAlignment.AlignCenter;
  39720. return;
  39721. case "stretch":
  39722. this.horizontal = PrimitiveAlignment.AlignStretch;
  39723. return;
  39724. }
  39725. };
  39726. /**
  39727. * Set the vertical alignment from a string value.
  39728. * @param text can be either: 'top','bottom','center','stretch'
  39729. */
  39730. PrimitiveAlignment.prototype.setVertical = function (text) {
  39731. var v = text.trim().toLocaleLowerCase();
  39732. switch (v) {
  39733. case "top":
  39734. this.vertical = PrimitiveAlignment.AlignTop;
  39735. return;
  39736. case "bottom":
  39737. this.vertical = PrimitiveAlignment.AlignBottom;
  39738. return;
  39739. case "center":
  39740. this.vertical = PrimitiveAlignment.AlignCenter;
  39741. return;
  39742. case "stretch":
  39743. this.vertical = PrimitiveAlignment.AlignStretch;
  39744. return;
  39745. }
  39746. };
  39747. /**
  39748. * Set the horizontal and or vertical alignments from a string value.
  39749. * @param text can be: [<h:|horizontal:><left|right|center|stretch>], [<v:|vertical:><top|bottom|center|stretch>]
  39750. */
  39751. PrimitiveAlignment.prototype.fromString = function (value) {
  39752. var m = value.trim().split(",");
  39753. for (var _i = 0; _i < m.length; _i++) {
  39754. var v = m[_i];
  39755. v = v.toLocaleLowerCase().trim();
  39756. // Horizontal
  39757. var i = v.indexOf("h:");
  39758. if (i === -1) {
  39759. i = v.indexOf("horizontal:");
  39760. }
  39761. if (i !== -1) {
  39762. v = v.substr(v.indexOf(":") + 1);
  39763. this.setHorizontal(v);
  39764. continue;
  39765. }
  39766. // Vertical
  39767. i = v.indexOf("v:");
  39768. if (i === -1) {
  39769. i = v.indexOf("vertical:");
  39770. }
  39771. if (i !== -1) {
  39772. v = v.substr(v.indexOf(":") + 1);
  39773. this.setVertical(v);
  39774. continue;
  39775. }
  39776. }
  39777. };
  39778. PrimitiveAlignment._AlignLeft = 1;
  39779. PrimitiveAlignment._AlignTop = 1; // Same as left
  39780. PrimitiveAlignment._AlignRight = 2;
  39781. PrimitiveAlignment._AlignBottom = 2; // Same as right
  39782. PrimitiveAlignment._AlignCenter = 3;
  39783. PrimitiveAlignment._AlignStretch = 4;
  39784. return PrimitiveAlignment;
  39785. })();
  39786. BABYLON.PrimitiveAlignment = PrimitiveAlignment;
  39787. /**
  39788. * Stores information about a Primitive that was intersected
  39789. */
  39790. var PrimitiveIntersectedInfo = (function () {
  39791. function PrimitiveIntersectedInfo(prim, intersectionLocation) {
  39792. this.prim = prim;
  39793. this.intersectionLocation = intersectionLocation;
  39794. }
  39795. return PrimitiveIntersectedInfo;
  39796. })();
  39797. BABYLON.PrimitiveIntersectedInfo = PrimitiveIntersectedInfo;
  39798. /**
  39799. * Define a thickness toward every edges of a Primitive to allow margin and padding.
  39800. * The thickness can be expressed as pixels, percentages, inherit the value of the parent primitive or be auto.
  39801. */
  39802. var PrimitiveThickness = (function () {
  39803. function PrimitiveThickness(parentAccess, changedCallback) {
  39804. this._parentAccess = parentAccess;
  39805. this._changedCallback = changedCallback;
  39806. this._pixels = new Array(4);
  39807. this._percentages = new Array(4);
  39808. this._setType(0, PrimitiveThickness.Auto);
  39809. this._setType(1, PrimitiveThickness.Auto);
  39810. this._setType(2, PrimitiveThickness.Auto);
  39811. this._setType(3, PrimitiveThickness.Auto);
  39812. this._pixels[0] = 0;
  39813. this._pixels[1] = 0;
  39814. this._pixels[2] = 0;
  39815. this._pixels[3] = 0;
  39816. }
  39817. /**
  39818. * Set the thickness from a string value
  39819. * @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.
  39820. * Values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39821. */
  39822. PrimitiveThickness.prototype.fromString = function (thickness) {
  39823. this._clear();
  39824. var m = thickness.trim().split(",");
  39825. // Special case, one value to apply to all edges
  39826. if (m.length === 1 && thickness.indexOf(":") === -1) {
  39827. this._setStringValue(m[0], 0, false);
  39828. this._setStringValue(m[0], 1, false);
  39829. this._setStringValue(m[0], 2, false);
  39830. this._setStringValue(m[0], 3, false);
  39831. this._changedCallback();
  39832. return;
  39833. }
  39834. var res = false;
  39835. for (var _i = 0; _i < m.length; _i++) {
  39836. var cm = m[_i];
  39837. res = this._extractString(cm, false) || res;
  39838. }
  39839. if (!res) {
  39840. throw new Error("Can't parse the string to create a PrimitiveMargin object, format must be: 'top: <value>, left:<value>, right:<value>, bottom:<value>");
  39841. }
  39842. // Check the margin that weren't set and set them in auto
  39843. if ((this._flags & 0x000F) === 0)
  39844. this._flags |= PrimitiveThickness.Pixel << 0;
  39845. if ((this._flags & 0x00F0) === 0)
  39846. this._flags |= PrimitiveThickness.Pixel << 4;
  39847. if ((this._flags & 0x0F00) === 0)
  39848. this._flags |= PrimitiveThickness.Pixel << 8;
  39849. if ((this._flags & 0xF000) === 0)
  39850. this._flags |= PrimitiveThickness.Pixel << 12;
  39851. this._changedCallback();
  39852. };
  39853. /**
  39854. * Set the thickness from multiple string
  39855. * Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39856. * @param top the top thickness to set
  39857. * @param left the left thickness to set
  39858. * @param right the right thickness to set
  39859. * @param bottom the bottom thickness to set
  39860. */
  39861. PrimitiveThickness.prototype.fromStrings = function (top, left, right, bottom) {
  39862. this._clear();
  39863. this._setStringValue(top, 0, false);
  39864. this._setStringValue(left, 1, false);
  39865. this._setStringValue(right, 2, false);
  39866. this._setStringValue(bottom, 3, false);
  39867. this._changedCallback();
  39868. return this;
  39869. };
  39870. /**
  39871. * Set the thickness from pixel values
  39872. * @param top the top thickness in pixels to set
  39873. * @param left the left thickness in pixels to set
  39874. * @param right the right thickness in pixels to set
  39875. * @param bottom the bottom thickness in pixels to set
  39876. */
  39877. PrimitiveThickness.prototype.fromPixels = function (top, left, right, bottom) {
  39878. this._clear();
  39879. this._pixels[0] = top;
  39880. this._pixels[1] = left;
  39881. this._pixels[2] = right;
  39882. this._pixels[3] = bottom;
  39883. this._changedCallback();
  39884. return this;
  39885. };
  39886. /**
  39887. * Apply the same pixel value to all edges
  39888. * @param margin the value to set, in pixels.
  39889. */
  39890. PrimitiveThickness.prototype.fromUniformPixels = function (margin) {
  39891. this._clear();
  39892. this._pixels[0] = margin;
  39893. this._pixels[1] = margin;
  39894. this._pixels[2] = margin;
  39895. this._pixels[3] = margin;
  39896. this._changedCallback();
  39897. return this;
  39898. };
  39899. /**
  39900. * Set all edges in auto
  39901. */
  39902. PrimitiveThickness.prototype.auto = function () {
  39903. this._clear();
  39904. this._flags = (PrimitiveThickness.Auto << 0) | (PrimitiveThickness.Auto << 4) | (PrimitiveThickness.Auto << 8) | (PrimitiveThickness.Auto << 12);
  39905. this._pixels[0] = 0;
  39906. this._pixels[1] = 0;
  39907. this._pixels[2] = 0;
  39908. this._pixels[3] = 0;
  39909. this._changedCallback();
  39910. return this;
  39911. };
  39912. PrimitiveThickness.prototype._clear = function () {
  39913. this._flags = 0;
  39914. this._pixels[0] = 0;
  39915. this._pixels[1] = 0;
  39916. this._pixels[2] = 0;
  39917. this._pixels[3] = 0;
  39918. this._percentages[0] = null;
  39919. this._percentages[1] = null;
  39920. this._percentages[2] = null;
  39921. this._percentages[3] = null;
  39922. };
  39923. PrimitiveThickness.prototype._extractString = function (value, emitChanged) {
  39924. var v = value.trim().toLocaleLowerCase();
  39925. if (v.indexOf("top:") === 0) {
  39926. v = v.substr(4).trim();
  39927. return this._setStringValue(v, 0, emitChanged);
  39928. }
  39929. if (v.indexOf("left:") === 0) {
  39930. v = v.substr(5).trim();
  39931. return this._setStringValue(v, 1, emitChanged);
  39932. }
  39933. if (v.indexOf("right:") === 0) {
  39934. v = v.substr(6).trim();
  39935. return this._setStringValue(v, 2, emitChanged);
  39936. }
  39937. if (v.indexOf("bottom:") === 0) {
  39938. v = v.substr(7).trim();
  39939. return this._setStringValue(v, 3, emitChanged);
  39940. }
  39941. return false;
  39942. };
  39943. PrimitiveThickness.prototype._setStringValue = function (value, index, emitChanged) {
  39944. // Check for auto
  39945. var v = value.trim().toLocaleLowerCase();
  39946. if (v === "auto") {
  39947. if (this._isType(index, PrimitiveThickness.Auto)) {
  39948. return true;
  39949. }
  39950. this._setType(index, PrimitiveThickness.Auto);
  39951. this._pixels[index] = 0;
  39952. if (emitChanged) {
  39953. this._changedCallback();
  39954. }
  39955. }
  39956. else if (v === "inherit") {
  39957. if (this._isType(index, PrimitiveThickness.Inherit)) {
  39958. return true;
  39959. }
  39960. this._setType(index, PrimitiveThickness.Inherit);
  39961. this._pixels[index] = null;
  39962. if (emitChanged) {
  39963. this._changedCallback();
  39964. }
  39965. }
  39966. else {
  39967. var pI = v.indexOf("%");
  39968. // Check for percentage
  39969. if (pI !== -1) {
  39970. var n_1 = v.substr(0, pI);
  39971. var number_1 = Math.round(Number(n_1)) / 100; // Normalize the percentage to [0;1] with a 0.01 precision
  39972. if (this._isType(index, PrimitiveThickness.Percentage) && (this._percentages[index] === number_1)) {
  39973. return true;
  39974. }
  39975. this._setType(index, PrimitiveThickness.Percentage);
  39976. if (isNaN(number_1)) {
  39977. return false;
  39978. }
  39979. this._percentages[index] = number_1;
  39980. if (emitChanged) {
  39981. this._changedCallback();
  39982. }
  39983. return true;
  39984. }
  39985. // Check for pixel
  39986. var n;
  39987. pI = v.indexOf("px");
  39988. if (pI !== -1) {
  39989. n = v.substr(0, pI).trim();
  39990. }
  39991. else {
  39992. n = v;
  39993. }
  39994. var number = Number(n);
  39995. if (this._isType(index, PrimitiveThickness.Pixel) && (this._pixels[index] === number)) {
  39996. return true;
  39997. }
  39998. if (isNaN(number)) {
  39999. return false;
  40000. }
  40001. this._pixels[index] = number;
  40002. this._setType(index, PrimitiveThickness.Pixel);
  40003. if (emitChanged) {
  40004. this._changedCallback();
  40005. }
  40006. return true;
  40007. }
  40008. };
  40009. PrimitiveThickness.prototype._setPixels = function (value, index, emitChanged) {
  40010. // 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
  40011. value = Math.round(value);
  40012. if (this._isType(index, PrimitiveThickness.Pixel) && this._pixels[index] === value) {
  40013. return;
  40014. }
  40015. this._setType(index, PrimitiveThickness.Pixel);
  40016. this._pixels[index] = value;
  40017. if (emitChanged) {
  40018. this._changedCallback();
  40019. }
  40020. };
  40021. PrimitiveThickness.prototype._setPercentage = function (value, index, emitChanged) {
  40022. // Clip Value to bounds
  40023. value = Math.min(1, value);
  40024. value = Math.max(0, value);
  40025. value = Math.round(value * 100) / 100; // 0.01 precision
  40026. if (this._isType(index, PrimitiveThickness.Percentage) && this._percentages[index] === value) {
  40027. return;
  40028. }
  40029. this._setType(index, PrimitiveThickness.Percentage);
  40030. this._percentages[index] = value;
  40031. if (emitChanged) {
  40032. this._changedCallback();
  40033. }
  40034. };
  40035. PrimitiveThickness.prototype._getStringValue = function (index) {
  40036. var f = (this._flags >> (index * 4)) & 0xF;
  40037. switch (f) {
  40038. case PrimitiveThickness.Auto:
  40039. return "auto";
  40040. case PrimitiveThickness.Pixel:
  40041. return this._pixels[index] + "px";
  40042. case PrimitiveThickness.Percentage:
  40043. return this._percentages[index] * 100 + "%";
  40044. case PrimitiveThickness.Inherit:
  40045. return "inherit";
  40046. }
  40047. return "";
  40048. };
  40049. PrimitiveThickness.prototype._isType = function (index, type) {
  40050. var f = (this._flags >> (index * 4)) & 0xF;
  40051. return f === type;
  40052. };
  40053. PrimitiveThickness.prototype._getType = function (index, processInherit) {
  40054. var t = (this._flags >> (index * 4)) & 0xF;
  40055. if (processInherit && (t === PrimitiveThickness.Inherit)) {
  40056. var p = this._parentAccess();
  40057. if (p) {
  40058. return p._getType(index, true);
  40059. }
  40060. return PrimitiveThickness.Auto;
  40061. }
  40062. return t;
  40063. };
  40064. PrimitiveThickness.prototype._setType = function (index, type) {
  40065. this._flags &= ~(0xF << (index * 4));
  40066. this._flags |= type << (index * 4);
  40067. };
  40068. PrimitiveThickness.prototype.setTop = function (value) {
  40069. if (typeof value === "string") {
  40070. this._setStringValue(value, 0, true);
  40071. }
  40072. else {
  40073. this.topPixels = value;
  40074. }
  40075. };
  40076. PrimitiveThickness.prototype.setLeft = function (value) {
  40077. if (typeof value === "string") {
  40078. this._setStringValue(value, 1, true);
  40079. }
  40080. else {
  40081. this.leftPixels = value;
  40082. }
  40083. };
  40084. PrimitiveThickness.prototype.setRight = function (value) {
  40085. if (typeof value === "string") {
  40086. this._setStringValue(value, 2, true);
  40087. }
  40088. else {
  40089. this.rightPixels = value;
  40090. }
  40091. };
  40092. PrimitiveThickness.prototype.setBottom = function (value) {
  40093. if (typeof value === "string") {
  40094. this._setStringValue(value, 3, true);
  40095. }
  40096. else {
  40097. this.bottomPixels = value;
  40098. }
  40099. };
  40100. Object.defineProperty(PrimitiveThickness.prototype, "top", {
  40101. /**
  40102. * Get/set the top thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  40103. */
  40104. get: function () {
  40105. return this._getStringValue(0);
  40106. },
  40107. set: function (value) {
  40108. this._setStringValue(value, 0, true);
  40109. },
  40110. enumerable: true,
  40111. configurable: true
  40112. });
  40113. Object.defineProperty(PrimitiveThickness.prototype, "left", {
  40114. /**
  40115. * Get/set the left thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  40116. */
  40117. get: function () {
  40118. return this._getStringValue(1);
  40119. },
  40120. set: function (value) {
  40121. this._setStringValue(value, 1, true);
  40122. },
  40123. enumerable: true,
  40124. configurable: true
  40125. });
  40126. Object.defineProperty(PrimitiveThickness.prototype, "right", {
  40127. /**
  40128. * Get/set the right thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  40129. */
  40130. get: function () {
  40131. return this._getStringValue(2);
  40132. },
  40133. set: function (value) {
  40134. this._setStringValue(value, 2, true);
  40135. },
  40136. enumerable: true,
  40137. configurable: true
  40138. });
  40139. Object.defineProperty(PrimitiveThickness.prototype, "bottom", {
  40140. /**
  40141. * Get/set the bottom thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  40142. */
  40143. get: function () {
  40144. return this._getStringValue(3);
  40145. },
  40146. set: function (value) {
  40147. this._setStringValue(value, 3, true);
  40148. },
  40149. enumerable: true,
  40150. configurable: true
  40151. });
  40152. Object.defineProperty(PrimitiveThickness.prototype, "topPixels", {
  40153. /**
  40154. * Get/set the top thickness in pixel.
  40155. */
  40156. get: function () {
  40157. return this._pixels[0];
  40158. },
  40159. set: function (value) {
  40160. this._setPixels(value, 0, true);
  40161. },
  40162. enumerable: true,
  40163. configurable: true
  40164. });
  40165. Object.defineProperty(PrimitiveThickness.prototype, "leftPixels", {
  40166. /**
  40167. * Get/set the left thickness in pixel.
  40168. */
  40169. get: function () {
  40170. return this._pixels[1];
  40171. },
  40172. set: function (value) {
  40173. this._setPixels(value, 1, true);
  40174. },
  40175. enumerable: true,
  40176. configurable: true
  40177. });
  40178. Object.defineProperty(PrimitiveThickness.prototype, "rightPixels", {
  40179. /**
  40180. * Get/set the right thickness in pixel.
  40181. */
  40182. get: function () {
  40183. return this._pixels[2];
  40184. },
  40185. set: function (value) {
  40186. this._setPixels(value, 2, true);
  40187. },
  40188. enumerable: true,
  40189. configurable: true
  40190. });
  40191. Object.defineProperty(PrimitiveThickness.prototype, "bottomPixels", {
  40192. /**
  40193. * Get/set the bottom thickness in pixel.
  40194. */
  40195. get: function () {
  40196. return this._pixels[3];
  40197. },
  40198. set: function (value) {
  40199. this._setPixels(value, 3, true);
  40200. },
  40201. enumerable: true,
  40202. configurable: true
  40203. });
  40204. Object.defineProperty(PrimitiveThickness.prototype, "topPercentage", {
  40205. /**
  40206. * Get/set the top thickness in percentage.
  40207. * The get will return a valid value only if the edge type is percentage.
  40208. * The Set will change the edge mode if needed
  40209. */
  40210. get: function () {
  40211. return this._percentages[0];
  40212. },
  40213. set: function (value) {
  40214. this._setPercentage(value, 0, true);
  40215. },
  40216. enumerable: true,
  40217. configurable: true
  40218. });
  40219. Object.defineProperty(PrimitiveThickness.prototype, "leftPercentage", {
  40220. /**
  40221. * Get/set the left thickness in percentage.
  40222. * The get will return a valid value only if the edge mode is percentage.
  40223. * The Set will change the edge mode if needed
  40224. */
  40225. get: function () {
  40226. return this._percentages[1];
  40227. },
  40228. set: function (value) {
  40229. this._setPercentage(value, 1, true);
  40230. },
  40231. enumerable: true,
  40232. configurable: true
  40233. });
  40234. Object.defineProperty(PrimitiveThickness.prototype, "rightPercentage", {
  40235. /**
  40236. * Get/set the right thickness in percentage.
  40237. * The get will return a valid value only if the edge mode is percentage.
  40238. * The Set will change the edge mode if needed
  40239. */
  40240. get: function () {
  40241. return this._percentages[2];
  40242. },
  40243. set: function (value) {
  40244. this._setPercentage(value, 2, true);
  40245. },
  40246. enumerable: true,
  40247. configurable: true
  40248. });
  40249. Object.defineProperty(PrimitiveThickness.prototype, "bottomPercentage", {
  40250. /**
  40251. * Get/set the bottom thickness in percentage.
  40252. * The get will return a valid value only if the edge mode is percentage.
  40253. * The Set will change the edge mode if needed
  40254. */
  40255. get: function () {
  40256. return this._percentages[3];
  40257. },
  40258. set: function (value) {
  40259. this._setPercentage(value, 3, true);
  40260. },
  40261. enumerable: true,
  40262. configurable: true
  40263. });
  40264. Object.defineProperty(PrimitiveThickness.prototype, "topMode", {
  40265. /**
  40266. * Get/set the top mode. The setter shouldn't be used, other setters with value should be preferred
  40267. */
  40268. get: function () {
  40269. return this._getType(0, false);
  40270. },
  40271. set: function (mode) {
  40272. this._setType(0, mode);
  40273. },
  40274. enumerable: true,
  40275. configurable: true
  40276. });
  40277. Object.defineProperty(PrimitiveThickness.prototype, "leftMode", {
  40278. /**
  40279. * Get/set the left mode. The setter shouldn't be used, other setters with value should be preferred
  40280. */
  40281. get: function () {
  40282. return this._getType(1, false);
  40283. },
  40284. set: function (mode) {
  40285. this._setType(1, mode);
  40286. },
  40287. enumerable: true,
  40288. configurable: true
  40289. });
  40290. Object.defineProperty(PrimitiveThickness.prototype, "rightMode", {
  40291. /**
  40292. * Get/set the right mode. The setter shouldn't be used, other setters with value should be preferred
  40293. */
  40294. get: function () {
  40295. return this._getType(2, false);
  40296. },
  40297. set: function (mode) {
  40298. this._setType(2, mode);
  40299. },
  40300. enumerable: true,
  40301. configurable: true
  40302. });
  40303. Object.defineProperty(PrimitiveThickness.prototype, "bottomMode", {
  40304. /**
  40305. * Get/set the bottom mode. The setter shouldn't be used, other setters with value should be preferred
  40306. */
  40307. get: function () {
  40308. return this._getType(3, false);
  40309. },
  40310. set: function (mode) {
  40311. this._setType(3, mode);
  40312. },
  40313. enumerable: true,
  40314. configurable: true
  40315. });
  40316. PrimitiveThickness.prototype._computePixels = function (index, sourceArea, emitChanged) {
  40317. var type = this._getType(index, false);
  40318. if (type === PrimitiveThickness.Inherit) {
  40319. this._parentAccess()._computePixels(index, sourceArea, emitChanged);
  40320. return;
  40321. }
  40322. if (type !== PrimitiveThickness.Percentage) {
  40323. return;
  40324. }
  40325. var pixels = ((index === 0 || index === 3) ? sourceArea.height : sourceArea.width) * this._percentages[index];
  40326. this._pixels[index] = pixels;
  40327. if (emitChanged) {
  40328. this._changedCallback();
  40329. }
  40330. };
  40331. /**
  40332. * Compute the positioning/size of an area considering the thickness of this object and a given alignment
  40333. * @param sourceArea the source area where the content must be sized/positioned
  40334. * @param contentSize the content size to position/resize
  40335. * @param alignment the alignment setting
  40336. * @param dstOffset the position of the content
  40337. * @param dstArea the new size of the content
  40338. */
  40339. PrimitiveThickness.prototype.computeWithAlignment = function (sourceArea, contentSize, alignment, dstOffset, dstArea, computeLayoutArea) {
  40340. if (computeLayoutArea === void 0) { computeLayoutArea = false; }
  40341. // Fetch some data
  40342. var topType = this._getType(0, true);
  40343. var leftType = this._getType(1, true);
  40344. var rightType = this._getType(2, true);
  40345. var bottomType = this._getType(3, true);
  40346. var hasWidth = contentSize && (contentSize.width != null);
  40347. var hasHeight = contentSize && (contentSize.height != null);
  40348. var width = hasWidth ? contentSize.width : 0;
  40349. var height = hasHeight ? contentSize.height : 0;
  40350. var isTopAuto = topType === PrimitiveThickness.Auto;
  40351. var isLeftAuto = leftType === PrimitiveThickness.Auto;
  40352. var isRightAuto = rightType === PrimitiveThickness.Auto;
  40353. var isBottomAuto = bottomType === PrimitiveThickness.Auto;
  40354. switch (alignment.horizontal) {
  40355. case PrimitiveAlignment.AlignLeft:
  40356. {
  40357. if (isLeftAuto) {
  40358. dstOffset.x = 0;
  40359. }
  40360. else {
  40361. this._computePixels(1, sourceArea, true);
  40362. dstOffset.x = this.leftPixels;
  40363. }
  40364. dstArea.width = width;
  40365. if (computeLayoutArea) {
  40366. dstArea.width += this.leftPixels;
  40367. }
  40368. break;
  40369. }
  40370. case PrimitiveAlignment.AlignRight:
  40371. {
  40372. if (isRightAuto) {
  40373. dstOffset.x = Math.round(sourceArea.width - width);
  40374. }
  40375. else {
  40376. this._computePixels(2, sourceArea, true);
  40377. dstOffset.x = Math.round(sourceArea.width - (width + this.rightPixels));
  40378. }
  40379. dstArea.width = width;
  40380. if (computeLayoutArea) {
  40381. dstArea.width += this.rightPixels;
  40382. }
  40383. break;
  40384. }
  40385. case PrimitiveAlignment.AlignStretch:
  40386. {
  40387. if (isLeftAuto) {
  40388. dstOffset.x = 0;
  40389. }
  40390. else {
  40391. this._computePixels(1, sourceArea, true);
  40392. dstOffset.x = this.leftPixels;
  40393. }
  40394. var right = 0;
  40395. if (!isRightAuto) {
  40396. this._computePixels(2, sourceArea, true);
  40397. right = this.rightPixels;
  40398. }
  40399. dstArea.width = sourceArea.width - (dstOffset.x + right);
  40400. break;
  40401. }
  40402. case PrimitiveAlignment.AlignCenter:
  40403. {
  40404. if (!isLeftAuto) {
  40405. this._computePixels(1, sourceArea, true);
  40406. }
  40407. if (!isRightAuto) {
  40408. this._computePixels(2, sourceArea, true);
  40409. }
  40410. var offset = (isLeftAuto ? 0 : this.leftPixels) - (isRightAuto ? 0 : this.rightPixels);
  40411. dstOffset.x = Math.round(((sourceArea.width - width) / 2) + offset);
  40412. dstArea.width = width;
  40413. break;
  40414. }
  40415. }
  40416. switch (alignment.vertical) {
  40417. case PrimitiveAlignment.AlignTop:
  40418. {
  40419. if (isTopAuto) {
  40420. dstOffset.y = sourceArea.height - height;
  40421. }
  40422. else {
  40423. this._computePixels(0, sourceArea, true);
  40424. dstOffset.y = Math.round(sourceArea.height - (height + this.topPixels));
  40425. }
  40426. dstArea.height = height;
  40427. if (computeLayoutArea) {
  40428. dstArea.height += this.topPixels;
  40429. }
  40430. break;
  40431. }
  40432. case PrimitiveAlignment.AlignBottom:
  40433. {
  40434. if (isBottomAuto) {
  40435. dstOffset.y = 0;
  40436. }
  40437. else {
  40438. this._computePixels(3, sourceArea, true);
  40439. dstOffset.y = this.bottomPixels;
  40440. }
  40441. dstArea.height = height;
  40442. if (computeLayoutArea) {
  40443. dstArea.height += this.bottomPixels;
  40444. }
  40445. break;
  40446. }
  40447. case PrimitiveAlignment.AlignStretch:
  40448. {
  40449. if (isBottomAuto) {
  40450. dstOffset.y = 0;
  40451. }
  40452. else {
  40453. this._computePixels(3, sourceArea, true);
  40454. dstOffset.y = this.bottomPixels;
  40455. }
  40456. var top_1 = 0;
  40457. if (!isTopAuto) {
  40458. this._computePixels(0, sourceArea, true);
  40459. top_1 = this.topPixels;
  40460. }
  40461. dstArea.height = sourceArea.height - (dstOffset.y + top_1);
  40462. break;
  40463. }
  40464. case PrimitiveAlignment.AlignCenter:
  40465. {
  40466. if (!isTopAuto) {
  40467. this._computePixels(0, sourceArea, true);
  40468. }
  40469. if (!isBottomAuto) {
  40470. this._computePixels(3, sourceArea, true);
  40471. }
  40472. var offset = (isBottomAuto ? 0 : this.bottomPixels) - (isTopAuto ? 0 : this.topPixels);
  40473. dstOffset.y = Math.round(((sourceArea.height - height) / 2) + offset);
  40474. dstArea.height = height;
  40475. break;
  40476. }
  40477. }
  40478. };
  40479. /**
  40480. * Compute an area and its position considering this thickness properties based on a given source area
  40481. * @param sourceArea the source area
  40482. * @param dstOffset the position of the resulting area
  40483. * @param dstArea the size of the resulting area
  40484. */
  40485. PrimitiveThickness.prototype.compute = function (sourceArea, dstOffset, dstArea) {
  40486. this._computePixels(0, sourceArea, true);
  40487. this._computePixels(1, sourceArea, true);
  40488. this._computePixels(2, sourceArea, true);
  40489. this._computePixels(3, sourceArea, true);
  40490. dstOffset.x = this.leftPixels;
  40491. dstArea.width = sourceArea.width - (dstOffset.x + this.rightPixels);
  40492. dstOffset.y = this.bottomPixels;
  40493. dstArea.height = sourceArea.height - (dstOffset.y + this.topPixels);
  40494. };
  40495. /**
  40496. * Compute an area considering this thickness properties based on a given source area
  40497. * @param sourceArea the source area
  40498. * @param result the resulting area
  40499. */
  40500. PrimitiveThickness.prototype.computeArea = function (sourceArea, result) {
  40501. this._computePixels(0, sourceArea, true);
  40502. this._computePixels(1, sourceArea, true);
  40503. this._computePixels(2, sourceArea, true);
  40504. this._computePixels(3, sourceArea, true);
  40505. result.width = this.leftPixels + sourceArea.width + this.rightPixels;
  40506. result.height = this.bottomPixels + sourceArea.height + this.topPixels;
  40507. };
  40508. PrimitiveThickness.prototype.enlarge = function (sourceArea, dstOffset, enlargedArea) {
  40509. this._computePixels(0, sourceArea, true);
  40510. this._computePixels(1, sourceArea, true);
  40511. this._computePixels(2, sourceArea, true);
  40512. this._computePixels(3, sourceArea, true);
  40513. dstOffset.x = this.leftPixels;
  40514. enlargedArea.width = sourceArea.width + (dstOffset.x + this.rightPixels);
  40515. dstOffset.y = this.bottomPixels;
  40516. enlargedArea.height = sourceArea.height + (dstOffset.y + this.topPixels);
  40517. };
  40518. PrimitiveThickness.Auto = 0x1;
  40519. PrimitiveThickness.Inherit = 0x2;
  40520. PrimitiveThickness.Percentage = 0x4;
  40521. PrimitiveThickness.Pixel = 0x8;
  40522. return PrimitiveThickness;
  40523. })();
  40524. BABYLON.PrimitiveThickness = PrimitiveThickness;
  40525. /**
  40526. * Main class used for the Primitive Intersection API
  40527. */
  40528. var IntersectInfo2D = (function () {
  40529. function IntersectInfo2D() {
  40530. this.findFirstOnly = false;
  40531. this.intersectHidden = false;
  40532. this.pickPosition = BABYLON.Vector2.Zero();
  40533. }
  40534. Object.defineProperty(IntersectInfo2D.prototype, "isIntersected", {
  40535. /**
  40536. * true if at least one primitive intersected during the test
  40537. */
  40538. get: function () {
  40539. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  40540. },
  40541. enumerable: true,
  40542. configurable: true
  40543. });
  40544. IntersectInfo2D.prototype.isPrimIntersected = function (prim) {
  40545. for (var _i = 0, _a = this.intersectedPrimitives; _i < _a.length; _i++) {
  40546. var cur = _a[_i];
  40547. if (cur.prim === prim) {
  40548. return cur.intersectionLocation;
  40549. }
  40550. }
  40551. return null;
  40552. };
  40553. // Internals, don't use
  40554. IntersectInfo2D.prototype._exit = function (firstLevel) {
  40555. if (firstLevel) {
  40556. this._globalPickPosition = null;
  40557. }
  40558. };
  40559. return IntersectInfo2D;
  40560. })();
  40561. BABYLON.IntersectInfo2D = IntersectInfo2D;
  40562. var Prim2DBase = (function (_super) {
  40563. __extends(Prim2DBase, _super);
  40564. function Prim2DBase(settings) {
  40565. // Avoid checking every time if the object exists
  40566. if (settings == null) {
  40567. settings = {};
  40568. }
  40569. // BASE CLASS CALL
  40570. _super.call(this);
  40571. // Fetch the owner, parent. There're many ways to do it and we can end up with nothing for both
  40572. var owner;
  40573. var parent;
  40574. if (Prim2DBase._isCanvasInit) {
  40575. owner = this;
  40576. parent = null;
  40577. this._canvasPreInit(settings);
  40578. }
  40579. else {
  40580. if (settings.parent != null) {
  40581. parent = settings.parent;
  40582. owner = settings.parent.owner;
  40583. if (!owner) {
  40584. throw new Error("Parent " + parent.id + " of " + settings.id + " doesn't have a valid owner!");
  40585. }
  40586. 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)) {
  40587. 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");
  40588. }
  40589. }
  40590. }
  40591. // Fields initialization
  40592. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  40593. this._size = null; //Size.Zero();
  40594. this._scale = new BABYLON.Vector2(1, 1);
  40595. this._actualSize = null;
  40596. this._boundingSize = BABYLON.Size.Zero();
  40597. this._layoutArea = BABYLON.Size.Zero();
  40598. this._layoutAreaPos = null;
  40599. this._layoutBoundingInfo = null;
  40600. this._marginOffset = BABYLON.Vector2.Zero();
  40601. this._paddingOffset = BABYLON.Vector2.Zero();
  40602. this._parentPaddingOffset = BABYLON.Vector2.Zero();
  40603. this._parentContentArea = BABYLON.Size.Zero();
  40604. this._lastAutoSizeArea = BABYLON.Size.Zero();
  40605. this._contentArea = new BABYLON.Size(null, null);
  40606. this._pointerEventObservable = new BABYLON.Observable();
  40607. this._boundingInfo = new BABYLON.BoundingInfo2D();
  40608. this._owner = owner;
  40609. this._parent = null;
  40610. this._margin = null;
  40611. this._padding = null;
  40612. this._marginAlignment = null;
  40613. this._id = settings.id;
  40614. this.propertyChanged = new BABYLON.Observable();
  40615. this._children = new Array();
  40616. this._localTransform = new BABYLON.Matrix();
  40617. this._globalTransform = null;
  40618. this._invGlobalTransform = null;
  40619. this._globalTransformProcessStep = 0;
  40620. this._globalTransformStep = 0;
  40621. this._renderGroup = null;
  40622. this._primLinearPosition = 0;
  40623. this._manualZOrder = null;
  40624. this._zOrder = 0;
  40625. this._zMax = 0;
  40626. this._firstZDirtyIndex = Prim2DBase._bigInt;
  40627. this._actualOpacity = 0;
  40628. this._actualScale = BABYLON.Vector2.Zero();
  40629. var isPickable = true;
  40630. var isContainer = true;
  40631. if (settings.isPickable !== undefined) {
  40632. isPickable = settings.isPickable;
  40633. }
  40634. if (settings.isContainer !== undefined) {
  40635. isContainer = settings.isContainer;
  40636. }
  40637. if (settings.dontInheritParentScale) {
  40638. this._setFlags(BABYLON.SmartPropertyPrim.flagDontInheritParentScale);
  40639. }
  40640. this._setFlags((isPickable ? BABYLON.SmartPropertyPrim.flagIsPickable : 0) | BABYLON.SmartPropertyPrim.flagBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagActualOpacityDirty | (isContainer ? BABYLON.SmartPropertyPrim.flagIsContainer : 0) | BABYLON.SmartPropertyPrim.flagActualScaleDirty | BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  40641. if (settings.opacity != null) {
  40642. this._opacity = settings.opacity;
  40643. }
  40644. else {
  40645. this._opacity = 1;
  40646. }
  40647. this._updateRenderMode();
  40648. if (settings.childrenFlatZOrder) {
  40649. this._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  40650. }
  40651. // If the parent is given, initialize the hierarchy/owner related data
  40652. if (parent != null) {
  40653. parent.addChild(this);
  40654. this._hierarchyDepth = parent._hierarchyDepth + 1;
  40655. this._patchHierarchy(parent.owner);
  40656. }
  40657. // If it's a group, detect its own states
  40658. if (this.owner && this instanceof BABYLON.Group2D) {
  40659. var group = this;
  40660. group.detectGroupStates();
  40661. }
  40662. // Time to insert children if some are specified
  40663. if (settings.children != null) {
  40664. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  40665. var child = _a[_i];
  40666. this.addChild(child);
  40667. // Good time to patch the hierarchy, it won't go very far if there's no need to
  40668. if (this.owner != null) {
  40669. child._patchHierarchy(this.owner);
  40670. }
  40671. }
  40672. }
  40673. if (settings.zOrder != null) {
  40674. this.zOrder = settings.zOrder;
  40675. }
  40676. // Set the model related properties
  40677. if (settings.position != null) {
  40678. this.position = settings.position;
  40679. }
  40680. else if (settings.x != null || settings.y != null) {
  40681. this.position = new BABYLON.Vector2(settings.x || 0, settings.y || 0);
  40682. }
  40683. else {
  40684. this._position = null;
  40685. }
  40686. this.rotation = (settings.rotation == null) ? 0 : settings.rotation;
  40687. if (settings.scale != null) {
  40688. this.scale = settings.scale;
  40689. }
  40690. else {
  40691. if (settings.scaleX != null) {
  40692. this.scaleX = settings.scaleX;
  40693. }
  40694. if (settings.scaleY != null) {
  40695. this.scaleY = settings.scaleY;
  40696. }
  40697. }
  40698. this.levelVisible = (settings.isVisible == null) ? true : settings.isVisible;
  40699. this.origin = settings.origin || new BABYLON.Vector2(0.5, 0.5);
  40700. // Layout Engine
  40701. if (settings.layoutEngine != null) {
  40702. if (typeof settings.layoutEngine === "string") {
  40703. var name_1 = settings.layoutEngine.toLocaleLowerCase().trim();
  40704. if (name_1 === "canvas" || name_1 === "canvaslayoutengine") {
  40705. this.layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  40706. }
  40707. else if (name_1.indexOf("stackpanel") === 0 || name_1.indexOf("horizontalstackpanel") === 0) {
  40708. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Horizontal;
  40709. }
  40710. else if (name_1.indexOf("verticalstackpanel") === 0) {
  40711. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Vertical;
  40712. }
  40713. }
  40714. else if (settings.layoutEngine instanceof BABYLON.LayoutEngineBase) {
  40715. this.layoutEngine = settings.layoutEngine;
  40716. }
  40717. }
  40718. // Set the layout/margin stuffs
  40719. if (settings.marginTop) {
  40720. this.margin.setTop(settings.marginTop);
  40721. }
  40722. if (settings.marginLeft) {
  40723. this.margin.setLeft(settings.marginLeft);
  40724. }
  40725. if (settings.marginRight) {
  40726. this.margin.setRight(settings.marginRight);
  40727. }
  40728. if (settings.marginBottom) {
  40729. this.margin.setBottom(settings.marginBottom);
  40730. }
  40731. if (settings.margin) {
  40732. if (typeof settings.margin === "string") {
  40733. this.margin.fromString(settings.margin);
  40734. }
  40735. else {
  40736. this.margin.fromUniformPixels(settings.margin);
  40737. }
  40738. }
  40739. if (settings.marginHAlignment) {
  40740. this.marginAlignment.horizontal = settings.marginHAlignment;
  40741. }
  40742. if (settings.marginVAlignment) {
  40743. this.marginAlignment.vertical = settings.marginVAlignment;
  40744. }
  40745. if (settings.marginAlignment) {
  40746. this.marginAlignment.fromString(settings.marginAlignment);
  40747. }
  40748. if (settings.paddingTop) {
  40749. this.padding.setTop(settings.paddingTop);
  40750. }
  40751. if (settings.paddingLeft) {
  40752. this.padding.setLeft(settings.paddingLeft);
  40753. }
  40754. if (settings.paddingRight) {
  40755. this.padding.setRight(settings.paddingRight);
  40756. }
  40757. if (settings.paddingBottom) {
  40758. this.padding.setBottom(settings.paddingBottom);
  40759. }
  40760. if (settings.padding) {
  40761. this.padding.fromString(settings.padding);
  40762. }
  40763. // Dirty layout and positioning
  40764. this._parentLayoutDirty();
  40765. this._positioningDirty();
  40766. }
  40767. Object.defineProperty(Prim2DBase.prototype, "actionManager", {
  40768. get: function () {
  40769. if (!this._actionManager) {
  40770. this._actionManager = new BABYLON.ActionManager(this.owner.scene);
  40771. }
  40772. return this._actionManager;
  40773. },
  40774. enumerable: true,
  40775. configurable: true
  40776. });
  40777. /**
  40778. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  40779. * @param predicate the predicate to test on each parent
  40780. * @return the first primitive where the predicate was successful
  40781. */
  40782. Prim2DBase.prototype.traverseUp = function (predicate) {
  40783. var p = this;
  40784. while (p != null) {
  40785. if (predicate(p)) {
  40786. return p;
  40787. }
  40788. p = p._parent;
  40789. }
  40790. return null;
  40791. };
  40792. Object.defineProperty(Prim2DBase.prototype, "owner", {
  40793. /**
  40794. * Retrieve the owner Canvas2D
  40795. */
  40796. get: function () {
  40797. return this._owner;
  40798. },
  40799. enumerable: true,
  40800. configurable: true
  40801. });
  40802. Object.defineProperty(Prim2DBase.prototype, "parent", {
  40803. /**
  40804. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  40805. */
  40806. get: function () {
  40807. return this._parent;
  40808. },
  40809. enumerable: true,
  40810. configurable: true
  40811. });
  40812. Object.defineProperty(Prim2DBase.prototype, "children", {
  40813. /**
  40814. * The array of direct children primitives
  40815. */
  40816. get: function () {
  40817. return this._children;
  40818. },
  40819. enumerable: true,
  40820. configurable: true
  40821. });
  40822. Object.defineProperty(Prim2DBase.prototype, "id", {
  40823. /**
  40824. * The identifier of this primitive, may not be unique, it's for information purpose only
  40825. */
  40826. get: function () {
  40827. return this._id;
  40828. },
  40829. enumerable: true,
  40830. configurable: true
  40831. });
  40832. Object.defineProperty(Prim2DBase.prototype, "actualPosition", {
  40833. get: function () {
  40834. if (this._actualPosition != null) {
  40835. return this._actualPosition;
  40836. }
  40837. if (this._position != null) {
  40838. return this._position;
  40839. }
  40840. // At least return 0,0, we can't return null on actualPosition
  40841. return Prim2DBase._nullPosition;
  40842. },
  40843. /**
  40844. * DO NOT INVOKE for internal purpose only
  40845. */
  40846. set: function (val) {
  40847. this._actualPosition = val;
  40848. },
  40849. enumerable: true,
  40850. configurable: true
  40851. });
  40852. Object.defineProperty(Prim2DBase.prototype, "actualX", {
  40853. /**
  40854. * Shortcut to actualPosition.x
  40855. */
  40856. get: function () {
  40857. return this.actualPosition.x;
  40858. },
  40859. enumerable: true,
  40860. configurable: true
  40861. });
  40862. Object.defineProperty(Prim2DBase.prototype, "actualY", {
  40863. /**
  40864. * Shortcut to actualPosition.y
  40865. */
  40866. get: function () {
  40867. return this.actualPosition.y;
  40868. },
  40869. enumerable: true,
  40870. configurable: true
  40871. });
  40872. Object.defineProperty(Prim2DBase.prototype, "position", {
  40873. /**
  40874. * Position of the primitive, relative to its parent.
  40875. * BEWARE: if you change only position.x or y it won't trigger a property change and you won't have the expected behavior.
  40876. * Use this property to set a new Vector2 object, otherwise to change only the x/y use Prim2DBase.x or y properties.
  40877. * Setting this property may have no effect is specific alignment are in effect.
  40878. */
  40879. get: function () {
  40880. return this._position || Prim2DBase._nullPosition;
  40881. },
  40882. set: function (value) {
  40883. if (!this._checkPositionChange()) {
  40884. return;
  40885. }
  40886. this._position = value;
  40887. this._triggerPropertyChanged(Prim2DBase.actualPositionProperty, value);
  40888. },
  40889. enumerable: true,
  40890. configurable: true
  40891. });
  40892. Object.defineProperty(Prim2DBase.prototype, "x", {
  40893. /**
  40894. * Direct access to the position.x value of the primitive
  40895. * Use this property when you only want to change one component of the position property
  40896. */
  40897. get: function () {
  40898. if (!this._position) {
  40899. return null;
  40900. }
  40901. return this._position.x;
  40902. },
  40903. set: function (value) {
  40904. if (!this._checkPositionChange()) {
  40905. return;
  40906. }
  40907. if (!this._position) {
  40908. this._position = BABYLON.Vector2.Zero();
  40909. }
  40910. if (this._position.x === value) {
  40911. return;
  40912. }
  40913. this._position.x = value;
  40914. this._triggerPropertyChanged(Prim2DBase.positionProperty, value);
  40915. this._triggerPropertyChanged(Prim2DBase.actualPositionProperty, value);
  40916. },
  40917. enumerable: true,
  40918. configurable: true
  40919. });
  40920. Object.defineProperty(Prim2DBase.prototype, "y", {
  40921. /**
  40922. * Direct access to the position.y value of the primitive
  40923. * Use this property when you only want to change one component of the position property
  40924. */
  40925. get: function () {
  40926. if (!this._position) {
  40927. return null;
  40928. }
  40929. return this._position.y;
  40930. },
  40931. set: function (value) {
  40932. if (!this._checkPositionChange()) {
  40933. return;
  40934. }
  40935. if (!this._position) {
  40936. this._position = BABYLON.Vector2.Zero();
  40937. }
  40938. if (this._position.y === value) {
  40939. return;
  40940. }
  40941. this._position.y = value;
  40942. this._triggerPropertyChanged(Prim2DBase.positionProperty, value);
  40943. this._triggerPropertyChanged(Prim2DBase.actualPositionProperty, value);
  40944. },
  40945. enumerable: true,
  40946. configurable: true
  40947. });
  40948. Object.defineProperty(Prim2DBase.prototype, "size", {
  40949. /**
  40950. * Size of the primitive or its bounding area
  40951. * BEWARE: if you change only size.width or height it won't trigger a property change and you won't have the expected behavior.
  40952. * Use this property to set a new Size object, otherwise to change only the width/height use Prim2DBase.width or height properties.
  40953. */
  40954. get: function () {
  40955. if (!this._size || this._size.width == null || this._size.height == null) {
  40956. if (Prim2DBase.boundinbBoxReentrency) {
  40957. return Prim2DBase.nullSize;
  40958. }
  40959. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  40960. return this._boundingSize;
  40961. }
  40962. Prim2DBase.boundinbBoxReentrency = true;
  40963. var b = this.boundingInfo;
  40964. Prim2DBase.boundinbBoxReentrency = false;
  40965. return this._boundingSize;
  40966. }
  40967. return this._size;
  40968. },
  40969. set: function (value) {
  40970. this._size = value;
  40971. },
  40972. enumerable: true,
  40973. configurable: true
  40974. });
  40975. Object.defineProperty(Prim2DBase.prototype, "width", {
  40976. /**
  40977. * Direct access to the size.width value of the primitive
  40978. * Use this property when you only want to change one component of the size property
  40979. */
  40980. get: function () {
  40981. if (!this.size) {
  40982. return null;
  40983. }
  40984. return this.size.width;
  40985. },
  40986. set: function (value) {
  40987. if (!this.size) {
  40988. this.size = new BABYLON.Size(value, 0);
  40989. return;
  40990. }
  40991. if (this.size.width === value) {
  40992. return;
  40993. }
  40994. this.size.width = value;
  40995. this._triggerPropertyChanged(Prim2DBase.sizeProperty, value);
  40996. this._positioningDirty();
  40997. },
  40998. enumerable: true,
  40999. configurable: true
  41000. });
  41001. Object.defineProperty(Prim2DBase.prototype, "height", {
  41002. /**
  41003. * Direct access to the size.height value of the primitive
  41004. * Use this property when you only want to change one component of the size property
  41005. */
  41006. get: function () {
  41007. if (!this.size) {
  41008. return null;
  41009. }
  41010. return this.size.height;
  41011. },
  41012. set: function (value) {
  41013. if (!this.size) {
  41014. this.size = new BABYLON.Size(0, value);
  41015. return;
  41016. }
  41017. if (this.size.height === value) {
  41018. return;
  41019. }
  41020. this.size.height = value;
  41021. this._triggerPropertyChanged(Prim2DBase.sizeProperty, value);
  41022. this._positioningDirty();
  41023. },
  41024. enumerable: true,
  41025. configurable: true
  41026. });
  41027. Object.defineProperty(Prim2DBase.prototype, "rotation", {
  41028. get: function () {
  41029. return this._rotation;
  41030. },
  41031. set: function (value) {
  41032. this._rotation = value;
  41033. },
  41034. enumerable: true,
  41035. configurable: true
  41036. });
  41037. Object.defineProperty(Prim2DBase.prototype, "scale", {
  41038. get: function () {
  41039. return this._scale.x;
  41040. },
  41041. set: function (value) {
  41042. this._scale.x = this._scale.y = value;
  41043. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  41044. this._spreadActualScaleDirty();
  41045. },
  41046. enumerable: true,
  41047. configurable: true
  41048. });
  41049. Object.defineProperty(Prim2DBase.prototype, "actualSize", {
  41050. /**
  41051. * Return the size of the primitive as it's being rendered into the target.
  41052. * 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.
  41053. * BEWARE: don't use the setter, it's for internal purpose only
  41054. * Note to implementers: you have to override this property and declare if necessary a @xxxxInstanceLevel decorator
  41055. */
  41056. get: function () {
  41057. if (this._actualSize) {
  41058. return this._actualSize;
  41059. }
  41060. return this._size;
  41061. },
  41062. set: function (value) {
  41063. if (this._actualSize.equals(value)) {
  41064. return;
  41065. }
  41066. this._actualSize = value;
  41067. },
  41068. enumerable: true,
  41069. configurable: true
  41070. });
  41071. Object.defineProperty(Prim2DBase.prototype, "actualZOffset", {
  41072. get: function () {
  41073. if (this._manualZOrder != null) {
  41074. return this._manualZOrder;
  41075. }
  41076. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  41077. this._updateZOrder();
  41078. }
  41079. return (1 - this._zOrder);
  41080. },
  41081. enumerable: true,
  41082. configurable: true
  41083. });
  41084. Object.defineProperty(Prim2DBase.prototype, "minSize", {
  41085. /**
  41086. * Get or set the minimal size the Layout Engine should respect when computing the primitive's actualSize.
  41087. * The Primitive's size won't be less than specified.
  41088. * The default value depends of the Primitive type
  41089. */
  41090. get: function () {
  41091. return this._minSize;
  41092. },
  41093. set: function (value) {
  41094. if (this._minSize && value && this._minSize.equals(value)) {
  41095. return;
  41096. }
  41097. this._minSize = value;
  41098. this._parentLayoutDirty();
  41099. },
  41100. enumerable: true,
  41101. configurable: true
  41102. });
  41103. Object.defineProperty(Prim2DBase.prototype, "maxSize", {
  41104. /**
  41105. * Get or set the maximal size the Layout Engine should respect when computing the primitive's actualSize.
  41106. * The Primitive's size won't be more than specified.
  41107. * The default value depends of the Primitive type
  41108. */
  41109. get: function () {
  41110. return this._maxSize;
  41111. },
  41112. set: function (value) {
  41113. if (this._maxSize && value && this._maxSize.equals(value)) {
  41114. return;
  41115. }
  41116. this._maxSize = value;
  41117. this._parentLayoutDirty();
  41118. },
  41119. enumerable: true,
  41120. configurable: true
  41121. });
  41122. Object.defineProperty(Prim2DBase.prototype, "origin", {
  41123. /**
  41124. * The origin defines the normalized coordinate of the center of the primitive, from the bottom/left corner.
  41125. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  41126. * For instance:
  41127. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  41128. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  41129. * 0,1 means the center is top/left
  41130. * @returns The normalized center.
  41131. */
  41132. get: function () {
  41133. return this._origin;
  41134. },
  41135. set: function (value) {
  41136. this._origin = value;
  41137. },
  41138. enumerable: true,
  41139. configurable: true
  41140. });
  41141. Object.defineProperty(Prim2DBase.prototype, "levelVisible", {
  41142. get: function () {
  41143. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelVisible);
  41144. },
  41145. set: function (value) {
  41146. this._changeFlags(BABYLON.SmartPropertyPrim.flagLevelVisible, value);
  41147. },
  41148. enumerable: true,
  41149. configurable: true
  41150. });
  41151. Object.defineProperty(Prim2DBase.prototype, "isVisible", {
  41152. get: function () {
  41153. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsVisible);
  41154. },
  41155. set: function (value) {
  41156. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsVisible, value);
  41157. },
  41158. enumerable: true,
  41159. configurable: true
  41160. });
  41161. Object.defineProperty(Prim2DBase.prototype, "zOrder", {
  41162. get: function () {
  41163. return this._manualZOrder;
  41164. },
  41165. set: function (value) {
  41166. if (this._manualZOrder === value) {
  41167. return;
  41168. }
  41169. this._manualZOrder = value;
  41170. this.onZOrderChanged();
  41171. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  41172. this._actualZOrderChangedObservable.notifyObservers(value);
  41173. }
  41174. },
  41175. enumerable: true,
  41176. configurable: true
  41177. });
  41178. Object.defineProperty(Prim2DBase.prototype, "isManualZOrder", {
  41179. get: function () {
  41180. return this._manualZOrder != null;
  41181. },
  41182. enumerable: true,
  41183. configurable: true
  41184. });
  41185. Object.defineProperty(Prim2DBase.prototype, "margin", {
  41186. get: function () {
  41187. var _this = this;
  41188. if (!this._margin) {
  41189. this._margin = new PrimitiveThickness(function () {
  41190. if (!_this.parent) {
  41191. return null;
  41192. }
  41193. return _this.parent.margin;
  41194. }, function () { return _this._positioningDirty(); });
  41195. }
  41196. return this._margin;
  41197. },
  41198. enumerable: true,
  41199. configurable: true
  41200. });
  41201. Object.defineProperty(Prim2DBase.prototype, "_hasMargin", {
  41202. get: function () {
  41203. return (this._margin !== null) || (this._marginAlignment !== null);
  41204. },
  41205. enumerable: true,
  41206. configurable: true
  41207. });
  41208. Object.defineProperty(Prim2DBase.prototype, "padding", {
  41209. get: function () {
  41210. var _this = this;
  41211. if (!this._padding) {
  41212. this._padding = new PrimitiveThickness(function () {
  41213. if (!_this.parent) {
  41214. return null;
  41215. }
  41216. return _this.parent.padding;
  41217. }, function () { return _this._positioningDirty(); });
  41218. }
  41219. return this._padding;
  41220. },
  41221. enumerable: true,
  41222. configurable: true
  41223. });
  41224. Object.defineProperty(Prim2DBase.prototype, "_hasPadding", {
  41225. get: function () {
  41226. return this._padding !== null;
  41227. },
  41228. enumerable: true,
  41229. configurable: true
  41230. });
  41231. Object.defineProperty(Prim2DBase.prototype, "marginAlignment", {
  41232. get: function () {
  41233. var _this = this;
  41234. if (!this._marginAlignment) {
  41235. this._marginAlignment = new PrimitiveAlignment(function () { return _this._positioningDirty(); });
  41236. }
  41237. return this._marginAlignment;
  41238. },
  41239. enumerable: true,
  41240. configurable: true
  41241. });
  41242. Object.defineProperty(Prim2DBase.prototype, "opacity", {
  41243. get: function () {
  41244. return this._opacity;
  41245. },
  41246. set: function (value) {
  41247. if (value < 0) {
  41248. value = 0;
  41249. }
  41250. else if (value > 1) {
  41251. value = 1;
  41252. }
  41253. if (this._opacity === value) {
  41254. return;
  41255. }
  41256. this._opacity = value;
  41257. this._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  41258. this._spreadActualOpacityChanged();
  41259. this._updateRenderMode();
  41260. },
  41261. enumerable: true,
  41262. configurable: true
  41263. });
  41264. Object.defineProperty(Prim2DBase.prototype, "scaleX", {
  41265. get: function () {
  41266. return this._scale.x;
  41267. },
  41268. set: function (value) {
  41269. this._scale.x = value;
  41270. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  41271. this._spreadActualScaleDirty();
  41272. },
  41273. enumerable: true,
  41274. configurable: true
  41275. });
  41276. Object.defineProperty(Prim2DBase.prototype, "scaleY", {
  41277. get: function () {
  41278. return this._scale.y;
  41279. },
  41280. set: function (value) {
  41281. this._scale.y = value;
  41282. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  41283. this._spreadActualScaleDirty();
  41284. },
  41285. enumerable: true,
  41286. configurable: true
  41287. });
  41288. Prim2DBase.prototype._spreadActualScaleDirty = function () {
  41289. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41290. var child = _a[_i];
  41291. child._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  41292. child._spreadActualScaleDirty();
  41293. }
  41294. };
  41295. Object.defineProperty(Prim2DBase.prototype, "actualScale", {
  41296. /**
  41297. * Returns the actual scale of this Primitive, the value is computed from the scale property of this primitive, multiplied by the actualScale of its parent one (if any). The Vector2 object returned contains the scale for both X and Y axis
  41298. */
  41299. get: function () {
  41300. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualScaleDirty)) {
  41301. var cur = this._isFlagSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? null : this.parent;
  41302. var sx = this.scaleX;
  41303. var sy = this.scaleY;
  41304. while (cur) {
  41305. sx *= cur.scaleX;
  41306. sy *= cur.scaleY;
  41307. cur = cur._isFlagSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? null : cur.parent;
  41308. }
  41309. this._actualScale.copyFromFloats(sx, sy);
  41310. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  41311. }
  41312. return this._actualScale;
  41313. },
  41314. enumerable: true,
  41315. configurable: true
  41316. });
  41317. Object.defineProperty(Prim2DBase.prototype, "actualScaleX", {
  41318. /**
  41319. * Get the actual Scale of the X axis, shortcut for this.actualScale.x
  41320. */
  41321. get: function () {
  41322. return this.actualScale.x;
  41323. },
  41324. enumerable: true,
  41325. configurable: true
  41326. });
  41327. Object.defineProperty(Prim2DBase.prototype, "actualScaleY", {
  41328. /**
  41329. * Get the actual Scale of the Y axis, shortcut for this.actualScale.y
  41330. */
  41331. get: function () {
  41332. return this.actualScale.y;
  41333. },
  41334. enumerable: true,
  41335. configurable: true
  41336. });
  41337. Object.defineProperty(Prim2DBase.prototype, "actualOpacity", {
  41338. /**
  41339. * Get the actual opacity level, this property is computed from the opacity property, multiplied by the actualOpacity of its parent (if any)
  41340. */
  41341. get: function () {
  41342. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualOpacityDirty)) {
  41343. var cur = this.parent;
  41344. var op = this.opacity;
  41345. while (cur) {
  41346. op *= cur.opacity;
  41347. cur = cur.parent;
  41348. }
  41349. this._actualOpacity = op;
  41350. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  41351. }
  41352. return this._actualOpacity;
  41353. },
  41354. enumerable: true,
  41355. configurable: true
  41356. });
  41357. Object.defineProperty(Prim2DBase.prototype, "layoutEngine", {
  41358. /**
  41359. * Get/set the layout engine to use for this primitive.
  41360. * The default layout engine is the CanvasLayoutEngine.
  41361. */
  41362. get: function () {
  41363. if (!this._layoutEngine) {
  41364. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  41365. }
  41366. return this._layoutEngine;
  41367. },
  41368. set: function (value) {
  41369. if (this._layoutEngine === value) {
  41370. return;
  41371. }
  41372. this._changeLayoutEngine(value);
  41373. },
  41374. enumerable: true,
  41375. configurable: true
  41376. });
  41377. Object.defineProperty(Prim2DBase.prototype, "layoutArea", {
  41378. /**
  41379. * Get/set the layout are of this primitive.
  41380. * The Layout area is the zone allocated by the Layout Engine for this particular primitive. Margins/Alignment will be computed based on this area.
  41381. * The setter should only be called by a Layout Engine class.
  41382. */
  41383. get: function () {
  41384. return this._layoutArea;
  41385. },
  41386. set: function (val) {
  41387. if (this._layoutArea.equals(val)) {
  41388. return;
  41389. }
  41390. this._positioningDirty();
  41391. if (this.parent) {
  41392. this.parent._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  41393. }
  41394. this._layoutArea = val;
  41395. },
  41396. enumerable: true,
  41397. configurable: true
  41398. });
  41399. Object.defineProperty(Prim2DBase.prototype, "layoutAreaPos", {
  41400. /**
  41401. * Get/set the layout area position (relative to the parent primitive).
  41402. * The setter should only be called by a Layout Engine class.
  41403. */
  41404. get: function () {
  41405. return this._layoutAreaPos || Prim2DBase._nullPosition;
  41406. },
  41407. set: function (val) {
  41408. if (this._layoutAreaPos && this._layoutAreaPos.equals(val)) {
  41409. return;
  41410. }
  41411. if (this.parent) {
  41412. this.parent._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  41413. }
  41414. this._positioningDirty();
  41415. this._layoutAreaPos = val;
  41416. },
  41417. enumerable: true,
  41418. configurable: true
  41419. });
  41420. Object.defineProperty(Prim2DBase.prototype, "isPickable", {
  41421. /**
  41422. * Define if the Primitive can be subject to intersection test or not (default is true)
  41423. */
  41424. get: function () {
  41425. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsPickable);
  41426. },
  41427. set: function (value) {
  41428. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsPickable, value);
  41429. },
  41430. enumerable: true,
  41431. configurable: true
  41432. });
  41433. Object.defineProperty(Prim2DBase.prototype, "isContainer", {
  41434. /**
  41435. * Define if the Primitive acts as a container or not
  41436. * A container will encapsulate its children for interaction event.
  41437. * If it's not a container events will be process down to children if the primitive is not pickable.
  41438. * Default value is true
  41439. */
  41440. get: function () {
  41441. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsContainer);
  41442. },
  41443. set: function (value) {
  41444. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsContainer, value);
  41445. },
  41446. enumerable: true,
  41447. configurable: true
  41448. });
  41449. Object.defineProperty(Prim2DBase.prototype, "hierarchyDepth", {
  41450. /**
  41451. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  41452. */
  41453. get: function () {
  41454. return this._hierarchyDepth;
  41455. },
  41456. enumerable: true,
  41457. configurable: true
  41458. });
  41459. Object.defineProperty(Prim2DBase.prototype, "renderGroup", {
  41460. /**
  41461. * Retrieve the Group that is responsible to render this primitive
  41462. */
  41463. get: function () {
  41464. return this._renderGroup;
  41465. },
  41466. enumerable: true,
  41467. configurable: true
  41468. });
  41469. Object.defineProperty(Prim2DBase.prototype, "globalTransform", {
  41470. /**
  41471. * Get the global transformation matrix of the primitive
  41472. */
  41473. get: function () {
  41474. this._updateLocalTransform();
  41475. return this._globalTransform;
  41476. },
  41477. enumerable: true,
  41478. configurable: true
  41479. });
  41480. /**
  41481. * return the global position of the primitive, relative to its canvas
  41482. */
  41483. Prim2DBase.prototype.getGlobalPosition = function () {
  41484. var v = new BABYLON.Vector2(0, 0);
  41485. this.getGlobalPositionByRef(v);
  41486. return v;
  41487. };
  41488. /**
  41489. * return the global position of the primitive, relative to its canvas
  41490. * @param v the valid Vector2 object where the global position will be stored
  41491. */
  41492. Prim2DBase.prototype.getGlobalPositionByRef = function (v) {
  41493. v.x = this.globalTransform.m[12];
  41494. v.y = this.globalTransform.m[13];
  41495. };
  41496. Object.defineProperty(Prim2DBase.prototype, "invGlobalTransform", {
  41497. /**
  41498. * Get invert of the global transformation matrix of the primitive
  41499. */
  41500. get: function () {
  41501. this._updateLocalTransform();
  41502. return this._invGlobalTransform;
  41503. },
  41504. enumerable: true,
  41505. configurable: true
  41506. });
  41507. Object.defineProperty(Prim2DBase.prototype, "localTransform", {
  41508. /**
  41509. * Get the local transformation of the primitive
  41510. */
  41511. get: function () {
  41512. this._updateLocalTransform();
  41513. return this._localTransform;
  41514. },
  41515. enumerable: true,
  41516. configurable: true
  41517. });
  41518. Object.defineProperty(Prim2DBase.prototype, "boundingInfo", {
  41519. /**
  41520. * Get the boundingInfo associated to the primitive and its children.
  41521. * The value is supposed to be always up to date
  41522. */
  41523. get: function () {
  41524. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  41525. if (this.owner) {
  41526. this.owner.boundingInfoRecomputeCounter.addCount(1, false);
  41527. }
  41528. if (this.isSizedByContent) {
  41529. this._boundingInfo.clear();
  41530. }
  41531. else {
  41532. this._boundingInfo.copyFrom(this.levelBoundingInfo);
  41533. }
  41534. var bi = this._boundingInfo;
  41535. var tps = new BABYLON.BoundingInfo2D();
  41536. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41537. var curChild = _a[_i];
  41538. var bb = curChild.boundingInfo;
  41539. bb.transformToRef(curChild.localTransform, tps);
  41540. bi.unionToRef(tps, bi);
  41541. }
  41542. this._boundingInfo.maxToRef(Prim2DBase._bMax);
  41543. 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);
  41544. this._clearFlags(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty);
  41545. }
  41546. return this._boundingInfo;
  41547. },
  41548. enumerable: true,
  41549. configurable: true
  41550. });
  41551. Object.defineProperty(Prim2DBase.prototype, "layoutBoundingInfo", {
  41552. /**
  41553. * Get the boundingInfo of the primitive's content arranged by a layout Engine
  41554. * If a particular child is not arranged by layout, it's boundingInfo is used instead to produce something as accurate as possible
  41555. */
  41556. get: function () {
  41557. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty)) {
  41558. if (!this._layoutBoundingInfo) {
  41559. this._layoutBoundingInfo = new BABYLON.BoundingInfo2D();
  41560. }
  41561. if (this.isSizedByContent) {
  41562. this._layoutBoundingInfo.clear();
  41563. }
  41564. else {
  41565. this._layoutBoundingInfo.copyFrom(this.levelBoundingInfo);
  41566. }
  41567. var bi = this._layoutBoundingInfo;
  41568. var tps = new BABYLON.BoundingInfo2D();
  41569. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41570. var curChild = _a[_i];
  41571. var bb = void 0;
  41572. if (curChild._layoutAreaPos) {
  41573. var s = curChild._layoutArea;
  41574. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(0, s.width, 0, s.height, Prim2DBase._tpsBB);
  41575. bb = Prim2DBase._tpsBB;
  41576. }
  41577. else {
  41578. bb = curChild.boundingInfo;
  41579. }
  41580. bb.transformToRef(curChild.localTransform, tps);
  41581. bi.unionToRef(tps, bi);
  41582. }
  41583. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  41584. }
  41585. return this._layoutBoundingInfo;
  41586. },
  41587. enumerable: true,
  41588. configurable: true
  41589. });
  41590. Object.defineProperty(Prim2DBase.prototype, "isSizeAuto", {
  41591. /**
  41592. * Determine if the size is automatically computed or fixed because manually specified.
  41593. * Use the actualSize property to get the final/real size of the primitive
  41594. * @returns true if the size is automatically computed, false if it were manually specified.
  41595. */
  41596. get: function () {
  41597. return this._size == null;
  41598. },
  41599. enumerable: true,
  41600. configurable: true
  41601. });
  41602. Object.defineProperty(Prim2DBase.prototype, "isSizedByContent", {
  41603. /**
  41604. * Return true if this prim has an auto size which is set by the children's global bounding box
  41605. */
  41606. get: function () {
  41607. return (this._size == null) && (this._children.length > 0);
  41608. },
  41609. enumerable: true,
  41610. configurable: true
  41611. });
  41612. Object.defineProperty(Prim2DBase.prototype, "isPositionAuto", {
  41613. /**
  41614. * Determine if the position is automatically computed or fixed because manually specified.
  41615. * Use the actualPosition property to get the final/real position of the primitive
  41616. * @returns true if the position is automatically computed, false if it were manually specified.
  41617. */
  41618. get: function () {
  41619. return this._position == null;
  41620. },
  41621. enumerable: true,
  41622. configurable: true
  41623. });
  41624. Object.defineProperty(Prim2DBase.prototype, "pointerEventObservable", {
  41625. /**
  41626. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  41627. */
  41628. get: function () {
  41629. return this._pointerEventObservable;
  41630. },
  41631. enumerable: true,
  41632. configurable: true
  41633. });
  41634. Object.defineProperty(Prim2DBase.prototype, "zActualOrderChangedObservable", {
  41635. get: function () {
  41636. if (!this._actualZOrderChangedObservable) {
  41637. this._actualZOrderChangedObservable = new BABYLON.Observable();
  41638. }
  41639. return this._actualZOrderChangedObservable;
  41640. },
  41641. enumerable: true,
  41642. configurable: true
  41643. });
  41644. Prim2DBase.prototype.findById = function (id) {
  41645. if (this._id === id) {
  41646. return this;
  41647. }
  41648. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41649. var child = _a[_i];
  41650. var r = child.findById(id);
  41651. if (r != null) {
  41652. return r;
  41653. }
  41654. }
  41655. };
  41656. Prim2DBase.prototype.onZOrderChanged = function () {
  41657. };
  41658. Prim2DBase.prototype.levelIntersect = function (intersectInfo) {
  41659. return false;
  41660. };
  41661. /**
  41662. * Capture all the Events of the given PointerId for this primitive.
  41663. * Don't forget to call releasePointerEventsCapture when done.
  41664. * @param pointerId the Id of the pointer to capture the events from.
  41665. */
  41666. Prim2DBase.prototype.setPointerEventCapture = function (pointerId) {
  41667. return this.owner._setPointerCapture(pointerId, this);
  41668. };
  41669. /**
  41670. * Release a captured pointer made with setPointerEventCapture.
  41671. * @param pointerId the Id of the pointer to release the capture from.
  41672. */
  41673. Prim2DBase.prototype.releasePointerEventsCapture = function (pointerId) {
  41674. return this.owner._releasePointerCapture(pointerId, this);
  41675. };
  41676. /**
  41677. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  41678. * @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.
  41679. */
  41680. Prim2DBase.prototype.intersect = function (intersectInfo) {
  41681. if (!intersectInfo) {
  41682. return false;
  41683. }
  41684. // If this is null it means this method is call for the first level, initialize stuffs
  41685. var firstLevel = !intersectInfo._globalPickPosition;
  41686. if (firstLevel) {
  41687. // 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).
  41688. intersectInfo._globalPickPosition = BABYLON.Vector2.Zero();
  41689. BABYLON.Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  41690. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  41691. intersectInfo.intersectedPrimitives = new Array();
  41692. intersectInfo.topMostIntersectedPrimitive = null;
  41693. }
  41694. if (!intersectInfo.intersectHidden && !this.isVisible) {
  41695. return false;
  41696. }
  41697. var id = this.id;
  41698. if (id != null && id.indexOf("__cachedSpriteOfGroup__") === 0) {
  41699. var ownerGroup = this.getExternalData("__cachedGroup__");
  41700. return ownerGroup.intersect(intersectInfo);
  41701. }
  41702. // If we're testing a cachedGroup, we must reject pointer outside its levelBoundingInfo because children primitives could be partially clipped outside so we must not accept them as intersected when it's the case (because they're not visually visible).
  41703. var isIntersectionTest = false;
  41704. if (this instanceof BABYLON.Group2D) {
  41705. var g = this;
  41706. isIntersectionTest = g.isCachedGroup;
  41707. }
  41708. if (isIntersectionTest && !this.levelBoundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  41709. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  41710. intersectInfo._exit(firstLevel);
  41711. return false;
  41712. }
  41713. // Fast rejection test with boundingInfo
  41714. if (this.isPickable && !this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  41715. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  41716. intersectInfo._exit(firstLevel);
  41717. return false;
  41718. }
  41719. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  41720. var levelIntersectRes = false;
  41721. if (this.isPickable) {
  41722. levelIntersectRes = this.levelIntersect(intersectInfo);
  41723. if (levelIntersectRes) {
  41724. var pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  41725. intersectInfo.intersectedPrimitives.push(pii);
  41726. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.actualZOffset > pii.prim.actualZOffset)) {
  41727. intersectInfo.topMostIntersectedPrimitive = pii;
  41728. }
  41729. // If we must stop at the first intersection, we're done, quit!
  41730. if (intersectInfo.findFirstOnly) {
  41731. intersectInfo._exit(firstLevel);
  41732. return true;
  41733. }
  41734. }
  41735. }
  41736. // Recurse to children if needed
  41737. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  41738. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41739. var curChild = _a[_i];
  41740. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  41741. if ((!curChild.isPickable && curChild.isContainer) || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  41742. continue;
  41743. }
  41744. // Must compute the localPickLocation for the children level
  41745. BABYLON.Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  41746. // If we got an intersection with the child and we only need to find the first one, quit!
  41747. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  41748. intersectInfo._exit(firstLevel);
  41749. return true;
  41750. }
  41751. }
  41752. }
  41753. intersectInfo._exit(firstLevel);
  41754. return intersectInfo.isIntersected;
  41755. };
  41756. /**
  41757. * Move a child object into a new position regarding its siblings to change its rendering order.
  41758. * You can also use the shortcut methods to move top/bottom: moveChildToTop, moveChildToBottom, moveToTop, moveToBottom.
  41759. * @param child the object to move
  41760. * @param previous the object which will be before "child", if child has to be the first among sibling, set "previous" to null.
  41761. */
  41762. Prim2DBase.prototype.moveChild = function (child, previous) {
  41763. if (child.parent !== this) {
  41764. return false;
  41765. }
  41766. var childIndex = this._children.indexOf(child);
  41767. var prevIndex = previous ? this._children.indexOf(previous) : -1;
  41768. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  41769. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41770. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, prevIndex + 1);
  41771. }
  41772. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  41773. return true;
  41774. };
  41775. /**
  41776. * Move the given child so it's displayed on the top of all its siblings
  41777. * @param child the primitive to move to the top
  41778. */
  41779. Prim2DBase.prototype.moveChildToTop = function (child) {
  41780. return this.moveChild(child, this._children[this._children.length - 1]);
  41781. };
  41782. /**
  41783. * Move the given child so it's displayed on the bottom of all its siblings
  41784. * @param child the primitive to move to the top
  41785. */
  41786. Prim2DBase.prototype.moveChildToBottom = function (child) {
  41787. return this.moveChild(child, null);
  41788. };
  41789. /**
  41790. * Move this primitive to be at the top among all its sibling
  41791. */
  41792. Prim2DBase.prototype.moveToTop = function () {
  41793. if (this.parent == null) {
  41794. return false;
  41795. }
  41796. return this.parent.moveChildToTop(this);
  41797. };
  41798. /**
  41799. * Move this primitive to be at the bottom among all its sibling
  41800. */
  41801. Prim2DBase.prototype.moveToBottom = function () {
  41802. if (this.parent == null) {
  41803. return false;
  41804. }
  41805. return this.parent.moveChildToBottom(this);
  41806. };
  41807. Prim2DBase.prototype.addChild = function (child) {
  41808. child._parent = this;
  41809. this._boundingBoxDirty();
  41810. var flat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  41811. if (flat) {
  41812. child._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  41813. child._setZOrder(this._zOrder, true);
  41814. child._zMax = this._zOrder;
  41815. }
  41816. else {
  41817. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41818. }
  41819. var length = this._children.push(child);
  41820. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, length - 1);
  41821. };
  41822. /**
  41823. * Dispose the primitive, remove it from its parent.
  41824. */
  41825. Prim2DBase.prototype.dispose = function () {
  41826. if (!_super.prototype.dispose.call(this)) {
  41827. return false;
  41828. }
  41829. if (this._actionManager) {
  41830. this._actionManager.dispose();
  41831. this._actionManager = null;
  41832. }
  41833. // If there's a parent, remove this object from its parent list
  41834. if (this._parent) {
  41835. if (this instanceof BABYLON.Group2D) {
  41836. var g = this;
  41837. if (g.isRenderableGroup) {
  41838. var parentRenderable = this.parent.traverseUp(function (p) { return (p instanceof BABYLON.Group2D && p.isRenderableGroup); });
  41839. if (parentRenderable != null) {
  41840. var l = parentRenderable._renderableData._childrenRenderableGroups;
  41841. var i_1 = l.indexOf(g);
  41842. if (i_1 !== -1) {
  41843. l.splice(i_1, 1);
  41844. }
  41845. }
  41846. }
  41847. }
  41848. var i = this._parent._children.indexOf(this);
  41849. if (i !== undefined) {
  41850. this._parent._children.splice(i, 1);
  41851. }
  41852. this._parent = null;
  41853. }
  41854. // Recurse dispose to children
  41855. if (this._children) {
  41856. while (this._children.length > 0) {
  41857. this._children[this._children.length - 1].dispose();
  41858. }
  41859. }
  41860. return true;
  41861. };
  41862. Prim2DBase.prototype.onPrimBecomesDirty = function () {
  41863. if (this._renderGroup && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPrimInDirtyList)) {
  41864. this._renderGroup._addPrimToDirtyList(this);
  41865. this._setFlags(BABYLON.SmartPropertyPrim.flagPrimInDirtyList);
  41866. }
  41867. };
  41868. Prim2DBase.prototype._needPrepare = function () {
  41869. return this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagModelDirty | BABYLON.SmartPropertyPrim.flagNeedRefresh) || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
  41870. };
  41871. Prim2DBase.prototype._prepareRender = function (context) {
  41872. this._prepareRenderPre(context);
  41873. this._prepareRenderPost(context);
  41874. };
  41875. Prim2DBase.prototype._prepareRenderPre = function (context) {
  41876. };
  41877. Prim2DBase.prototype._prepareRenderPost = function (context) {
  41878. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  41879. if (this instanceof BABYLON.Group2D) {
  41880. var self = this;
  41881. if (self.isRenderableGroup) {
  41882. return;
  41883. }
  41884. }
  41885. // Check if we need to recurse the prepare to children primitives
  41886. // - must have children
  41887. // - the global transform of this level have changed, or
  41888. // - the visible state of primitive has changed
  41889. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  41890. this.checkPropertiesDirty(Prim2DBase.isVisibleProperty.flagId))) {
  41891. this._children.forEach(function (c) {
  41892. // As usual stop the recursion if we meet a renderable group
  41893. if (!(c instanceof BABYLON.Group2D && c.isRenderableGroup)) {
  41894. c._prepareRender(context);
  41895. }
  41896. });
  41897. }
  41898. // Finally reset the dirty flags as we've processed everything
  41899. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  41900. this._instanceDirtyFlags = 0;
  41901. };
  41902. Prim2DBase.prototype._canvasPreInit = function (settings) {
  41903. };
  41904. Prim2DBase.CheckParent = function (parent) {
  41905. //if (!Prim2DBase._isCanvasInit && !parent) {
  41906. // 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)");
  41907. //}
  41908. };
  41909. Prim2DBase.prototype.updateCachedStatesOf = function (list, recurse) {
  41910. for (var _i = 0; _i < list.length; _i++) {
  41911. var cur = list[_i];
  41912. cur.updateCachedStates(recurse);
  41913. }
  41914. };
  41915. Prim2DBase.prototype._parentLayoutDirty = function () {
  41916. if (!this._parent || this._parent.isDisposed) {
  41917. return;
  41918. }
  41919. this._parent._setLayoutDirty();
  41920. };
  41921. Prim2DBase.prototype._setLayoutDirty = function () {
  41922. this.onPrimBecomesDirty();
  41923. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  41924. };
  41925. Prim2DBase.prototype._checkPositionChange = function () {
  41926. if (this.parent && this.parent.layoutEngine.isChildPositionAllowed === false) {
  41927. console.log("Can't manually set the position of " + this.id + ", the Layout Engine of its parent doesn't allow it");
  41928. return false;
  41929. }
  41930. return true;
  41931. };
  41932. Prim2DBase.prototype._positioningDirty = function () {
  41933. this.onPrimBecomesDirty();
  41934. this._setFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41935. };
  41936. Prim2DBase.prototype._spreadActualOpacityChanged = function () {
  41937. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41938. var child = _a[_i];
  41939. child._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  41940. child._updateRenderMode();
  41941. child.onPrimBecomesDirty();
  41942. child._spreadActualOpacityChanged();
  41943. }
  41944. };
  41945. Prim2DBase.prototype._changeLayoutEngine = function (engine) {
  41946. this._layoutEngine = engine;
  41947. };
  41948. Prim2DBase.prototype._updateLocalTransform = function () {
  41949. var tflags = Prim2DBase.actualPositionProperty.flagId | Prim2DBase.rotationProperty.flagId | Prim2DBase.scaleProperty.flagId | Prim2DBase.scaleXProperty.flagId | Prim2DBase.scaleYProperty.flagId | Prim2DBase.originProperty.flagId;
  41950. if (this.checkPropertiesDirty(tflags)) {
  41951. if (this.owner) {
  41952. this.owner.addupdateLocalTransformCounter(1);
  41953. }
  41954. var rot = BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), this._rotation);
  41955. var local;
  41956. var pos = this._position ? this.position : this.layoutAreaPos;
  41957. if (this._origin.x === 0 && this._origin.y === 0) {
  41958. local = BABYLON.Matrix.Compose(new BABYLON.Vector3(this._scale.x, this._scale.y, 1), rot, new BABYLON.Vector3(pos.x, pos.y, 0));
  41959. this._localTransform = local;
  41960. }
  41961. else {
  41962. // -Origin offset
  41963. var as = this.actualSize;
  41964. BABYLON.Matrix.TranslationToRef((-as.width * this._origin.x), (-as.height * this._origin.y), 0, Prim2DBase._t0);
  41965. // -Origin * rotation
  41966. rot.toRotationMatrix(Prim2DBase._t1);
  41967. Prim2DBase._t0.multiplyToRef(Prim2DBase._t1, Prim2DBase._t2);
  41968. // -Origin * rotation * scale
  41969. BABYLON.Matrix.ScalingToRef(this._scale.x, this._scale.y, 1, Prim2DBase._t0);
  41970. Prim2DBase._t2.multiplyToRef(Prim2DBase._t0, Prim2DBase._t1);
  41971. // -Origin * rotation * scale * (Origin + Position)
  41972. BABYLON.Matrix.TranslationToRef((as.width * this._origin.x) + pos.x, (as.height * this._origin.y) + pos.y, 0, Prim2DBase._t2);
  41973. Prim2DBase._t1.multiplyToRef(Prim2DBase._t2, this._localTransform);
  41974. }
  41975. this.clearPropertiesDirty(tflags);
  41976. this._setFlags(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  41977. return true;
  41978. }
  41979. return false;
  41980. };
  41981. Prim2DBase.prototype.updateCachedStates = function (recurse) {
  41982. if (this.isDisposed) {
  41983. return;
  41984. }
  41985. this.owner.addCachedGroupRenderCounter(1);
  41986. // Check if the parent is synced
  41987. if (this._parent && ((this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || this._parent._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagLayoutDirty | BABYLON.SmartPropertyPrim.flagPositioningDirty | BABYLON.SmartPropertyPrim.flagZOrderDirty))) {
  41988. this._parent.updateCachedStates(false);
  41989. }
  41990. // Update Z-Order if needed
  41991. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  41992. this._updateZOrder();
  41993. }
  41994. // Update actualSize only if there' not positioning to recompute and the size changed
  41995. // Otherwise positioning will take care of it.
  41996. var sizeDirty = this.checkPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  41997. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty) && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) && sizeDirty) {
  41998. var size = this.size;
  41999. if (size) {
  42000. if (this.size.width != null) {
  42001. this.actualSize.width = this.size.width;
  42002. }
  42003. if (this.size.height != null) {
  42004. this.actualSize.height = this.size.height;
  42005. }
  42006. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  42007. }
  42008. }
  42009. var positioningDirty = this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  42010. var positioningComputed = positioningDirty && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  42011. // Check for layout update
  42012. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  42013. this.owner.addUpdateLayoutCounter(1);
  42014. this._layoutEngine.updateLayout(this);
  42015. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  42016. }
  42017. var autoContentChanged = false;
  42018. if (this.isSizeAuto) {
  42019. if (!this._lastAutoSizeArea) {
  42020. autoContentChanged = this.actualSize !== null;
  42021. }
  42022. else {
  42023. autoContentChanged = (!this._lastAutoSizeArea.equals(this.actualSize));
  42024. }
  42025. }
  42026. // Check for positioning update
  42027. if (!positioningComputed && (autoContentChanged || sizeDirty || this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) || (this._parent && !this._parent.contentArea.equals(this._parentContentArea)))) {
  42028. this._updatePositioning();
  42029. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  42030. if (sizeDirty) {
  42031. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  42032. }
  42033. positioningComputed = true;
  42034. }
  42035. if (positioningComputed && this._parent) {
  42036. this._parentContentArea.copyFrom(this._parent.contentArea);
  42037. }
  42038. // Check if we must update this prim
  42039. if (this === this.owner || this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  42040. this.owner.addUpdateGlobalTransformCounter(1);
  42041. var curVisibleState = this.isVisible;
  42042. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  42043. // Detect a change of visibility
  42044. this._changeFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged, curVisibleState !== this.isVisible);
  42045. // Get/compute the localTransform
  42046. var localDirty = this._updateLocalTransform();
  42047. var parentPaddingChanged = false;
  42048. var parentPaddingOffset = Prim2DBase._v0;
  42049. if (this._parent) {
  42050. parentPaddingOffset = this._parent._paddingOffset;
  42051. parentPaddingChanged = !parentPaddingOffset.equals(this._parentPaddingOffset);
  42052. }
  42053. // Check if there are changes in the parent that will force us to update the global matrix
  42054. var parentDirty = (this._parent != null) ? (this._parent._globalTransformStep !== this._parentTransformStep) : false;
  42055. // Check if we have to update the globalTransform
  42056. if (!this._globalTransform || localDirty || parentDirty || parentPaddingChanged || this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty)) {
  42057. var globalTransform = this._parent ? this._parent._globalTransform : null;
  42058. var localTransform;
  42059. Prim2DBase._transMtx.copyFrom(this._localTransform);
  42060. Prim2DBase._transMtx.m[12] += this._marginOffset.x + parentPaddingOffset.x;
  42061. Prim2DBase._transMtx.m[13] += this._marginOffset.y + parentPaddingOffset.y;
  42062. localTransform = Prim2DBase._transMtx;
  42063. this._globalTransform = this._parent ? localTransform.multiply(globalTransform) : localTransform.clone();
  42064. this._invGlobalTransform = BABYLON.Matrix.Invert(this._globalTransform);
  42065. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  42066. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  42067. this._clearFlags(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  42068. }
  42069. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  42070. }
  42071. if (recurse) {
  42072. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  42073. var child = _a[_i];
  42074. // Stop the recursion if we meet a renderable group
  42075. child.updateCachedStates(!(child instanceof BABYLON.Group2D && child.isRenderableGroup));
  42076. }
  42077. }
  42078. };
  42079. Prim2DBase.prototype._updatePositioning = function () {
  42080. if (this.owner) {
  42081. this.owner.addUpdatePositioningCounter(1);
  42082. }
  42083. // From this point we assume that the primitive layoutArea is computed and up to date.
  42084. // We know have to :
  42085. // 1. Determine the PaddingArea and the ActualPosition based on the margin/marginAlignment properties, which will also set the size property of the primitive
  42086. // 2. Determine the contentArea based on the padding property.
  42087. // 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
  42088. if (!this._hasMargin && (this.actualSize.width == null || this.actualSize.height == null)) {
  42089. if (this.actualSize.width == null) {
  42090. this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  42091. }
  42092. if (this.actualSize.height == null) {
  42093. this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  42094. }
  42095. }
  42096. // Apply margin
  42097. if (this._hasMargin) {
  42098. this.margin.computeWithAlignment(this.layoutArea, this.size || this.actualSize, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  42099. this.actualSize = Prim2DBase._size.clone();
  42100. }
  42101. var isSizeAuto = this.isSizeAuto;
  42102. if (this._hasPadding) {
  42103. // Two cases from here: the size of the Primitive is Auto, its content can't be shrink, so me resize the primitive itself
  42104. if (isSizeAuto) {
  42105. var content = this.size.clone();
  42106. this._getActualSizeFromContentToRef(content, Prim2DBase._icArea);
  42107. this.padding.enlarge(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  42108. this._contentArea.copyFrom(content);
  42109. this.actualSize = Prim2DBase._size.clone();
  42110. // Changing the padding has resize the prim, which forces us to recompute margin again
  42111. if (this._hasMargin) {
  42112. this.margin.computeWithAlignment(this.layoutArea, Prim2DBase._size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  42113. }
  42114. }
  42115. else {
  42116. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  42117. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  42118. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  42119. this.padding.compute(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  42120. this._paddingOffset.x += Prim2DBase._icPos.x;
  42121. this._paddingOffset.y += Prim2DBase._icPos.y;
  42122. this._contentArea.copyFrom(Prim2DBase._size);
  42123. }
  42124. }
  42125. else {
  42126. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  42127. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  42128. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  42129. this._paddingOffset.copyFrom(Prim2DBase._icPos);
  42130. this._contentArea.copyFrom(Prim2DBase._icArea);
  42131. }
  42132. if (!this._position) {
  42133. var aPos = new BABYLON.Vector2(this.layoutAreaPos.x + this._marginOffset.x, this.layoutAreaPos.y + this._marginOffset.y);
  42134. this.actualPosition = aPos;
  42135. }
  42136. if (isSizeAuto) {
  42137. this._lastAutoSizeArea = this.actualSize;
  42138. }
  42139. };
  42140. Object.defineProperty(Prim2DBase.prototype, "contentArea", {
  42141. /**
  42142. * Get the content are of this primitive, this area is computed using the padding property and also possibly the primitive type itself.
  42143. * Children of this primitive will be positioned relative to the bottom/left corner of this area.
  42144. */
  42145. get: function () {
  42146. // Check for positioning update
  42147. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  42148. this._updatePositioning();
  42149. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  42150. }
  42151. return this._contentArea;
  42152. },
  42153. enumerable: true,
  42154. configurable: true
  42155. });
  42156. Prim2DBase.prototype._patchHierarchy = function (owner) {
  42157. this._owner = owner;
  42158. // The only place we initialize the _renderGroup is this method, if it's set, we already been there, no need to execute more
  42159. if (this._renderGroup != null) {
  42160. return;
  42161. }
  42162. if (this instanceof BABYLON.Group2D) {
  42163. var group = this;
  42164. group.detectGroupStates();
  42165. if (group._trackedNode && !group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  42166. group.owner._registerTrackedNode(this);
  42167. }
  42168. }
  42169. this._renderGroup = this.traverseUp(function (p) { return p instanceof BABYLON.Group2D && p.isRenderableGroup; });
  42170. if (this._parent) {
  42171. this._parentLayoutDirty();
  42172. }
  42173. // Make sure the prim is in the dirtyList if it should be
  42174. if (this._renderGroup && this.isDirty) {
  42175. var list = this._renderGroup._renderableData._primDirtyList;
  42176. var i = list.indexOf(this);
  42177. if (i === -1) {
  42178. list.push(this);
  42179. }
  42180. }
  42181. // Recurse
  42182. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  42183. var child = _a[_i];
  42184. child._hierarchyDepth = this._hierarchyDepth + 1;
  42185. child._patchHierarchy(owner);
  42186. }
  42187. };
  42188. Prim2DBase.prototype._updateZOrder = function () {
  42189. var prevLinPos = this._primLinearPosition;
  42190. var startI = 0;
  42191. var startZ = this._zOrder;
  42192. // 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
  42193. var childrenCount = this._children.length;
  42194. if (this._firstZDirtyIndex > 0) {
  42195. if ((this._firstZDirtyIndex - 1) < childrenCount) {
  42196. var prevPrim = this._children[this._firstZDirtyIndex - 1];
  42197. prevLinPos = prevPrim._primLinearPosition;
  42198. startI = this._firstZDirtyIndex - 1;
  42199. startZ = prevPrim._zOrder;
  42200. }
  42201. }
  42202. var startPos = prevLinPos;
  42203. // Update the linear position of the primitive from the first one to the last inside this primitive, compute the total number of prim traversed
  42204. Prim2DBase._totalCount = 0;
  42205. for (var i = startI; i < childrenCount; i++) {
  42206. var child = this._children[i];
  42207. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  42208. }
  42209. // Compute the new Z-Order for all the primitives
  42210. // Add 20% to the current total count to reserve space for future insertions, except if we're rebuilding due to a zMinDelta reached
  42211. var zDelta = (this._zMax - startZ) / (Prim2DBase._totalCount * (Prim2DBase._zRebuildReentrency ? 1 : 1.2));
  42212. // 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.
  42213. if (zDelta < BABYLON.Canvas2D._zMinDelta) {
  42214. // 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...
  42215. if (Prim2DBase._zRebuildReentrency) {
  42216. var p = this._parent;
  42217. if (p == null) {
  42218. // 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...)
  42219. console.log("Can't compute Z-Order for " + this.id + "'s children, zDelta is too small, Z-Order is now in an unstable state");
  42220. Prim2DBase._zRebuildReentrency = false;
  42221. return;
  42222. }
  42223. p._firstZDirtyIndex = 0;
  42224. return p._updateZOrder();
  42225. }
  42226. Prim2DBase._zRebuildReentrency = true;
  42227. this._firstZDirtyIndex = 0;
  42228. this._updateZOrder();
  42229. Prim2DBase._zRebuildReentrency = false;
  42230. }
  42231. for (var i = startI; i < childrenCount; i++) {
  42232. var child = this._children[i];
  42233. child._updatePrimitiveZOrder(startPos, startZ, zDelta);
  42234. }
  42235. // Notify the Observers that we found during the Z change (we do it after to avoid any kind of re-entrance)
  42236. for (var _i = 0, _a = Prim2DBase._zOrderChangedNotifList; _i < _a.length; _i++) {
  42237. var p = _a[_i];
  42238. p._actualZOrderChangedObservable.notifyObservers(p.actualZOffset);
  42239. }
  42240. Prim2DBase._zOrderChangedNotifList.splice(0);
  42241. this._firstZDirtyIndex = Prim2DBase._bigInt;
  42242. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  42243. };
  42244. Prim2DBase.prototype._updatePrimitiveLinearPosition = function (prevLinPos) {
  42245. if (this.isManualZOrder) {
  42246. return prevLinPos;
  42247. }
  42248. this._primLinearPosition = ++prevLinPos;
  42249. Prim2DBase._totalCount++;
  42250. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  42251. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  42252. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  42253. var child = _a[_i];
  42254. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  42255. }
  42256. }
  42257. return prevLinPos;
  42258. };
  42259. Prim2DBase.prototype._updatePrimitiveZOrder = function (startPos, startZ, deltaZ) {
  42260. if (this.isManualZOrder) {
  42261. return null;
  42262. }
  42263. var newZ = startZ + ((this._primLinearPosition - startPos) * deltaZ);
  42264. var isFlat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  42265. this._setZOrder(newZ, false);
  42266. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  42267. this._firstZDirtyIndex = Prim2DBase._bigInt;
  42268. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  42269. }
  42270. var curZ = newZ;
  42271. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  42272. if (isFlat) {
  42273. if (this._children.length > 0) {
  42274. //let childrenZOrder = startZ + ((this._children[0]._primLinearPosition - startPos) * deltaZ);
  42275. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  42276. var child = _a[_i];
  42277. child._updatePrimitiveFlatZOrder(this._zOrder);
  42278. }
  42279. }
  42280. }
  42281. else {
  42282. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  42283. var child = _c[_b];
  42284. var r = child._updatePrimitiveZOrder(startPos, startZ, deltaZ);
  42285. if (r != null) {
  42286. curZ = r;
  42287. }
  42288. }
  42289. }
  42290. this._zMax = isFlat ? newZ : (curZ + deltaZ);
  42291. return curZ;
  42292. };
  42293. Prim2DBase.prototype._updatePrimitiveFlatZOrder = function (newZ) {
  42294. if (this.isManualZOrder) {
  42295. return;
  42296. }
  42297. this._setZOrder(newZ, false);
  42298. this._zMax = newZ;
  42299. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  42300. this._firstZDirtyIndex = Prim2DBase._bigInt;
  42301. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  42302. }
  42303. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  42304. var child = _a[_i];
  42305. child._updatePrimitiveFlatZOrder(newZ);
  42306. }
  42307. };
  42308. Prim2DBase.prototype._setZOrder = function (newZ, directEmit) {
  42309. if (newZ !== this._zOrder) {
  42310. this._zOrder = newZ;
  42311. this.onPrimBecomesDirty();
  42312. this.onZOrderChanged();
  42313. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  42314. if (directEmit) {
  42315. this._actualZOrderChangedObservable.notifyObservers(newZ);
  42316. }
  42317. else {
  42318. Prim2DBase._zOrderChangedNotifList.push(this);
  42319. }
  42320. }
  42321. }
  42322. };
  42323. Prim2DBase.prototype._updateRenderMode = function () {
  42324. };
  42325. /**
  42326. * This method is used to alter the contentArea of the Primitive before margin is applied.
  42327. * 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.
  42328. * @param primSize the current size of the primitive
  42329. * @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!
  42330. * @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!
  42331. */
  42332. Prim2DBase.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  42333. initialContentArea.copyFrom(primSize);
  42334. initialContentPosition.x = initialContentPosition.y = 0;
  42335. };
  42336. /**
  42337. * This method is used to calculate the new size of the primitive based on the content which must stay the same
  42338. * Check the Rectangle2D implementation for a concrete application.
  42339. * @param primSize the current size of the primitive
  42340. * @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!
  42341. */
  42342. Prim2DBase.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  42343. newPrimSize.copyFrom(primSize);
  42344. };
  42345. Prim2DBase.PRIM2DBASE_PROPCOUNT = 16;
  42346. Prim2DBase._bigInt = Math.pow(2, 30);
  42347. Prim2DBase._nullPosition = BABYLON.Vector2.Zero();
  42348. Prim2DBase.boundinbBoxReentrency = false;
  42349. Prim2DBase.nullSize = BABYLON.Size.Zero();
  42350. Prim2DBase._bMax = BABYLON.Vector2.Zero();
  42351. Prim2DBase._tpsBB = new BABYLON.BoundingInfo2D();
  42352. Prim2DBase._isCanvasInit = false;
  42353. Prim2DBase._t0 = new BABYLON.Matrix();
  42354. Prim2DBase._t1 = new BABYLON.Matrix();
  42355. Prim2DBase._t2 = new BABYLON.Matrix();
  42356. Prim2DBase._v0 = BABYLON.Vector2.Zero(); // Must stay with the value 0,0
  42357. Prim2DBase._transMtx = BABYLON.Matrix.Zero();
  42358. Prim2DBase._icPos = BABYLON.Vector2.Zero();
  42359. Prim2DBase._icArea = BABYLON.Size.Zero();
  42360. Prim2DBase._size = BABYLON.Size.Zero();
  42361. Prim2DBase._zOrderChangedNotifList = new Array();
  42362. Prim2DBase._zRebuildReentrency = false;
  42363. Prim2DBase._totalCount = 0;
  42364. __decorate([
  42365. BABYLON.instanceLevelProperty(1, function (pi) { return Prim2DBase.actualPositionProperty = pi; }, false, false, true)
  42366. ], Prim2DBase.prototype, "actualPosition", null);
  42367. __decorate([
  42368. BABYLON.dynamicLevelProperty(2, function (pi) { return Prim2DBase.positionProperty = pi; }, false, false, true)
  42369. ], Prim2DBase.prototype, "position", null);
  42370. __decorate([
  42371. BABYLON.dynamicLevelProperty(3, function (pi) { return Prim2DBase.sizeProperty = pi; }, false, true)
  42372. ], Prim2DBase.prototype, "size", null);
  42373. __decorate([
  42374. BABYLON.instanceLevelProperty(4, function (pi) { return Prim2DBase.rotationProperty = pi; }, false, true)
  42375. ], Prim2DBase.prototype, "rotation", null);
  42376. __decorate([
  42377. BABYLON.instanceLevelProperty(5, function (pi) { return Prim2DBase.scaleProperty = pi; }, false, true)
  42378. ], Prim2DBase.prototype, "scale", null);
  42379. __decorate([
  42380. BABYLON.dynamicLevelProperty(6, function (pi) { return Prim2DBase.originProperty = pi; }, false, true)
  42381. ], Prim2DBase.prototype, "origin", null);
  42382. __decorate([
  42383. BABYLON.dynamicLevelProperty(7, function (pi) { return Prim2DBase.levelVisibleProperty = pi; })
  42384. ], Prim2DBase.prototype, "levelVisible", null);
  42385. __decorate([
  42386. BABYLON.instanceLevelProperty(8, function (pi) { return Prim2DBase.isVisibleProperty = pi; })
  42387. ], Prim2DBase.prototype, "isVisible", null);
  42388. __decorate([
  42389. BABYLON.instanceLevelProperty(9, function (pi) { return Prim2DBase.zOrderProperty = pi; })
  42390. ], Prim2DBase.prototype, "zOrder", null);
  42391. __decorate([
  42392. BABYLON.dynamicLevelProperty(10, function (pi) { return Prim2DBase.marginProperty = pi; })
  42393. ], Prim2DBase.prototype, "margin", null);
  42394. __decorate([
  42395. BABYLON.dynamicLevelProperty(11, function (pi) { return Prim2DBase.paddingProperty = pi; })
  42396. ], Prim2DBase.prototype, "padding", null);
  42397. __decorate([
  42398. BABYLON.dynamicLevelProperty(12, function (pi) { return Prim2DBase.marginAlignmentProperty = pi; })
  42399. ], Prim2DBase.prototype, "marginAlignment", null);
  42400. __decorate([
  42401. BABYLON.instanceLevelProperty(13, function (pi) { return Prim2DBase.opacityProperty = pi; })
  42402. ], Prim2DBase.prototype, "opacity", null);
  42403. __decorate([
  42404. BABYLON.instanceLevelProperty(14, function (pi) { return Prim2DBase.scaleXProperty = pi; }, false, true)
  42405. ], Prim2DBase.prototype, "scaleX", null);
  42406. __decorate([
  42407. BABYLON.instanceLevelProperty(15, function (pi) { return Prim2DBase.scaleYProperty = pi; }, false, true)
  42408. ], Prim2DBase.prototype, "scaleY", null);
  42409. Prim2DBase = __decorate([
  42410. BABYLON.className("Prim2DBase")
  42411. ], Prim2DBase);
  42412. return Prim2DBase;
  42413. })(BABYLON.SmartPropertyPrim);
  42414. BABYLON.Prim2DBase = Prim2DBase;
  42415. })(BABYLON || (BABYLON = {}));
  42416. var BABYLON;
  42417. (function (BABYLON) {
  42418. var GroupInstanceInfo = (function () {
  42419. function GroupInstanceInfo(owner, mrc, partCount) {
  42420. this._partCount = partCount;
  42421. this.owner = owner;
  42422. this.modelRenderCache = mrc;
  42423. this.modelRenderCache.addRef();
  42424. this.partIndexFromId = new BABYLON.StringDictionary();
  42425. this._usedShaderCategories = new Array(partCount);
  42426. this._strides = new Array(partCount);
  42427. this._opaqueData = null;
  42428. this._alphaTestData = null;
  42429. this._transparentData = null;
  42430. this.opaqueDirty = this.alphaTestDirty = this.transparentDirty = this.transparentOrderDirty = false;
  42431. }
  42432. GroupInstanceInfo.prototype.dispose = function () {
  42433. if (this._isDisposed) {
  42434. return false;
  42435. }
  42436. if (this.modelRenderCache) {
  42437. this.modelRenderCache.dispose();
  42438. this.modelRenderCache = null;
  42439. }
  42440. var engine = this.owner.owner.engine;
  42441. if (this._opaqueData) {
  42442. this._opaqueData.forEach(function (d) { return d.dispose(engine); });
  42443. this._opaqueData = null;
  42444. }
  42445. if (this._alphaTestData) {
  42446. this._alphaTestData.forEach(function (d) { return d.dispose(engine); });
  42447. this._alphaTestData = null;
  42448. }
  42449. if (this._transparentData) {
  42450. this._transparentData.forEach(function (d) { return d.dispose(engine); });
  42451. this._transparentData = null;
  42452. }
  42453. this.partIndexFromId = null;
  42454. this._isDisposed = true;
  42455. return true;
  42456. };
  42457. Object.defineProperty(GroupInstanceInfo.prototype, "hasOpaqueData", {
  42458. get: function () {
  42459. return this._opaqueData != null;
  42460. },
  42461. enumerable: true,
  42462. configurable: true
  42463. });
  42464. Object.defineProperty(GroupInstanceInfo.prototype, "hasAlphaTestData", {
  42465. get: function () {
  42466. return this._alphaTestData != null;
  42467. },
  42468. enumerable: true,
  42469. configurable: true
  42470. });
  42471. Object.defineProperty(GroupInstanceInfo.prototype, "hasTransparentData", {
  42472. get: function () {
  42473. return this._transparentData != null;
  42474. },
  42475. enumerable: true,
  42476. configurable: true
  42477. });
  42478. Object.defineProperty(GroupInstanceInfo.prototype, "opaqueData", {
  42479. get: function () {
  42480. if (!this._opaqueData) {
  42481. this._opaqueData = new Array(this._partCount);
  42482. for (var i = 0; i < this._partCount; i++) {
  42483. this._opaqueData[i] = new GroupInfoPartData(this._strides[i]);
  42484. }
  42485. }
  42486. return this._opaqueData;
  42487. },
  42488. enumerable: true,
  42489. configurable: true
  42490. });
  42491. Object.defineProperty(GroupInstanceInfo.prototype, "alphaTestData", {
  42492. get: function () {
  42493. if (!this._alphaTestData) {
  42494. this._alphaTestData = new Array(this._partCount);
  42495. for (var i = 0; i < this._partCount; i++) {
  42496. this._alphaTestData[i] = new GroupInfoPartData(this._strides[i]);
  42497. }
  42498. }
  42499. return this._alphaTestData;
  42500. },
  42501. enumerable: true,
  42502. configurable: true
  42503. });
  42504. Object.defineProperty(GroupInstanceInfo.prototype, "transparentData", {
  42505. get: function () {
  42506. if (!this._transparentData) {
  42507. this._transparentData = new Array(this._partCount);
  42508. for (var i = 0; i < this._partCount; i++) {
  42509. var zoff = this.modelRenderCache._partData[i]._zBiasOffset;
  42510. this._transparentData[i] = new TransparentGroupInfoPartData(this._strides[i], zoff);
  42511. }
  42512. }
  42513. return this._transparentData;
  42514. },
  42515. enumerable: true,
  42516. configurable: true
  42517. });
  42518. GroupInstanceInfo.prototype.sortTransparentData = function () {
  42519. if (!this.transparentOrderDirty) {
  42520. return;
  42521. }
  42522. for (var i = 0; i < this._transparentData.length; i++) {
  42523. var td = this._transparentData[i];
  42524. td._partData.sort();
  42525. }
  42526. this.transparentOrderDirty = false;
  42527. };
  42528. Object.defineProperty(GroupInstanceInfo.prototype, "usedShaderCategories", {
  42529. get: function () {
  42530. return this._usedShaderCategories;
  42531. },
  42532. enumerable: true,
  42533. configurable: true
  42534. });
  42535. Object.defineProperty(GroupInstanceInfo.prototype, "strides", {
  42536. get: function () {
  42537. return this._strides;
  42538. },
  42539. enumerable: true,
  42540. configurable: true
  42541. });
  42542. return GroupInstanceInfo;
  42543. })();
  42544. BABYLON.GroupInstanceInfo = GroupInstanceInfo;
  42545. var TransparentSegment = (function () {
  42546. function TransparentSegment() {
  42547. this.groupInsanceInfo = null;
  42548. this.startZ = 0;
  42549. this.endZ = 0;
  42550. this.startDataIndex = BABYLON.Prim2DBase._bigInt;
  42551. this.endDataIndex = 0;
  42552. this.partBuffers = null;
  42553. }
  42554. TransparentSegment.prototype.dispose = function (engine) {
  42555. if (this.partBuffers) {
  42556. this.partBuffers.forEach(function (b) { return engine._releaseBuffer(b); });
  42557. this.partBuffers.splice(0);
  42558. this.partBuffers = null;
  42559. }
  42560. };
  42561. return TransparentSegment;
  42562. })();
  42563. BABYLON.TransparentSegment = TransparentSegment;
  42564. var GroupInfoPartData = (function () {
  42565. function GroupInfoPartData(stride) {
  42566. this._partData = null;
  42567. this._partBuffer = null;
  42568. this._partBufferSize = 0;
  42569. this._partData = new BABYLON.DynamicFloatArray(stride / 4, 50);
  42570. this._isDisposed = false;
  42571. }
  42572. GroupInfoPartData.prototype.dispose = function (engine) {
  42573. if (this._isDisposed) {
  42574. return false;
  42575. }
  42576. if (this._partBuffer) {
  42577. engine._releaseBuffer(this._partBuffer);
  42578. this._partBuffer = null;
  42579. }
  42580. this._partData = null;
  42581. this._isDisposed = true;
  42582. };
  42583. return GroupInfoPartData;
  42584. })();
  42585. BABYLON.GroupInfoPartData = GroupInfoPartData;
  42586. var TransparentGroupInfoPartData = (function (_super) {
  42587. __extends(TransparentGroupInfoPartData, _super);
  42588. function TransparentGroupInfoPartData(stride, zoff) {
  42589. _super.call(this, stride);
  42590. this._partData.compareValueOffset = zoff;
  42591. this._partData.sortingAscending = false;
  42592. }
  42593. return TransparentGroupInfoPartData;
  42594. })(GroupInfoPartData);
  42595. BABYLON.TransparentGroupInfoPartData = TransparentGroupInfoPartData;
  42596. var ModelRenderCache = (function () {
  42597. function ModelRenderCache(engine, modelKey) {
  42598. this._engine = engine;
  42599. this._modelKey = modelKey;
  42600. this._nextKey = 1;
  42601. this._refCounter = 1;
  42602. this._partData = null;
  42603. }
  42604. ModelRenderCache.prototype.dispose = function () {
  42605. if (--this._refCounter !== 0) {
  42606. return false;
  42607. }
  42608. // Remove the Model Render Cache from the global dictionary
  42609. var edata = this._engine.getExternalData("__BJSCANVAS2D__");
  42610. if (edata) {
  42611. edata.DisposeModelRenderCache(this);
  42612. }
  42613. return true;
  42614. };
  42615. Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
  42616. get: function () {
  42617. return this._refCounter <= 0;
  42618. },
  42619. enumerable: true,
  42620. configurable: true
  42621. });
  42622. ModelRenderCache.prototype.addRef = function () {
  42623. return ++this._refCounter;
  42624. };
  42625. Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
  42626. get: function () {
  42627. return this._modelKey;
  42628. },
  42629. enumerable: true,
  42630. configurable: true
  42631. });
  42632. /**
  42633. * Render the model instances
  42634. * @param instanceInfo
  42635. * @param context
  42636. * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
  42637. */
  42638. ModelRenderCache.prototype.render = function (instanceInfo, context) {
  42639. return true;
  42640. };
  42641. ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
  42642. for (var i = 0; i < this._partData.length; i++) {
  42643. if (this._partData[i]._partId === partId) {
  42644. return i;
  42645. }
  42646. }
  42647. return null;
  42648. };
  42649. ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
  42650. var i = this.getPartIndexFromId(partId);
  42651. if (i === null) {
  42652. return null;
  42653. }
  42654. var ci = this._partsClassInfo[i];
  42655. var categories = this._partData[i]._partUsedCategories;
  42656. var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
  42657. return res;
  42658. };
  42659. ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
  42660. var pd = this._partData[partIndex];
  42661. var offset = (pd._partDataStride / 4) * elementCount;
  42662. var pci = this._partsClassInfo[partIndex];
  42663. var self = this;
  42664. pci.fullContent.forEach(function (k, v) {
  42665. if (!v.category || pd._partUsedCategories.indexOf(v.category) !== -1) {
  42666. switch (v.dataType) {
  42667. case 4 /* float */:
  42668. {
  42669. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  42670. effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
  42671. break;
  42672. }
  42673. case 0 /* Vector2 */:
  42674. {
  42675. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  42676. ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
  42677. ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
  42678. effect.setVector2(v.attributeName, ModelRenderCache.v2);
  42679. break;
  42680. }
  42681. case 5 /* Color3 */:
  42682. case 1 /* Vector3 */:
  42683. {
  42684. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  42685. ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
  42686. ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
  42687. ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
  42688. effect.setVector3(v.attributeName, ModelRenderCache.v3);
  42689. break;
  42690. }
  42691. case 6 /* Color4 */:
  42692. case 2 /* Vector4 */:
  42693. {
  42694. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  42695. ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
  42696. ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
  42697. ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
  42698. ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
  42699. effect.setVector4(v.attributeName, ModelRenderCache.v4);
  42700. break;
  42701. }
  42702. default:
  42703. }
  42704. }
  42705. });
  42706. };
  42707. //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
  42708. // let i = this.getPartIndexFromId(partId);
  42709. // if (i === null) {
  42710. // return null;
  42711. // }
  42712. // let pci = this._partsClassInfo[i];
  42713. // pci.fullContent.forEach((k, v) => {
  42714. // if (uniforms.indexOf(v.attributeName) !== -1) {
  42715. // v.uniformLocation = effect.getUniform(v.attributeName);
  42716. // }
  42717. // });
  42718. //}
  42719. ModelRenderCache.v2 = BABYLON.Vector2.Zero();
  42720. ModelRenderCache.v3 = BABYLON.Vector3.Zero();
  42721. ModelRenderCache.v4 = BABYLON.Vector4.Zero();
  42722. return ModelRenderCache;
  42723. })();
  42724. BABYLON.ModelRenderCache = ModelRenderCache;
  42725. var ModelRenderCachePartData = (function () {
  42726. function ModelRenderCachePartData() {
  42727. }
  42728. return ModelRenderCachePartData;
  42729. })();
  42730. BABYLON.ModelRenderCachePartData = ModelRenderCachePartData;
  42731. })(BABYLON || (BABYLON = {}));
  42732. var BABYLON;
  42733. (function (BABYLON) {
  42734. var InstanceClassInfo = (function () {
  42735. function InstanceClassInfo(base) {
  42736. this._baseInfo = base;
  42737. this._nextOffset = new BABYLON.StringDictionary();
  42738. this._attributes = new Array();
  42739. }
  42740. InstanceClassInfo.prototype.mapProperty = function (propInfo, push) {
  42741. var curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
  42742. propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
  42743. //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
  42744. this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
  42745. if (push) {
  42746. this._attributes.push(propInfo);
  42747. }
  42748. };
  42749. InstanceClassInfo.prototype.getInstancingAttributeInfos = function (effect, categories) {
  42750. var catInline = ";" + categories.join(";") + ";";
  42751. var res = new Array();
  42752. var curInfo = this;
  42753. while (curInfo) {
  42754. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  42755. var attrib = _a[_i];
  42756. // 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
  42757. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  42758. var index = effect.getAttributeLocationByName(attrib.attributeName);
  42759. var iai = new BABYLON.InstancingAttributeInfo();
  42760. iai.index = index;
  42761. 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)
  42762. iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
  42763. iai.attributeName = attrib.attributeName;
  42764. res.push(iai);
  42765. }
  42766. }
  42767. curInfo = curInfo._baseInfo;
  42768. }
  42769. return res;
  42770. };
  42771. InstanceClassInfo.prototype.getShaderAttributes = function (categories) {
  42772. var res = new Array();
  42773. var curInfo = this;
  42774. while (curInfo) {
  42775. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  42776. var attrib = _a[_i];
  42777. // 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
  42778. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  42779. res.push(attrib.attributeName);
  42780. }
  42781. }
  42782. curInfo = curInfo._baseInfo;
  42783. }
  42784. return res;
  42785. };
  42786. InstanceClassInfo.prototype._getBaseOffset = function (categories) {
  42787. var curOffset = 0;
  42788. var curBase = this._baseInfo;
  42789. while (curBase) {
  42790. curOffset += curBase._nextOffset.getOrAdd(categories, 0);
  42791. curBase = curBase._baseInfo;
  42792. }
  42793. return curOffset;
  42794. };
  42795. return InstanceClassInfo;
  42796. })();
  42797. BABYLON.InstanceClassInfo = InstanceClassInfo;
  42798. var InstancePropInfo = (function () {
  42799. function InstancePropInfo() {
  42800. this.instanceOffset = new BABYLON.StringDictionary();
  42801. }
  42802. InstancePropInfo.prototype.setSize = function (val) {
  42803. if (val instanceof BABYLON.Vector2) {
  42804. this.size = 8;
  42805. this.dataType = 0 /* Vector2 */;
  42806. return;
  42807. }
  42808. if (val instanceof BABYLON.Vector3) {
  42809. this.size = 12;
  42810. this.dataType = 1 /* Vector3 */;
  42811. return;
  42812. }
  42813. if (val instanceof BABYLON.Vector4) {
  42814. this.size = 16;
  42815. this.dataType = 2 /* Vector4 */;
  42816. return;
  42817. }
  42818. if (val instanceof BABYLON.Matrix) {
  42819. throw new Error("Matrix type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
  42820. }
  42821. if (typeof (val) === "number") {
  42822. this.size = 4;
  42823. this.dataType = 4 /* float */;
  42824. return;
  42825. }
  42826. if (val instanceof BABYLON.Color3) {
  42827. this.size = 12;
  42828. this.dataType = 5 /* Color3 */;
  42829. return;
  42830. }
  42831. if (val instanceof BABYLON.Color4) {
  42832. this.size = 16;
  42833. this.dataType = 6 /* Color4 */;
  42834. return;
  42835. }
  42836. if (val instanceof BABYLON.Size) {
  42837. this.size = 8;
  42838. this.dataType = 7 /* Size */;
  42839. return;
  42840. }
  42841. return;
  42842. };
  42843. InstancePropInfo.prototype.writeData = function (array, offset, val) {
  42844. switch (this.dataType) {
  42845. case 0 /* Vector2 */:
  42846. {
  42847. var v = val;
  42848. array[offset + 0] = v.x;
  42849. array[offset + 1] = v.y;
  42850. break;
  42851. }
  42852. case 1 /* Vector3 */:
  42853. {
  42854. var v = val;
  42855. array[offset + 0] = v.x;
  42856. array[offset + 1] = v.y;
  42857. array[offset + 2] = v.z;
  42858. break;
  42859. }
  42860. case 2 /* Vector4 */:
  42861. {
  42862. var v = val;
  42863. array[offset + 0] = v.x;
  42864. array[offset + 1] = v.y;
  42865. array[offset + 2] = v.z;
  42866. array[offset + 3] = v.w;
  42867. break;
  42868. }
  42869. case 5 /* Color3 */:
  42870. {
  42871. var v = val;
  42872. array[offset + 0] = v.r;
  42873. array[offset + 1] = v.g;
  42874. array[offset + 2] = v.b;
  42875. break;
  42876. }
  42877. case 6 /* Color4 */:
  42878. {
  42879. var v = val;
  42880. array[offset + 0] = v.r;
  42881. array[offset + 1] = v.g;
  42882. array[offset + 2] = v.b;
  42883. array[offset + 3] = v.a;
  42884. break;
  42885. }
  42886. case 4 /* float */:
  42887. {
  42888. var v = val;
  42889. array[offset] = v;
  42890. break;
  42891. }
  42892. case 3 /* Matrix */:
  42893. {
  42894. var v = val;
  42895. for (var i = 0; i < 16; i++) {
  42896. array[offset + i] = v.m[i];
  42897. }
  42898. break;
  42899. }
  42900. case 7 /* Size */:
  42901. {
  42902. var s = val;
  42903. array[offset + 0] = s.width;
  42904. array[offset + 1] = s.height;
  42905. break;
  42906. }
  42907. }
  42908. };
  42909. return InstancePropInfo;
  42910. })();
  42911. BABYLON.InstancePropInfo = InstancePropInfo;
  42912. function instanceData(category, shaderAttributeName) {
  42913. return function (target, propName, descriptor) {
  42914. var dic = BABYLON.ClassTreeInfo.getOrRegister(target, function (base) { return new InstanceClassInfo(base); });
  42915. var node = dic.getLevelOf(target);
  42916. var instanceDataName = propName;
  42917. shaderAttributeName = shaderAttributeName || instanceDataName;
  42918. var info = node.levelContent.get(instanceDataName);
  42919. if (info) {
  42920. throw new Error("The ID " + instanceDataName + " is already taken by another instance data");
  42921. }
  42922. info = new InstancePropInfo();
  42923. info.attributeName = shaderAttributeName;
  42924. info.category = category || null;
  42925. if (info.category) {
  42926. info.delimitedCategory = ";" + info.category + ";";
  42927. }
  42928. node.levelContent.add(instanceDataName, info);
  42929. descriptor.get = function () {
  42930. return null;
  42931. };
  42932. descriptor.set = function (val) {
  42933. // Check that we're not trying to set a property that belongs to a category that is not allowed (current)
  42934. // Quit if it's the case, otherwise we could overwrite data somewhere...
  42935. if (info.category && InstanceClassInfo._CurCategories.indexOf(info.delimitedCategory) === -1) {
  42936. return;
  42937. }
  42938. if (!info.size) {
  42939. info.setSize(val);
  42940. node.classContent.mapProperty(info, true);
  42941. }
  42942. else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
  42943. node.classContent.mapProperty(info, false);
  42944. }
  42945. var obj = this;
  42946. if (obj.dataBuffer && obj.dataElements) {
  42947. var offset = obj.dataElements[obj.curElement].offset + info.instanceOffset.get(InstanceClassInfo._CurCategories);
  42948. info.writeData(obj.dataBuffer.buffer, offset, val);
  42949. }
  42950. };
  42951. };
  42952. }
  42953. BABYLON.instanceData = instanceData;
  42954. var InstanceDataBase = (function () {
  42955. function InstanceDataBase(partId, dataElementCount) {
  42956. this.id = partId;
  42957. this.curElement = 0;
  42958. this._dataElementCount = dataElementCount;
  42959. this.renderMode = 0;
  42960. this.arrayLengthChanged = false;
  42961. }
  42962. Object.defineProperty(InstanceDataBase.prototype, "zBias", {
  42963. get: function () {
  42964. return null;
  42965. },
  42966. enumerable: true,
  42967. configurable: true
  42968. });
  42969. Object.defineProperty(InstanceDataBase.prototype, "transformX", {
  42970. get: function () {
  42971. return null;
  42972. },
  42973. enumerable: true,
  42974. configurable: true
  42975. });
  42976. Object.defineProperty(InstanceDataBase.prototype, "transformY", {
  42977. get: function () {
  42978. return null;
  42979. },
  42980. enumerable: true,
  42981. configurable: true
  42982. });
  42983. Object.defineProperty(InstanceDataBase.prototype, "opacity", {
  42984. get: function () {
  42985. return null;
  42986. },
  42987. enumerable: true,
  42988. configurable: true
  42989. });
  42990. InstanceDataBase.prototype.getClassTreeInfo = function () {
  42991. if (!this.typeInfo) {
  42992. this.typeInfo = BABYLON.ClassTreeInfo.get(Object.getPrototypeOf(this));
  42993. }
  42994. return this.typeInfo;
  42995. };
  42996. InstanceDataBase.prototype.allocElements = function () {
  42997. if (!this.dataBuffer || this.dataElements) {
  42998. return;
  42999. }
  43000. var res = new Array(this.dataElementCount);
  43001. for (var i = 0; i < this.dataElementCount; i++) {
  43002. res[i] = this.dataBuffer.allocElement();
  43003. }
  43004. this.dataElements = res;
  43005. };
  43006. InstanceDataBase.prototype.freeElements = function () {
  43007. if (!this.dataElements) {
  43008. return;
  43009. }
  43010. for (var _i = 0, _a = this.dataElements; _i < _a.length; _i++) {
  43011. var ei = _a[_i];
  43012. this.dataBuffer.freeElement(ei);
  43013. }
  43014. this.dataElements = null;
  43015. };
  43016. Object.defineProperty(InstanceDataBase.prototype, "dataElementCount", {
  43017. get: function () {
  43018. return this._dataElementCount;
  43019. },
  43020. set: function (value) {
  43021. if (value === this._dataElementCount) {
  43022. return;
  43023. }
  43024. this.arrayLengthChanged = true;
  43025. this.freeElements();
  43026. this._dataElementCount = value;
  43027. this.allocElements();
  43028. },
  43029. enumerable: true,
  43030. configurable: true
  43031. });
  43032. __decorate([
  43033. instanceData()
  43034. ], InstanceDataBase.prototype, "zBias", null);
  43035. __decorate([
  43036. instanceData()
  43037. ], InstanceDataBase.prototype, "transformX", null);
  43038. __decorate([
  43039. instanceData()
  43040. ], InstanceDataBase.prototype, "transformY", null);
  43041. __decorate([
  43042. instanceData()
  43043. ], InstanceDataBase.prototype, "opacity", null);
  43044. return InstanceDataBase;
  43045. })();
  43046. BABYLON.InstanceDataBase = InstanceDataBase;
  43047. var RenderablePrim2D = (function (_super) {
  43048. __extends(RenderablePrim2D, _super);
  43049. function RenderablePrim2D(settings) {
  43050. _super.call(this, settings);
  43051. this._transparentPrimitiveInfo = null;
  43052. }
  43053. Object.defineProperty(RenderablePrim2D.prototype, "isAlphaTest", {
  43054. get: function () {
  43055. return this._useTextureAlpha() || this._isPrimAlphaTest();
  43056. },
  43057. enumerable: true,
  43058. configurable: true
  43059. });
  43060. Object.defineProperty(RenderablePrim2D.prototype, "isTransparent", {
  43061. get: function () {
  43062. return (this.actualOpacity < 1) || this._shouldUseAlphaFromTexture() || this._isPrimTransparent();
  43063. },
  43064. enumerable: true,
  43065. configurable: true
  43066. });
  43067. Object.defineProperty(RenderablePrim2D.prototype, "renderMode", {
  43068. get: function () {
  43069. return this._renderMode;
  43070. },
  43071. enumerable: true,
  43072. configurable: true
  43073. });
  43074. /**
  43075. * Dispose the primitive and its resources, remove it from its parent
  43076. */
  43077. RenderablePrim2D.prototype.dispose = function () {
  43078. if (!_super.prototype.dispose.call(this)) {
  43079. return false;
  43080. }
  43081. if (this.renderGroup) {
  43082. this.renderGroup._setCacheGroupDirty();
  43083. }
  43084. if (this._transparentPrimitiveInfo) {
  43085. this.renderGroup._renderableData.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  43086. this._transparentPrimitiveInfo = null;
  43087. }
  43088. if (this._instanceDataParts) {
  43089. this._cleanupInstanceDataParts();
  43090. }
  43091. if (this._modelRenderCache) {
  43092. this._modelRenderCache.dispose();
  43093. this._modelRenderCache = null;
  43094. }
  43095. if (this._instanceDataParts) {
  43096. this._instanceDataParts.forEach(function (p) {
  43097. p.freeElements();
  43098. });
  43099. this._instanceDataParts = null;
  43100. }
  43101. return true;
  43102. };
  43103. RenderablePrim2D.prototype._cleanupInstanceDataParts = function () {
  43104. var gii = null;
  43105. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  43106. var part = _a[_i];
  43107. part.freeElements();
  43108. gii = part.groupInstanceInfo;
  43109. }
  43110. if (gii) {
  43111. var usedCount = 0;
  43112. if (gii.hasOpaqueData) {
  43113. var od = gii.opaqueData[0];
  43114. usedCount += od._partData.usedElementCount;
  43115. gii.opaqueDirty = true;
  43116. }
  43117. if (gii.hasAlphaTestData) {
  43118. var atd = gii.alphaTestData[0];
  43119. usedCount += atd._partData.usedElementCount;
  43120. gii.alphaTestDirty = true;
  43121. }
  43122. if (gii.hasTransparentData) {
  43123. var td = gii.transparentData[0];
  43124. usedCount += td._partData.usedElementCount;
  43125. gii.transparentDirty = true;
  43126. }
  43127. if (usedCount === 0 && gii.modelRenderCache != null) {
  43128. this.renderGroup._renderableData._renderGroupInstancesInfo.remove(gii.modelRenderCache.modelKey);
  43129. gii.dispose();
  43130. }
  43131. if (this._modelRenderCache) {
  43132. this._modelRenderCache.dispose();
  43133. this._modelRenderCache = null;
  43134. }
  43135. }
  43136. this._instanceDataParts = null;
  43137. };
  43138. RenderablePrim2D.prototype._prepareRenderPre = function (context) {
  43139. _super.prototype._prepareRenderPre.call(this, context);
  43140. // If the model changed and we have already an instance, we must remove this instance from the obsolete model
  43141. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty) && this._instanceDataParts) {
  43142. this._cleanupInstanceDataParts();
  43143. }
  43144. // Need to create the model?
  43145. var setupModelRenderCache = false;
  43146. if (!this._modelRenderCache || this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty)) {
  43147. setupModelRenderCache = this._createModelRenderCache();
  43148. }
  43149. var gii = null;
  43150. var newInstance = false;
  43151. // Need to create the instance data parts?
  43152. if (!this._instanceDataParts) {
  43153. // Yes, flag it for later, more processing will have to be done
  43154. newInstance = true;
  43155. gii = this._createModelDataParts();
  43156. }
  43157. // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
  43158. if (setupModelRenderCache) {
  43159. this.setupModelRenderCache(this._modelRenderCache);
  43160. }
  43161. // 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.
  43162. // 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.
  43163. if (this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagNeedRefresh) || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep) || this._mustUpdateInstance()) {
  43164. this._updateInstanceDataParts(gii);
  43165. }
  43166. };
  43167. RenderablePrim2D.prototype._createModelRenderCache = function () {
  43168. var _this = this;
  43169. var setupModelRenderCache = false;
  43170. if (this._modelRenderCache) {
  43171. this._modelRenderCache.dispose();
  43172. }
  43173. this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, function (key) {
  43174. var mrc = _this.createModelRenderCache(key);
  43175. setupModelRenderCache = true;
  43176. return mrc;
  43177. });
  43178. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  43179. // if this is still false it means the MRC already exists, so we add a reference to it
  43180. if (!setupModelRenderCache) {
  43181. this._modelRenderCache.addRef();
  43182. }
  43183. return setupModelRenderCache;
  43184. };
  43185. RenderablePrim2D.prototype._createModelDataParts = function () {
  43186. var _this = this;
  43187. // Create the instance data parts of the primitive and store them
  43188. var parts = this.createInstanceDataParts();
  43189. this._instanceDataParts = parts;
  43190. // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
  43191. if (!this._modelRenderCache._partData) {
  43192. this._setupModelRenderCache(parts);
  43193. }
  43194. // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
  43195. // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
  43196. // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
  43197. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, function (k) {
  43198. var res = new BABYLON.GroupInstanceInfo(_this.renderGroup, _this._modelRenderCache, _this._modelRenderCache._partData.length);
  43199. for (var j = 0; j < _this._modelRenderCache._partData.length; j++) {
  43200. var part = _this._instanceDataParts[j];
  43201. res.partIndexFromId.add(part.id.toString(), j);
  43202. res.usedShaderCategories[j] = ";" + _this.getUsedShaderCategories(part).join(";") + ";";
  43203. res.strides[j] = _this._modelRenderCache._partData[j]._partDataStride;
  43204. }
  43205. return res;
  43206. });
  43207. // Get the GroupInfoDataPart corresponding to the render category of the part
  43208. var rm = 0;
  43209. var gipd = null;
  43210. if (this.isTransparent) {
  43211. gipd = gii.transparentData;
  43212. rm = BABYLON.Render2DContext.RenderModeTransparent;
  43213. }
  43214. else if (this.isAlphaTest) {
  43215. gipd = gii.alphaTestData;
  43216. rm = BABYLON.Render2DContext.RenderModeAlphaTest;
  43217. }
  43218. else {
  43219. gipd = gii.opaqueData;
  43220. rm = BABYLON.Render2DContext.RenderModeOpaque;
  43221. }
  43222. // For each instance data part of the primitive, allocate the instanced element it needs for render
  43223. for (var i = 0; i < parts.length; i++) {
  43224. var part = parts[i];
  43225. part.dataBuffer = gipd[i]._partData;
  43226. part.allocElements();
  43227. part.renderMode = rm;
  43228. part.groupInstanceInfo = gii;
  43229. }
  43230. return gii;
  43231. };
  43232. RenderablePrim2D.prototype._setupModelRenderCache = function (parts) {
  43233. var ctiArray = new Array();
  43234. this._modelRenderCache._partData = new Array();
  43235. for (var _i = 0; _i < parts.length; _i++) {
  43236. var dataPart = parts[_i];
  43237. var pd = new BABYLON.ModelRenderCachePartData();
  43238. this._modelRenderCache._partData.push(pd);
  43239. var cat = this.getUsedShaderCategories(dataPart);
  43240. var cti = dataPart.getClassTreeInfo();
  43241. // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
  43242. var curVisible = this.isVisible;
  43243. this.isVisible = true;
  43244. // 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.
  43245. //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
  43246. var joinCat = ";" + cat.join(";") + ";";
  43247. pd._partJoinedUsedCategories = joinCat;
  43248. InstanceClassInfo._CurCategories = joinCat;
  43249. var obj = this.beforeRefreshForLayoutConstruction(dataPart);
  43250. if (!this.refreshInstanceDataPart(dataPart)) {
  43251. console.log("Layout construction for " + BABYLON.Tools.getClassName(this._instanceDataParts[0]) + " failed because refresh returned false");
  43252. }
  43253. this.afterRefreshForLayoutConstruction(dataPart, obj);
  43254. this.isVisible = curVisible;
  43255. var size = 0;
  43256. cti.fullContent.forEach(function (k, v) {
  43257. if (!v.category || cat.indexOf(v.category) !== -1) {
  43258. if (v.attributeName === "zBias") {
  43259. pd._zBiasOffset = v.instanceOffset.get(joinCat);
  43260. }
  43261. if (!v.size) {
  43262. console.log("ERROR: Couldn't detect the size of the Property " + v.attributeName + " from type " + BABYLON.Tools.getClassName(cti.type) + ". Property is ignored.");
  43263. }
  43264. else {
  43265. size += v.size;
  43266. }
  43267. }
  43268. });
  43269. pd._partDataStride = size;
  43270. pd._partUsedCategories = cat;
  43271. pd._partId = dataPart.id;
  43272. ctiArray.push(cti);
  43273. }
  43274. this._modelRenderCache._partsClassInfo = ctiArray;
  43275. };
  43276. RenderablePrim2D.prototype.onZOrderChanged = function () {
  43277. if (this.isTransparent && this._transparentPrimitiveInfo) {
  43278. this.renderGroup._renderableData.transparentPrimitiveZChanged(this._transparentPrimitiveInfo);
  43279. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
  43280. // Flag the transparentData dirty has will have to sort it again
  43281. gii.transparentOrderDirty = true;
  43282. }
  43283. };
  43284. RenderablePrim2D.prototype._mustUpdateInstance = function () {
  43285. return false;
  43286. };
  43287. RenderablePrim2D.prototype._useTextureAlpha = function () {
  43288. return false;
  43289. };
  43290. RenderablePrim2D.prototype._shouldUseAlphaFromTexture = function () {
  43291. return false;
  43292. };
  43293. RenderablePrim2D.prototype._isPrimAlphaTest = function () {
  43294. return false;
  43295. };
  43296. RenderablePrim2D.prototype._isPrimTransparent = function () {
  43297. return false;
  43298. };
  43299. RenderablePrim2D.prototype._updateInstanceDataParts = function (gii) {
  43300. // Fetch the GroupInstanceInfo if we don't already have it
  43301. var rd = this.renderGroup._renderableData;
  43302. if (!gii) {
  43303. gii = rd._renderGroupInstancesInfo.get(this.modelKey);
  43304. }
  43305. var isTransparent = this.isTransparent;
  43306. var isAlphaTest = this.isAlphaTest;
  43307. var wereTransparent = false;
  43308. // Check a render mode change
  43309. var rmChanged = false;
  43310. if (this._instanceDataParts.length > 0) {
  43311. var firstPart = this._instanceDataParts[0];
  43312. var partRM = firstPart.renderMode;
  43313. var curRM = this.renderMode;
  43314. if (partRM !== curRM) {
  43315. wereTransparent = partRM === BABYLON.Render2DContext.RenderModeTransparent;
  43316. rmChanged = true;
  43317. var gipd;
  43318. switch (curRM) {
  43319. case BABYLON.Render2DContext.RenderModeTransparent:
  43320. gipd = gii.transparentData;
  43321. break;
  43322. case BABYLON.Render2DContext.RenderModeAlphaTest:
  43323. gipd = gii.alphaTestData;
  43324. break;
  43325. default:
  43326. gipd = gii.opaqueData;
  43327. }
  43328. for (var i = 0; i < this._instanceDataParts.length; i++) {
  43329. var part = this._instanceDataParts[i];
  43330. part.freeElements();
  43331. part.dataBuffer = gipd[i]._partData;
  43332. part.renderMode = curRM;
  43333. }
  43334. }
  43335. }
  43336. // Handle changes related to ZOffset
  43337. var visChanged = this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged);
  43338. if (isTransparent || wereTransparent) {
  43339. // Handle visibility change, which is also triggered when the primitive just got created
  43340. if (visChanged || rmChanged) {
  43341. if (this.isVisible && !wereTransparent) {
  43342. if (!this._transparentPrimitiveInfo) {
  43343. // Add the primitive to the list of transparent ones in the group that render is
  43344. this._transparentPrimitiveInfo = rd.addNewTransparentPrimitiveInfo(this, gii);
  43345. }
  43346. }
  43347. else {
  43348. if (this._transparentPrimitiveInfo) {
  43349. rd.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  43350. this._transparentPrimitiveInfo = null;
  43351. }
  43352. }
  43353. gii.transparentOrderDirty = true;
  43354. }
  43355. }
  43356. var rebuildTrans = false;
  43357. // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
  43358. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  43359. var part = _a[_i];
  43360. var justAllocated = false;
  43361. // Check if we need to allocate data elements (hidden prim which becomes visible again)
  43362. if (!part.dataElements && (visChanged || rmChanged || this.isVisible)) {
  43363. part.allocElements();
  43364. justAllocated = true;
  43365. }
  43366. InstanceClassInfo._CurCategories = gii.usedShaderCategories[gii.partIndexFromId.get(part.id.toString())];
  43367. // Will return false if the instance should not be rendered (not visible or other any reasons)
  43368. part.arrayLengthChanged = false;
  43369. if (!this.refreshInstanceDataPart(part)) {
  43370. // Free the data element
  43371. if (part.dataElements) {
  43372. part.freeElements();
  43373. }
  43374. // The refresh couldn't succeed, push the primitive to be dirty again for the next render
  43375. if (this.isVisible) {
  43376. rd._primNewDirtyList.push(this);
  43377. }
  43378. }
  43379. rebuildTrans = rebuildTrans || part.arrayLengthChanged || justAllocated;
  43380. }
  43381. this._instanceDirtyFlags = 0;
  43382. // Make the appropriate data dirty
  43383. if (isTransparent) {
  43384. gii.transparentDirty = true;
  43385. if (rebuildTrans) {
  43386. rd._transparentListChanged = true;
  43387. }
  43388. }
  43389. else if (isAlphaTest) {
  43390. gii.alphaTestDirty = true;
  43391. }
  43392. else {
  43393. gii.opaqueDirty = true;
  43394. }
  43395. this._clearFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged); // Reset the flag as we've handled the case
  43396. };
  43397. RenderablePrim2D.prototype._updateTransparentSegmentIndices = function (ts) {
  43398. var minOff = BABYLON.Prim2DBase._bigInt;
  43399. var maxOff = 0;
  43400. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  43401. var part = _a[_i];
  43402. if (part && part.dataElements) {
  43403. part.dataBuffer.pack();
  43404. for (var _b = 0, _c = part.dataElements; _b < _c.length; _b++) {
  43405. var el = _c[_b];
  43406. minOff = Math.min(minOff, el.offset);
  43407. maxOff = Math.max(maxOff, el.offset);
  43408. }
  43409. ts.startDataIndex = Math.min(ts.startDataIndex, minOff / part.dataBuffer.stride);
  43410. ts.endDataIndex = Math.max(ts.endDataIndex, (maxOff / part.dataBuffer.stride) + 1); // +1 for exclusive
  43411. }
  43412. }
  43413. };
  43414. // This internal method is mainly used for transparency processing
  43415. RenderablePrim2D.prototype._getNextPrimZOrder = function () {
  43416. var length = this._instanceDataParts.length;
  43417. for (var i = 0; i < length; i++) {
  43418. var part = this._instanceDataParts[i];
  43419. if (part) {
  43420. var stride = part.dataBuffer.stride;
  43421. var lastElementOffset = part.dataElements[part.dataElements.length - 1].offset;
  43422. // check if it's the last in the DFA
  43423. if (part.dataBuffer.totalElementCount * stride <= lastElementOffset) {
  43424. return null;
  43425. }
  43426. // Return the Z of the next primitive that lies in the DFA
  43427. return part.dataBuffer[lastElementOffset + stride + this.modelRenderCache._partData[i]._zBiasOffset];
  43428. }
  43429. }
  43430. return null;
  43431. };
  43432. // This internal method is mainly used for transparency processing
  43433. RenderablePrim2D.prototype._getPrevPrimZOrder = function () {
  43434. var length = this._instanceDataParts.length;
  43435. for (var i = 0; i < length; i++) {
  43436. var part = this._instanceDataParts[i];
  43437. if (part) {
  43438. var stride = part.dataBuffer.stride;
  43439. var firstElementOffset = part.dataElements[0].offset;
  43440. // check if it's the first in the DFA
  43441. if (firstElementOffset === 0) {
  43442. return null;
  43443. }
  43444. // Return the Z of the previous primitive that lies in the DFA
  43445. return part.dataBuffer[firstElementOffset - stride + this.modelRenderCache._partData[i]._zBiasOffset];
  43446. }
  43447. }
  43448. return null;
  43449. };
  43450. /**
  43451. * Transform a given point using the Primitive's origin setting.
  43452. * This method requires the Primitive's actualSize to be accurate
  43453. * @param p the point to transform
  43454. * @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.
  43455. * @param res an allocated Vector2 that will receive the transformed content
  43456. */
  43457. RenderablePrim2D.prototype.transformPointWithOriginByRef = function (p, originOffset, res) {
  43458. var actualSize = this.actualSize;
  43459. res.x = p.x - ((this.origin.x + (originOffset ? originOffset.x : 0)) * actualSize.width);
  43460. res.y = p.y - ((this.origin.y + (originOffset ? originOffset.y : 0)) * actualSize.height);
  43461. };
  43462. RenderablePrim2D.prototype.transformPointWithOriginToRef = function (p, originOffset, res) {
  43463. this.transformPointWithOriginByRef(p, originOffset, res);
  43464. return res;
  43465. };
  43466. /**
  43467. * Get the info for a given effect based on the dataPart metadata
  43468. * @param dataPartId partId in part list to get the info
  43469. * @param vertexBufferAttributes vertex buffer attributes to manually add
  43470. * @param uniforms uniforms to manually add
  43471. * @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
  43472. */
  43473. RenderablePrim2D.prototype.getDataPartEffectInfo = function (dataPartId, vertexBufferAttributes, uniforms, useInstanced) {
  43474. if (uniforms === void 0) { uniforms = null; }
  43475. if (useInstanced === void 0) { useInstanced = null; }
  43476. var dataPart = BABYLON.Tools.first(this._instanceDataParts, function (i) { return i.id === dataPartId; });
  43477. if (!dataPart) {
  43478. return null;
  43479. }
  43480. var instancedArray = this.owner.supportInstancedArray;
  43481. if (useInstanced != null) {
  43482. // Check if the caller ask for Instanced Array and the engine does not support it, return null if it's the case
  43483. if (useInstanced && instancedArray === false) {
  43484. return null;
  43485. }
  43486. // Use the caller's setting
  43487. instancedArray = useInstanced;
  43488. }
  43489. var cti = dataPart.getClassTreeInfo();
  43490. var categories = this.getUsedShaderCategories(dataPart);
  43491. var att = cti.classContent.getShaderAttributes(categories);
  43492. var defines = "";
  43493. categories.forEach(function (c) { defines += "#define " + c + "\n"; });
  43494. if (instancedArray) {
  43495. defines += "#define Instanced\n";
  43496. }
  43497. return {
  43498. attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes,
  43499. uniforms: instancedArray ? (uniforms != null ? uniforms : []) : ((uniforms != null) ? att.concat(uniforms) : (att != null ? att : [])),
  43500. defines: defines
  43501. };
  43502. };
  43503. Object.defineProperty(RenderablePrim2D.prototype, "modelRenderCache", {
  43504. get: function () {
  43505. return this._modelRenderCache;
  43506. },
  43507. enumerable: true,
  43508. configurable: true
  43509. });
  43510. RenderablePrim2D.prototype.createModelRenderCache = function (modelKey) {
  43511. return null;
  43512. };
  43513. RenderablePrim2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  43514. };
  43515. RenderablePrim2D.prototype.createInstanceDataParts = function () {
  43516. return null;
  43517. };
  43518. RenderablePrim2D.prototype.getUsedShaderCategories = function (dataPart) {
  43519. return [];
  43520. };
  43521. RenderablePrim2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  43522. };
  43523. RenderablePrim2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  43524. };
  43525. RenderablePrim2D.prototype.applyActualScaleOnTransform = function () {
  43526. return true;
  43527. };
  43528. RenderablePrim2D.prototype.refreshInstanceDataPart = function (part) {
  43529. if (!this.isVisible) {
  43530. return false;
  43531. }
  43532. part.isVisible = this.isVisible;
  43533. // 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)
  43534. if (part.dataElementCount === 1) {
  43535. part.curElement = 0;
  43536. this.updateInstanceDataPart(part);
  43537. }
  43538. return true;
  43539. };
  43540. /**
  43541. * Update the instanceDataBase level properties of a part
  43542. * @param part the part to update
  43543. * @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).
  43544. */
  43545. RenderablePrim2D.prototype.updateInstanceDataPart = function (part, positionOffset) {
  43546. if (positionOffset === void 0) { positionOffset = null; }
  43547. var t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform); // Compute the transformation into the renderGroup's space
  43548. var rgScale = this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? RenderablePrim2D._uV : this.renderGroup.actualScale; // We still need to apply the scale of the renderGroup to our rendering, so get it.
  43549. var size = this.renderGroup.viewportSize;
  43550. var zBias = this.actualZOffset;
  43551. var offX = 0;
  43552. var offY = 0;
  43553. // If there's an offset, apply the global transformation matrix on it to get a global offset
  43554. if (positionOffset) {
  43555. offX = positionOffset.x * t.m[0] + positionOffset.y * t.m[4];
  43556. offY = positionOffset.x * t.m[1] + positionOffset.y * t.m[5];
  43557. }
  43558. // 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
  43559. // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
  43560. // So for X:
  43561. // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
  43562. // - 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].
  43563. // At last we don't forget to apply the actualScale of the Render Group to tx[0] and ty[1] to propagate scaling correctly
  43564. var w = size.width;
  43565. var h = size.height;
  43566. var invZBias = 1 / zBias;
  43567. var tx = new BABYLON.Vector4(t.m[0] * rgScale.x * 2 / w, t.m[4] * 2 / w, 0 /*t.m[8]*/, ((t.m[12] + offX) * rgScale.x * 2 / w) - 1);
  43568. var ty = new BABYLON.Vector4(t.m[1] * 2 / h, t.m[5] * rgScale.y * 2 / h, 0 /*t.m[9]*/, ((t.m[13] + offY) * rgScale.y * 2 / h) - 1);
  43569. if (!this.applyActualScaleOnTransform()) {
  43570. var las = this.actualScale;
  43571. tx.x /= las.x;
  43572. ty.y /= las.y;
  43573. }
  43574. part.transformX = tx;
  43575. part.transformY = ty;
  43576. part.opacity = this.actualOpacity;
  43577. // 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)
  43578. part.zBias = new BABYLON.Vector2(zBias, invZBias);
  43579. };
  43580. RenderablePrim2D.prototype._updateRenderMode = function () {
  43581. if (this.isTransparent) {
  43582. this._renderMode = BABYLON.Render2DContext.RenderModeTransparent;
  43583. }
  43584. else if (this.isAlphaTest) {
  43585. this._renderMode = BABYLON.Render2DContext.RenderModeAlphaTest;
  43586. }
  43587. else {
  43588. this._renderMode = BABYLON.Render2DContext.RenderModeOpaque;
  43589. }
  43590. };
  43591. RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  43592. RenderablePrim2D._uV = new BABYLON.Vector2(1, 1);
  43593. __decorate([
  43594. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 0, function (pi) { return RenderablePrim2D.isAlphaTestProperty = pi; })
  43595. ], RenderablePrim2D.prototype, "isAlphaTest", null);
  43596. __decorate([
  43597. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return RenderablePrim2D.isTransparentProperty = pi; })
  43598. ], RenderablePrim2D.prototype, "isTransparent", null);
  43599. RenderablePrim2D = __decorate([
  43600. BABYLON.className("RenderablePrim2D")
  43601. ], RenderablePrim2D);
  43602. return RenderablePrim2D;
  43603. })(BABYLON.Prim2DBase);
  43604. BABYLON.RenderablePrim2D = RenderablePrim2D;
  43605. })(BABYLON || (BABYLON = {}));
  43606. var BABYLON;
  43607. (function (BABYLON) {
  43608. var Shape2D = (function (_super) {
  43609. __extends(Shape2D, _super);
  43610. function Shape2D(settings) {
  43611. _super.call(this, settings);
  43612. if (!settings) {
  43613. settings = {};
  43614. }
  43615. var borderBrush = null;
  43616. if (settings.border) {
  43617. if (typeof (settings.border) === "string") {
  43618. borderBrush = BABYLON.Canvas2D.GetBrushFromString(settings.border);
  43619. }
  43620. else {
  43621. borderBrush = settings.border;
  43622. }
  43623. }
  43624. var fillBrush = null;
  43625. if (settings.fill) {
  43626. if (typeof (settings.fill) === "string") {
  43627. fillBrush = BABYLON.Canvas2D.GetBrushFromString(settings.fill);
  43628. }
  43629. else {
  43630. fillBrush = settings.fill;
  43631. }
  43632. }
  43633. this._isTransparent = false;
  43634. this._oldTransparent = false;
  43635. this.border = borderBrush;
  43636. this.fill = fillBrush;
  43637. this._updateTransparencyStatus();
  43638. this.borderThickness = settings.borderThickness;
  43639. }
  43640. Object.defineProperty(Shape2D.prototype, "border", {
  43641. get: function () {
  43642. return this._border;
  43643. },
  43644. set: function (value) {
  43645. this._border = value;
  43646. this._updateTransparencyStatus();
  43647. },
  43648. enumerable: true,
  43649. configurable: true
  43650. });
  43651. Object.defineProperty(Shape2D.prototype, "fill", {
  43652. /**
  43653. * Get/set the brush to render the Fill part of the Primitive
  43654. */
  43655. get: function () {
  43656. return this._fill;
  43657. },
  43658. set: function (value) {
  43659. this._fill = value;
  43660. this._updateTransparencyStatus();
  43661. },
  43662. enumerable: true,
  43663. configurable: true
  43664. });
  43665. Object.defineProperty(Shape2D.prototype, "borderThickness", {
  43666. get: function () {
  43667. return this._borderThickness;
  43668. },
  43669. set: function (value) {
  43670. this._borderThickness = value;
  43671. },
  43672. enumerable: true,
  43673. configurable: true
  43674. });
  43675. Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
  43676. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  43677. // Fill Part
  43678. if (dataPart.id === Shape2D.SHAPE2D_FILLPARTID) {
  43679. var fill = this.fill;
  43680. if (fill instanceof BABYLON.SolidColorBrush2D) {
  43681. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLSOLID);
  43682. }
  43683. if (fill instanceof BABYLON.GradientColorBrush2D) {
  43684. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT);
  43685. }
  43686. }
  43687. // Border Part
  43688. if (dataPart.id === Shape2D.SHAPE2D_BORDERPARTID) {
  43689. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDER);
  43690. var border = this.border;
  43691. if (border instanceof BABYLON.SolidColorBrush2D) {
  43692. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID);
  43693. }
  43694. if (border instanceof BABYLON.GradientColorBrush2D) {
  43695. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT);
  43696. }
  43697. }
  43698. return cat;
  43699. };
  43700. Shape2D.prototype.applyActualScaleOnTransform = function () {
  43701. return false;
  43702. };
  43703. Shape2D.prototype.refreshInstanceDataPart = function (part) {
  43704. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  43705. return false;
  43706. }
  43707. // Fill Part
  43708. if (part.id === Shape2D.SHAPE2D_FILLPARTID) {
  43709. var d = part;
  43710. if (this.fill) {
  43711. var fill = this.fill;
  43712. if (fill instanceof BABYLON.SolidColorBrush2D) {
  43713. d.fillSolidColor = fill.color;
  43714. }
  43715. else if (fill instanceof BABYLON.GradientColorBrush2D) {
  43716. d.fillGradientColor1 = fill.color1;
  43717. d.fillGradientColor2 = fill.color2;
  43718. 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));
  43719. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  43720. d.fillGradientTY = ty;
  43721. }
  43722. }
  43723. }
  43724. else if (part.id === Shape2D.SHAPE2D_BORDERPARTID) {
  43725. var d = part;
  43726. if (this.border) {
  43727. d.borderThickness = this.borderThickness;
  43728. var border = this.border;
  43729. if (border instanceof BABYLON.SolidColorBrush2D) {
  43730. d.borderSolidColor = border.color;
  43731. }
  43732. else if (border instanceof BABYLON.GradientColorBrush2D) {
  43733. d.borderGradientColor1 = border.color1;
  43734. d.borderGradientColor2 = border.color2;
  43735. 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));
  43736. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  43737. d.borderGradientTY = ty;
  43738. }
  43739. }
  43740. }
  43741. return true;
  43742. };
  43743. Shape2D.prototype._updateTransparencyStatus = function () {
  43744. this._isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent()) || (this.actualOpacity < 1);
  43745. if (this._isTransparent !== this._oldTransparent) {
  43746. this._oldTransparent = this._isTransparent;
  43747. this._updateRenderMode();
  43748. }
  43749. };
  43750. Shape2D.prototype._mustUpdateInstance = function () {
  43751. var res = this._oldTransparent !== this._isTransparent;
  43752. if (res) {
  43753. this._updateRenderMode();
  43754. this._oldTransparent = this._isTransparent;
  43755. }
  43756. return res;
  43757. };
  43758. Shape2D.prototype._isPrimTransparent = function () {
  43759. return this._isTransparent;
  43760. };
  43761. Shape2D.SHAPE2D_BORDERPARTID = 1;
  43762. Shape2D.SHAPE2D_FILLPARTID = 2;
  43763. Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
  43764. Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
  43765. Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
  43766. Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
  43767. Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
  43768. Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
  43769. __decorate([
  43770. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D.borderProperty = pi; }, true)
  43771. ], Shape2D.prototype, "border", null);
  43772. __decorate([
  43773. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D.fillProperty = pi; }, true)
  43774. ], Shape2D.prototype, "fill", null);
  43775. __decorate([
  43776. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D.borderThicknessProperty = pi; })
  43777. ], Shape2D.prototype, "borderThickness", null);
  43778. Shape2D = __decorate([
  43779. BABYLON.className("Shape2D")
  43780. ], Shape2D);
  43781. return Shape2D;
  43782. })(BABYLON.RenderablePrim2D);
  43783. BABYLON.Shape2D = Shape2D;
  43784. var Shape2DInstanceData = (function (_super) {
  43785. __extends(Shape2DInstanceData, _super);
  43786. function Shape2DInstanceData() {
  43787. _super.apply(this, arguments);
  43788. }
  43789. Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
  43790. // FILL ATTRIBUTES
  43791. get: function () {
  43792. return null;
  43793. },
  43794. enumerable: true,
  43795. configurable: true
  43796. });
  43797. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
  43798. get: function () {
  43799. return null;
  43800. },
  43801. enumerable: true,
  43802. configurable: true
  43803. });
  43804. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
  43805. get: function () {
  43806. return null;
  43807. },
  43808. enumerable: true,
  43809. configurable: true
  43810. });
  43811. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
  43812. get: function () {
  43813. return null;
  43814. },
  43815. enumerable: true,
  43816. configurable: true
  43817. });
  43818. Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
  43819. // BORDER ATTRIBUTES
  43820. get: function () {
  43821. return null;
  43822. },
  43823. enumerable: true,
  43824. configurable: true
  43825. });
  43826. Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
  43827. get: function () {
  43828. return null;
  43829. },
  43830. enumerable: true,
  43831. configurable: true
  43832. });
  43833. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
  43834. get: function () {
  43835. return null;
  43836. },
  43837. enumerable: true,
  43838. configurable: true
  43839. });
  43840. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
  43841. get: function () {
  43842. return null;
  43843. },
  43844. enumerable: true,
  43845. configurable: true
  43846. });
  43847. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
  43848. get: function () {
  43849. return null;
  43850. },
  43851. enumerable: true,
  43852. configurable: true
  43853. });
  43854. __decorate([
  43855. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
  43856. ], Shape2DInstanceData.prototype, "fillSolidColor", null);
  43857. __decorate([
  43858. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  43859. ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
  43860. __decorate([
  43861. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  43862. ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
  43863. __decorate([
  43864. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  43865. ], Shape2DInstanceData.prototype, "fillGradientTY", null);
  43866. __decorate([
  43867. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
  43868. ], Shape2DInstanceData.prototype, "borderThickness", null);
  43869. __decorate([
  43870. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
  43871. ], Shape2DInstanceData.prototype, "borderSolidColor", null);
  43872. __decorate([
  43873. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  43874. ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
  43875. __decorate([
  43876. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  43877. ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
  43878. __decorate([
  43879. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  43880. ], Shape2DInstanceData.prototype, "borderGradientTY", null);
  43881. return Shape2DInstanceData;
  43882. })(BABYLON.InstanceDataBase);
  43883. BABYLON.Shape2DInstanceData = Shape2DInstanceData;
  43884. })(BABYLON || (BABYLON = {}));
  43885. var BABYLON;
  43886. (function (BABYLON) {
  43887. var Group2D = (function (_super) {
  43888. __extends(Group2D, _super);
  43889. /**
  43890. * Create an Logical or Renderable Group.
  43891. * @param settings a combination of settings, possible ones are
  43892. * - 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)
  43893. * - children: an array of direct children
  43894. * - id a text identifier, for information purpose
  43895. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  43896. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  43897. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  43898. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  43899. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  43900. * - zOrder: override the zOrder with the specified value
  43901. * - origin: define the normalized origin point location, default [0.5;0.5]
  43902. * - 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.
  43903. * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY
  43904. * - 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).
  43905. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  43906. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  43907. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  43908. * - 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!
  43909. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43910. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43911. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43912. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43913. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  43914. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  43915. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  43916. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  43917. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43918. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43919. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43920. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43921. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  43922. */
  43923. function Group2D(settings) {
  43924. if (settings == null) {
  43925. settings = {};
  43926. }
  43927. if (settings.origin == null) {
  43928. settings.origin = new BABYLON.Vector2(0, 0);
  43929. }
  43930. _super.call(this, settings);
  43931. var size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new BABYLON.Size(settings.width || 0, settings.height || 0)));
  43932. this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode;
  43933. if (this._trackedNode && this.owner) {
  43934. this.owner._registerTrackedNode(this);
  43935. }
  43936. this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior;
  43937. var rd = this._renderableData;
  43938. if (rd) {
  43939. rd._noResizeOnScale = (this.cacheBehavior & Group2D.GROUPCACHEBEHAVIOR_NORESIZEONSCALE) !== 0;
  43940. }
  43941. this.size = size;
  43942. this._viewportPosition = BABYLON.Vector2.Zero();
  43943. this._viewportSize = BABYLON.Size.Zero();
  43944. }
  43945. Group2D._createCachedCanvasGroup = function (owner) {
  43946. var g = new Group2D({ parent: owner, id: "__cachedCanvasGroup__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), size: null, isVisible: true, isPickable: false, dontInheritParentScale: true });
  43947. return g;
  43948. };
  43949. Group2D.prototype.applyCachedTexture = function (vertexData, material) {
  43950. this._bindCacheTarget();
  43951. if (vertexData) {
  43952. var uv = vertexData.uvs;
  43953. var nodeuv = this._renderableData._cacheNodeUVs;
  43954. for (var i = 0; i < 4; i++) {
  43955. uv[i * 2 + 0] = nodeuv[i].x;
  43956. uv[i * 2 + 1] = nodeuv[i].y;
  43957. }
  43958. }
  43959. if (material) {
  43960. material.diffuseTexture = this._renderableData._cacheTexture;
  43961. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  43962. }
  43963. this._renderableData._cacheTexture.hasAlpha = true;
  43964. this._unbindCacheTarget();
  43965. };
  43966. Object.defineProperty(Group2D.prototype, "cachedRect", {
  43967. /**
  43968. * Allow you to access the information regarding the cached rectangle of the Group2D into the MapTexture.
  43969. * 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.
  43970. */
  43971. get: function () {
  43972. if (!this._renderableData) {
  43973. return null;
  43974. }
  43975. return this._renderableData._cacheNode;
  43976. },
  43977. enumerable: true,
  43978. configurable: true
  43979. });
  43980. Object.defineProperty(Group2D.prototype, "cachedUVs", {
  43981. /**
  43982. * The UVs into the MapTexture that map the cached group
  43983. */
  43984. get: function () {
  43985. if (!this._renderableData) {
  43986. return null;
  43987. }
  43988. return this._renderableData._cacheNodeUVs;
  43989. },
  43990. enumerable: true,
  43991. configurable: true
  43992. });
  43993. Object.defineProperty(Group2D.prototype, "cachedUVsChanged", {
  43994. get: function () {
  43995. if (!this._renderableData) {
  43996. return null;
  43997. }
  43998. if (!this._renderableData._cacheNodeUVsChangedObservable) {
  43999. this._renderableData._cacheNodeUVsChangedObservable = new BABYLON.Observable();
  44000. }
  44001. return this._renderableData._cacheNodeUVsChangedObservable;
  44002. },
  44003. enumerable: true,
  44004. configurable: true
  44005. });
  44006. Object.defineProperty(Group2D.prototype, "cacheTexture", {
  44007. /**
  44008. * Access the texture that maintains a cached version of the Group2D.
  44009. * This is useful only if you're not using a WorldSpaceNode for your WorldSpace Canvas and therefore need to perform the rendering yourself.
  44010. */
  44011. get: function () {
  44012. if (!this._renderableData) {
  44013. return null;
  44014. }
  44015. return this._renderableData._cacheTexture;
  44016. },
  44017. enumerable: true,
  44018. configurable: true
  44019. });
  44020. /**
  44021. * Call this method to remove this Group and its children from the Canvas
  44022. */
  44023. Group2D.prototype.dispose = function () {
  44024. if (!_super.prototype.dispose.call(this)) {
  44025. return false;
  44026. }
  44027. if (this._trackedNode != null) {
  44028. this.owner._unregisterTrackedNode(this);
  44029. this._trackedNode = null;
  44030. }
  44031. if (this._renderableData) {
  44032. this._renderableData.dispose(this.owner);
  44033. this._renderableData = null;
  44034. }
  44035. return true;
  44036. };
  44037. Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
  44038. /**
  44039. * @returns Returns true if the Group render content, false if it's a logical group only
  44040. */
  44041. get: function () {
  44042. return this._isRenderableGroup;
  44043. },
  44044. enumerable: true,
  44045. configurable: true
  44046. });
  44047. Object.defineProperty(Group2D.prototype, "isCachedGroup", {
  44048. /**
  44049. * @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
  44050. */
  44051. get: function () {
  44052. return this._isCachedGroup;
  44053. },
  44054. enumerable: true,
  44055. configurable: true
  44056. });
  44057. Object.defineProperty(Group2D.prototype, "size", {
  44058. get: function () {
  44059. return this._size;
  44060. },
  44061. /**
  44062. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  44063. * 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.
  44064. */
  44065. set: function (val) {
  44066. this._size = val;
  44067. },
  44068. enumerable: true,
  44069. configurable: true
  44070. });
  44071. Object.defineProperty(Group2D.prototype, "viewportSize", {
  44072. get: function () {
  44073. return this._viewportSize;
  44074. },
  44075. enumerable: true,
  44076. configurable: true
  44077. });
  44078. Object.defineProperty(Group2D.prototype, "actualSize", {
  44079. get: function () {
  44080. // The computed size will be floor on both width and height
  44081. var actualSize;
  44082. // Return the actualSize if set
  44083. if (this._actualSize) {
  44084. return this._actualSize;
  44085. }
  44086. // Return the size if set by the user
  44087. if (this._size) {
  44088. actualSize = new BABYLON.Size(Math.ceil(this._size.width), Math.ceil(this._size.height));
  44089. }
  44090. else {
  44091. var m = this.layoutBoundingInfo.max();
  44092. actualSize = new BABYLON.Size(Math.ceil(m.x), Math.ceil(m.y));
  44093. }
  44094. // 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)
  44095. if (!actualSize.equals(this._actualSize)) {
  44096. this.onPrimitivePropertyDirty(Group2D.actualSizeProperty.flagId);
  44097. this._actualSize = actualSize;
  44098. this.handleGroupChanged(Group2D.actualSizeProperty);
  44099. }
  44100. return actualSize;
  44101. },
  44102. set: function (value) {
  44103. this._actualSize = value;
  44104. },
  44105. enumerable: true,
  44106. configurable: true
  44107. });
  44108. Object.defineProperty(Group2D.prototype, "cacheBehavior", {
  44109. /**
  44110. * 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.
  44111. * GROUPCACHEBEHAVIOR_NORESIZEONSCALE can also be set if you set it at creation time.
  44112. * 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.
  44113. */
  44114. get: function () {
  44115. return this._cacheBehavior;
  44116. },
  44117. enumerable: true,
  44118. configurable: true
  44119. });
  44120. Group2D.prototype._addPrimToDirtyList = function (prim) {
  44121. this._renderableData._primDirtyList.push(prim);
  44122. };
  44123. Group2D.prototype._renderCachedCanvas = function () {
  44124. this.owner._addGroupRenderCount(1);
  44125. this.updateCachedStates(true);
  44126. var context = new BABYLON.PrepareRender2DContext();
  44127. this._prepareGroupRender(context);
  44128. this._groupRender();
  44129. };
  44130. Object.defineProperty(Group2D.prototype, "trackedNode", {
  44131. /**
  44132. * Get/set the Scene's Node that should be tracked, the group's position will follow the projected position of the Node.
  44133. */
  44134. get: function () {
  44135. return this._trackedNode;
  44136. },
  44137. set: function (val) {
  44138. if (val != null) {
  44139. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  44140. this.owner._registerTrackedNode(this);
  44141. }
  44142. this._trackedNode = val;
  44143. }
  44144. else {
  44145. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  44146. this.owner._unregisterTrackedNode(this);
  44147. }
  44148. this._trackedNode = null;
  44149. }
  44150. },
  44151. enumerable: true,
  44152. configurable: true
  44153. });
  44154. Group2D.prototype.levelIntersect = function (intersectInfo) {
  44155. // 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
  44156. return true;
  44157. };
  44158. Group2D.prototype.updateLevelBoundingInfo = function () {
  44159. var size;
  44160. // If the size is set by the user, the boundingInfo is computed from this value
  44161. if (this.size) {
  44162. size = this.size;
  44163. }
  44164. else {
  44165. size = new BABYLON.Size(0, 0);
  44166. }
  44167. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  44168. };
  44169. // Method called only on renderable groups to prepare the rendering
  44170. Group2D.prototype._prepareGroupRender = function (context) {
  44171. var sortedDirtyList = null;
  44172. // Update the Global Transformation and visibility status of the changed primitives
  44173. var rd = this._renderableData;
  44174. if ((rd._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  44175. sortedDirtyList = rd._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  44176. this.updateCachedStatesOf(sortedDirtyList, true);
  44177. }
  44178. var s = this.actualSize;
  44179. var a = this.actualScale;
  44180. var sw = Math.ceil(s.width * a.x);
  44181. var sh = Math.ceil(s.height * a.y);
  44182. // The dimension must be overridden when using the designSize feature, the ratio is maintain to compute a uniform scale, which is mandatory but if the designSize's ratio is different from the rendering surface's ratio, content will be clipped in some cases.
  44183. // So we set the width/height to the rendering's one because that's what we want for the viewport!
  44184. if (this instanceof BABYLON.Canvas2D) {
  44185. var c = this;
  44186. if (c.designSize != null) {
  44187. sw = this.owner.engine.getRenderWidth();
  44188. sh = this.owner.engine.getRenderHeight();
  44189. }
  44190. }
  44191. // Setup the size of the rendering viewport
  44192. // 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
  44193. if (!this._isCachedGroup) {
  44194. // Compute the WebGL viewport's location/size
  44195. var t = this._globalTransform.getTranslation();
  44196. var rs = this.owner._renderingSize;
  44197. sh = Math.min(sh, rs.height - t.y);
  44198. sw = Math.min(sw, rs.width - t.x);
  44199. var x = t.x;
  44200. var y = t.y;
  44201. // 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
  44202. this._viewportPosition.x = x;
  44203. this._viewportPosition.y = y;
  44204. }
  44205. // For a cachedGroup we also check of the group's actualSize is changing, if it's the case then the rendering zone will be change so we also have to dirty all primitives to prepare them again.
  44206. if (this._viewportSize.width !== sw || this._viewportSize.height !== sh) {
  44207. context.forceRefreshPrimitive = true;
  44208. this._viewportSize.width = sw;
  44209. this._viewportSize.height = sh;
  44210. }
  44211. if ((rd._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  44212. // If the group is cached, set the dirty flag to true because of the incoming changes
  44213. this._cacheGroupDirty = this._isCachedGroup;
  44214. rd._primNewDirtyList.splice(0);
  44215. // If it's a force refresh, prepare all the children
  44216. if (context.forceRefreshPrimitive) {
  44217. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  44218. var p = _a[_i];
  44219. p._prepareRender(context);
  44220. }
  44221. }
  44222. else {
  44223. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  44224. // the hierarchyDepth in order to prepare primitives from top to bottom
  44225. if (!sortedDirtyList) {
  44226. sortedDirtyList = rd._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  44227. }
  44228. sortedDirtyList.forEach(function (p) {
  44229. // 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.
  44230. // 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.
  44231. if (!p.isDisposed && p._needPrepare()) {
  44232. p._prepareRender(context);
  44233. }
  44234. });
  44235. }
  44236. // Everything is updated, clear the dirty list
  44237. rd._primDirtyList.forEach(function (p) {
  44238. if (rd._primNewDirtyList.indexOf(p) === -1) {
  44239. p._resetPropertiesDirty();
  44240. }
  44241. else {
  44242. p._setFlags(BABYLON.SmartPropertyPrim.flagNeedRefresh);
  44243. }
  44244. });
  44245. rd._primDirtyList.splice(0);
  44246. rd._primDirtyList = rd._primDirtyList.concat(rd._primNewDirtyList);
  44247. }
  44248. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  44249. rd._childrenRenderableGroups.forEach(function (g) {
  44250. g._prepareGroupRender(context);
  44251. });
  44252. };
  44253. Group2D.prototype._groupRender = function () {
  44254. var _this = this;
  44255. var engine = this.owner.engine;
  44256. var failedCount = 0;
  44257. // First recurse to children render group to render them (in their cache or on screen)
  44258. for (var _i = 0, _a = this._renderableData._childrenRenderableGroups; _i < _a.length; _i++) {
  44259. var childGroup = _a[_i];
  44260. childGroup._groupRender();
  44261. }
  44262. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  44263. if (!this.isCachedGroup || this._cacheGroupDirty) {
  44264. this.owner._addGroupRenderCount(1);
  44265. if (this.isCachedGroup) {
  44266. this._bindCacheTarget();
  44267. }
  44268. else {
  44269. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  44270. }
  44271. var curAlphaTest = engine.getAlphaTesting() === true;
  44272. var curDepthWrite = engine.getDepthWrite() === true;
  44273. // ===================================================================
  44274. // First pass, update the InstancedArray and render Opaque primitives
  44275. // Disable Alpha Testing, Enable Depth Write
  44276. engine.setAlphaTesting(false);
  44277. engine.setDepthWrite(true);
  44278. // For each different model of primitive to render
  44279. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeOpaque);
  44280. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  44281. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  44282. var renderCount = _this._prepareContext(engine, context, v);
  44283. // If null is returned, there's no opaque data to render
  44284. if (renderCount === null) {
  44285. return;
  44286. }
  44287. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  44288. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  44289. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  44290. var renderFailed = !v.modelRenderCache.render(v, context);
  44291. // Update dirty flag/related
  44292. v.opaqueDirty = renderFailed;
  44293. failedCount += renderFailed ? 1 : 0;
  44294. }
  44295. });
  44296. // =======================================================================
  44297. // Second pass, update the InstancedArray and render AlphaTest primitives
  44298. // Enable Alpha Testing, Enable Depth Write
  44299. engine.setAlphaTesting(true);
  44300. engine.setDepthWrite(true);
  44301. // For each different model of primitive to render
  44302. context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeAlphaTest);
  44303. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  44304. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  44305. var renderCount = _this._prepareContext(engine, context, v);
  44306. // If null is returned, there's no opaque data to render
  44307. if (renderCount === null) {
  44308. return;
  44309. }
  44310. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  44311. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  44312. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  44313. var renderFailed = !v.modelRenderCache.render(v, context);
  44314. // Update dirty flag/related
  44315. v.opaqueDirty = renderFailed;
  44316. failedCount += renderFailed ? 1 : 0;
  44317. }
  44318. });
  44319. // =======================================================================
  44320. // Third pass, transparent primitive rendering
  44321. // Enable Alpha Testing, Disable Depth Write
  44322. engine.setAlphaTesting(true);
  44323. engine.setDepthWrite(false);
  44324. // First Check if the transparent List change so we can update the TransparentSegment and PartData (sort if needed)
  44325. if (this._renderableData._transparentListChanged) {
  44326. this._updateTransparentData();
  44327. }
  44328. // From this point on we have up to date data to render, so let's go
  44329. failedCount += this._renderTransparentData();
  44330. // =======================================================================
  44331. // Unbind target/restore viewport setting, clear dirty flag, and quit
  44332. // The group's content is no longer dirty
  44333. this._cacheGroupDirty = failedCount !== 0;
  44334. if (this.isCachedGroup) {
  44335. this._unbindCacheTarget();
  44336. }
  44337. else {
  44338. if (curVP) {
  44339. engine.setViewport(curVP);
  44340. }
  44341. }
  44342. // Restore saved states
  44343. engine.setAlphaTesting(curAlphaTest);
  44344. engine.setDepthWrite(curDepthWrite);
  44345. }
  44346. };
  44347. Group2D.prototype._setCacheGroupDirty = function () {
  44348. this._cacheGroupDirty = true;
  44349. };
  44350. Group2D.prototype._updateTransparentData = function () {
  44351. this.owner._addUpdateTransparentDataCount(1);
  44352. var rd = this._renderableData;
  44353. // Sort all the primitive from their depth, max (bottom) to min (top)
  44354. rd._transparentPrimitives.sort(function (a, b) { return b._primitive.actualZOffset - a._primitive.actualZOffset; });
  44355. var checkAndAddPrimInSegment = function (seg, tpiI) {
  44356. var tpi = rd._transparentPrimitives[tpiI];
  44357. // Fast rejection: if gii are different
  44358. if (seg.groupInsanceInfo !== tpi._groupInstanceInfo) {
  44359. return false;
  44360. }
  44361. //let tpiZ = tpi._primitive.actualZOffset;
  44362. // We've made it so far, the tpi can be part of the segment, add it
  44363. tpi._transparentSegment = seg;
  44364. tpi._primitive._updateTransparentSegmentIndices(seg);
  44365. return true;
  44366. };
  44367. // Free the existing TransparentSegments
  44368. for (var _i = 0, _a = rd._transparentSegments; _i < _a.length; _i++) {
  44369. var ts = _a[_i];
  44370. ts.dispose(this.owner.engine);
  44371. }
  44372. rd._transparentSegments.splice(0);
  44373. var prevSeg = null;
  44374. for (var tpiI = 0; tpiI < rd._transparentPrimitives.length; tpiI++) {
  44375. var tpi = rd._transparentPrimitives[tpiI];
  44376. // Check if the Data in which the primitive is stored is not sorted properly
  44377. if (tpi._groupInstanceInfo.transparentOrderDirty) {
  44378. tpi._groupInstanceInfo.sortTransparentData();
  44379. }
  44380. // Reset the segment, we have to create/rebuild it
  44381. tpi._transparentSegment = null;
  44382. // If there's a previous valid segment, check if this prim can be part of it
  44383. if (prevSeg) {
  44384. checkAndAddPrimInSegment(prevSeg, tpiI);
  44385. }
  44386. // If we couldn't insert in the adjacent segments, he have to create one
  44387. if (!tpi._transparentSegment) {
  44388. var ts = new BABYLON.TransparentSegment();
  44389. ts.groupInsanceInfo = tpi._groupInstanceInfo;
  44390. var prim = tpi._primitive;
  44391. ts.startZ = prim.actualZOffset;
  44392. prim._updateTransparentSegmentIndices(ts);
  44393. ts.endZ = ts.startZ;
  44394. tpi._transparentSegment = ts;
  44395. rd._transparentSegments.push(ts);
  44396. }
  44397. // Update prevSeg
  44398. prevSeg = tpi._transparentSegment;
  44399. }
  44400. //rd._firstChangedPrim = null;
  44401. rd._transparentListChanged = false;
  44402. };
  44403. Group2D.prototype._renderTransparentData = function () {
  44404. var failedCount = 0;
  44405. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeTransparent);
  44406. var rd = this._renderableData;
  44407. var useInstanced = this.owner.supportInstancedArray;
  44408. var length = rd._transparentSegments.length;
  44409. for (var i = 0; i < length; i++) {
  44410. context.instancedBuffers = null;
  44411. var ts = rd._transparentSegments[i];
  44412. var gii = ts.groupInsanceInfo;
  44413. var mrc = gii.modelRenderCache;
  44414. var engine = this.owner.engine;
  44415. var count = ts.endDataIndex - ts.startDataIndex;
  44416. // Use Instanced Array if it's supported and if there's at least 5 prims to draw.
  44417. // We don't want to create an Instanced Buffer for less that 5 prims
  44418. if (useInstanced && count >= 5) {
  44419. if (!ts.partBuffers) {
  44420. var buffers = new Array();
  44421. for (var j = 0; j < gii.transparentData.length; j++) {
  44422. var gitd = gii.transparentData[j];
  44423. var dfa = gitd._partData;
  44424. var data = dfa.pack();
  44425. var stride = dfa.stride;
  44426. var neededSize = count * stride * 4;
  44427. var buffer = engine.createInstancesBuffer(neededSize); // Create + bind
  44428. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  44429. engine.updateArrayBuffer(segData);
  44430. buffers.push(buffer);
  44431. }
  44432. ts.partBuffers = buffers;
  44433. }
  44434. else if (gii.transparentDirty) {
  44435. for (var j = 0; j < gii.transparentData.length; j++) {
  44436. var gitd = gii.transparentData[j];
  44437. var dfa = gitd._partData;
  44438. var data = dfa.pack();
  44439. var stride = dfa.stride;
  44440. var buffer = ts.partBuffers[j];
  44441. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  44442. engine.bindArrayBuffer(buffer);
  44443. engine.updateArrayBuffer(segData);
  44444. }
  44445. }
  44446. context.useInstancing = true;
  44447. context.instancesCount = count;
  44448. context.instancedBuffers = ts.partBuffers;
  44449. context.groupInfoPartData = gii.transparentData;
  44450. var renderFailed = !mrc.render(gii, context);
  44451. failedCount += renderFailed ? 1 : 0;
  44452. }
  44453. else {
  44454. context.useInstancing = false;
  44455. context.partDataStartIndex = ts.startDataIndex;
  44456. context.partDataEndIndex = ts.endDataIndex;
  44457. context.groupInfoPartData = gii.transparentData;
  44458. var renderFailed = !mrc.render(gii, context);
  44459. failedCount += renderFailed ? 1 : 0;
  44460. }
  44461. }
  44462. return failedCount;
  44463. };
  44464. Group2D.prototype._prepareContext = function (engine, context, gii) {
  44465. var gipd = null;
  44466. var setDirty;
  44467. var getDirty;
  44468. // Render Mode specifics
  44469. switch (context.renderMode) {
  44470. case BABYLON.Render2DContext.RenderModeOpaque:
  44471. {
  44472. if (!gii.hasOpaqueData) {
  44473. return null;
  44474. }
  44475. setDirty = function (dirty) { gii.opaqueDirty = dirty; };
  44476. getDirty = function () { return gii.opaqueDirty; };
  44477. context.groupInfoPartData = gii.opaqueData;
  44478. gipd = gii.opaqueData;
  44479. break;
  44480. }
  44481. case BABYLON.Render2DContext.RenderModeAlphaTest:
  44482. {
  44483. if (!gii.hasAlphaTestData) {
  44484. return null;
  44485. }
  44486. setDirty = function (dirty) { gii.alphaTestDirty = dirty; };
  44487. getDirty = function () { return gii.alphaTestDirty; };
  44488. context.groupInfoPartData = gii.alphaTestData;
  44489. gipd = gii.alphaTestData;
  44490. break;
  44491. }
  44492. default:
  44493. throw new Error("_prepareContext is only for opaque or alphaTest");
  44494. }
  44495. var renderCount = 0;
  44496. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  44497. // Skip it if instanced arrays are not supported
  44498. if (this.owner.supportInstancedArray) {
  44499. // Flag for instancing
  44500. context.useInstancing = true;
  44501. // Make sure all the WebGLBuffers of the Instanced Array are created/up to date for the parts to render.
  44502. for (var i = 0; i < gipd.length; i++) {
  44503. var pid = gipd[i];
  44504. // If the instances of the model was changed, pack the data
  44505. var array = pid._partData;
  44506. var instanceData_1 = array.pack();
  44507. renderCount += array.usedElementCount;
  44508. // Compute the size the instance buffer should have
  44509. var neededSize = array.usedElementCount * array.stride * 4;
  44510. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  44511. if (!pid._partBuffer || (pid._partBufferSize < neededSize)) {
  44512. if (pid._partBuffer) {
  44513. engine.deleteInstancesBuffer(pid._partBuffer);
  44514. }
  44515. pid._partBuffer = engine.createInstancesBuffer(neededSize); // Create + bind
  44516. pid._partBufferSize = neededSize;
  44517. setDirty(false);
  44518. // Update the WebGL buffer to match the new content of the instances data
  44519. engine.updateArrayBuffer(instanceData_1);
  44520. }
  44521. else if (getDirty()) {
  44522. // Update the WebGL buffer to match the new content of the instances data
  44523. engine.bindArrayBuffer(pid._partBuffer);
  44524. engine.updateArrayBuffer(instanceData_1);
  44525. }
  44526. }
  44527. setDirty(false);
  44528. }
  44529. else {
  44530. context.partDataStartIndex = 0;
  44531. // Find the first valid object to get the count
  44532. if (context.groupInfoPartData.length > 0) {
  44533. var i = 0;
  44534. while (!context.groupInfoPartData[i]) {
  44535. i++;
  44536. }
  44537. context.partDataEndIndex = context.groupInfoPartData[i]._partData.usedElementCount;
  44538. }
  44539. }
  44540. return renderCount;
  44541. };
  44542. Group2D.prototype._setRenderingScale = function (scale) {
  44543. if (this._renderableData._renderingScale === scale) {
  44544. return;
  44545. }
  44546. this._renderableData._renderingScale = scale;
  44547. };
  44548. Group2D.prototype._bindCacheTarget = function () {
  44549. var curWidth;
  44550. var curHeight;
  44551. var rd = this._renderableData;
  44552. var rs = rd._renderingScale;
  44553. var noResizeScale = rd._noResizeOnScale;
  44554. var isCanvas = this.parent == null;
  44555. var scale;
  44556. if (noResizeScale) {
  44557. scale = isCanvas ? Group2D._uV : this.parent.actualScale;
  44558. }
  44559. else {
  44560. scale = this.actualScale;
  44561. }
  44562. Group2D._s.width = Math.ceil(this.actualSize.width * scale.x * rs);
  44563. Group2D._s.height = Math.ceil(this.actualSize.height * scale.y * rs);
  44564. var sizeChanged = !Group2D._s.equals(rd._cacheSize);
  44565. if (rd._cacheNode) {
  44566. var size = rd._cacheNode.contentSize;
  44567. // Check if we have to deallocate because the size is too small
  44568. if ((size.width < Group2D._s.width) || (size.height < Group2D._s.height)) {
  44569. // For Screen space: over-provisioning of 7% more to avoid frequent resizing for few pixels...
  44570. // For World space: no over-provisioning
  44571. var overprovisioning = this.owner.isScreenSpace ? 1.07 : 1;
  44572. curWidth = Math.floor(Group2D._s.width * overprovisioning);
  44573. curHeight = Math.floor(Group2D._s.height * overprovisioning);
  44574. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  44575. rd._cacheTexture.freeRect(rd._cacheNode);
  44576. rd._cacheNode = null;
  44577. }
  44578. }
  44579. if (!rd._cacheNode) {
  44580. // Check if we have to allocate a rendering zone in the global cache texture
  44581. var res = this.owner._allocateGroupCache(this, this.parent && this.parent.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null, rd._useMipMap, rd._anisotropicLevel);
  44582. rd._cacheNode = res.node;
  44583. rd._cacheTexture = res.texture;
  44584. rd._cacheRenderSprite = res.sprite;
  44585. sizeChanged = true;
  44586. }
  44587. if (sizeChanged) {
  44588. rd._cacheSize.copyFrom(Group2D._s);
  44589. rd._cacheNodeUVs = rd._cacheNode.getUVsForCustomSize(rd._cacheSize);
  44590. if (rd._cacheNodeUVsChangedObservable && rd._cacheNodeUVsChangedObservable.hasObservers()) {
  44591. rd._cacheNodeUVsChangedObservable.notifyObservers(rd._cacheNodeUVs);
  44592. }
  44593. this._setFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  44594. }
  44595. var n = rd._cacheNode;
  44596. rd._cacheTexture.bindTextureForPosSize(n.pos, Group2D._s, true);
  44597. };
  44598. Group2D.prototype._unbindCacheTarget = function () {
  44599. if (this._renderableData._cacheTexture) {
  44600. this._renderableData._cacheTexture.unbindTexture();
  44601. }
  44602. };
  44603. Group2D.prototype.handleGroupChanged = function (prop) {
  44604. // This method is only for cachedGroup
  44605. var rd = this._renderableData;
  44606. if (!rd) {
  44607. return;
  44608. }
  44609. var cachedSprite = rd._cacheRenderSprite;
  44610. if (!this.isCachedGroup || !cachedSprite) {
  44611. return;
  44612. }
  44613. // For now we only support these property changes
  44614. // TODO: add more! :)
  44615. if (prop.id === BABYLON.Prim2DBase.actualPositionProperty.id) {
  44616. cachedSprite.actualPosition = this.actualPosition.clone();
  44617. if (cachedSprite.position != null) {
  44618. cachedSprite.position = cachedSprite.actualPosition.clone();
  44619. }
  44620. }
  44621. else if (prop.id === BABYLON.Prim2DBase.rotationProperty.id) {
  44622. cachedSprite.rotation = this.rotation;
  44623. }
  44624. else if (prop.id === BABYLON.Prim2DBase.scaleProperty.id) {
  44625. cachedSprite.scale = this.scale;
  44626. }
  44627. else if (prop.id === BABYLON.Prim2DBase.originProperty.id) {
  44628. cachedSprite.origin = this.origin.clone();
  44629. }
  44630. else if (prop.id === Group2D.actualSizeProperty.id) {
  44631. cachedSprite.size = this.actualSize.clone();
  44632. }
  44633. };
  44634. Group2D.prototype.detectGroupStates = function () {
  44635. var isCanvas = this instanceof BABYLON.Canvas2D;
  44636. var canvasStrat = this.owner.cachingStrategy;
  44637. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  44638. if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
  44639. this._isRenderableGroup = isCanvas;
  44640. this._isCachedGroup = false;
  44641. }
  44642. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
  44643. if (isCanvas) {
  44644. this._isRenderableGroup = true;
  44645. this._isCachedGroup = true;
  44646. }
  44647. else {
  44648. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  44649. this._isCachedGroup = false;
  44650. }
  44651. }
  44652. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  44653. if (isCanvas) {
  44654. this._isRenderableGroup = true;
  44655. this._isCachedGroup = false;
  44656. }
  44657. else {
  44658. if (this.hierarchyDepth === 1) {
  44659. this._isRenderableGroup = true;
  44660. this._isCachedGroup = true;
  44661. }
  44662. else {
  44663. this._isRenderableGroup = false;
  44664. this._isCachedGroup = false;
  44665. }
  44666. }
  44667. }
  44668. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  44669. var gcb = this.cacheBehavior & Group2D.GROUPCACHEBEHAVIOR_OPTIONMASK;
  44670. if ((gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  44671. this._isRenderableGroup = gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  44672. this._isCachedGroup = false;
  44673. }
  44674. if (gcb === Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  44675. this._isRenderableGroup = true;
  44676. this._isCachedGroup = true;
  44677. }
  44678. }
  44679. if (this._isRenderableGroup) {
  44680. // Yes, we do need that check, trust me, unfortunately we can call _detectGroupStates many time on the same object...
  44681. if (!this._renderableData) {
  44682. this._renderableData = new RenderableGroupData();
  44683. }
  44684. }
  44685. // If the group is tagged as renderable we add it to the renderable tree
  44686. if (this._isCachedGroup) {
  44687. this._renderableData._noResizeOnScale = (this.cacheBehavior & Group2D.GROUPCACHEBEHAVIOR_NORESIZEONSCALE) !== 0;
  44688. var cur = this.parent;
  44689. while (cur) {
  44690. if (cur instanceof Group2D && cur._isRenderableGroup) {
  44691. if (cur._renderableData._childrenRenderableGroups.indexOf(this) === -1) {
  44692. cur._renderableData._childrenRenderableGroups.push(this);
  44693. }
  44694. break;
  44695. }
  44696. cur = cur.parent;
  44697. }
  44698. }
  44699. };
  44700. Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  44701. /**
  44702. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  44703. */
  44704. Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  44705. /**
  44706. * When used, this group's content won't be cached, no matter which strategy used.
  44707. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  44708. */
  44709. Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  44710. /**
  44711. * When used, the group's content will be cached in the nearest cached parent group/canvas
  44712. */
  44713. Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  44714. /**
  44715. * You can specify this behavior to any cached Group2D to indicate that you don't want the cached content to be resized when the Group's actualScale is changing. It will draw the content stretched or shrink which is faster than a resize. This setting is obviously for performance consideration, don't use it if you want the best rendering quality
  44716. */
  44717. Group2D.GROUPCACHEBEHAVIOR_NORESIZEONSCALE = 0x100;
  44718. Group2D.GROUPCACHEBEHAVIOR_OPTIONMASK = 0xFF;
  44719. Group2D._uV = new BABYLON.Vector2(1, 1);
  44720. Group2D._s = BABYLON.Size.Zero();
  44721. __decorate([
  44722. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D.sizeProperty = pi; }, false, true)
  44723. ], Group2D.prototype, "size", null);
  44724. __decorate([
  44725. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 2, function (pi) { return Group2D.actualSizeProperty = pi; })
  44726. ], Group2D.prototype, "actualSize", null);
  44727. Group2D = __decorate([
  44728. BABYLON.className("Group2D")
  44729. ], Group2D);
  44730. return Group2D;
  44731. })(BABYLON.Prim2DBase);
  44732. BABYLON.Group2D = Group2D;
  44733. var RenderableGroupData = (function () {
  44734. function RenderableGroupData() {
  44735. this._primDirtyList = new Array();
  44736. this._primNewDirtyList = new Array();
  44737. this._childrenRenderableGroups = new Array();
  44738. this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
  44739. this._transparentPrimitives = new Array();
  44740. this._transparentSegments = new Array();
  44741. this._transparentListChanged = false;
  44742. this._cacheNode = null;
  44743. this._cacheTexture = null;
  44744. this._cacheRenderSprite = null;
  44745. this._renderingScale = 1;
  44746. this._cacheNodeUVs = null;
  44747. this._cacheNodeUVsChangedObservable = null;
  44748. this._cacheSize = BABYLON.Size.Zero();
  44749. this._useMipMap = false;
  44750. this._anisotropicLevel = 1;
  44751. this._noResizeOnScale = false;
  44752. }
  44753. RenderableGroupData.prototype.dispose = function (owner) {
  44754. var engine = owner.engine;
  44755. if (this._cacheRenderSprite) {
  44756. this._cacheRenderSprite.dispose();
  44757. this._cacheRenderSprite = null;
  44758. }
  44759. if (this._cacheTexture && this._cacheNode) {
  44760. this._cacheTexture.freeRect(this._cacheNode);
  44761. this._cacheTexture = null;
  44762. this._cacheNode = null;
  44763. }
  44764. if (this._primDirtyList) {
  44765. this._primDirtyList.splice(0);
  44766. this._primDirtyList = null;
  44767. }
  44768. if (this._renderGroupInstancesInfo) {
  44769. this._renderGroupInstancesInfo.forEach(function (k, v) {
  44770. v.dispose();
  44771. });
  44772. this._renderGroupInstancesInfo = null;
  44773. }
  44774. if (this._cacheNodeUVsChangedObservable) {
  44775. this._cacheNodeUVsChangedObservable.clear();
  44776. this._cacheNodeUVsChangedObservable = null;
  44777. }
  44778. if (this._transparentSegments) {
  44779. for (var _i = 0, _a = this._transparentSegments; _i < _a.length; _i++) {
  44780. var ts = _a[_i];
  44781. ts.dispose(engine);
  44782. }
  44783. this._transparentSegments.splice(0);
  44784. this._transparentSegments = null;
  44785. }
  44786. };
  44787. RenderableGroupData.prototype.addNewTransparentPrimitiveInfo = function (prim, gii) {
  44788. var tpi = new TransparentPrimitiveInfo();
  44789. tpi._primitive = prim;
  44790. tpi._groupInstanceInfo = gii;
  44791. tpi._transparentSegment = null;
  44792. this._transparentPrimitives.push(tpi);
  44793. this._transparentListChanged = true;
  44794. return tpi;
  44795. };
  44796. RenderableGroupData.prototype.removeTransparentPrimitiveInfo = function (tpi) {
  44797. var index = this._transparentPrimitives.indexOf(tpi);
  44798. if (index !== -1) {
  44799. this._transparentPrimitives.splice(index, 1);
  44800. this._transparentListChanged = true;
  44801. }
  44802. };
  44803. RenderableGroupData.prototype.transparentPrimitiveZChanged = function (tpi) {
  44804. this._transparentListChanged = true;
  44805. //this.updateSmallestZChangedPrim(tpi);
  44806. };
  44807. return RenderableGroupData;
  44808. })();
  44809. BABYLON.RenderableGroupData = RenderableGroupData;
  44810. var TransparentPrimitiveInfo = (function () {
  44811. function TransparentPrimitiveInfo() {
  44812. }
  44813. return TransparentPrimitiveInfo;
  44814. })();
  44815. BABYLON.TransparentPrimitiveInfo = TransparentPrimitiveInfo;
  44816. })(BABYLON || (BABYLON = {}));
  44817. var BABYLON;
  44818. (function (BABYLON) {
  44819. var Rectangle2DRenderCache = (function (_super) {
  44820. __extends(Rectangle2DRenderCache, _super);
  44821. function Rectangle2DRenderCache(engine, modelKey) {
  44822. _super.call(this, engine, modelKey);
  44823. this.effectsReady = false;
  44824. this.fillVB = null;
  44825. this.fillIB = null;
  44826. this.fillIndicesCount = 0;
  44827. this.instancingFillAttributes = null;
  44828. this.effectFill = null;
  44829. this.effectFillInstanced = null;
  44830. this.borderVB = null;
  44831. this.borderIB = null;
  44832. this.borderIndicesCount = 0;
  44833. this.instancingBorderAttributes = null;
  44834. this.effectBorder = null;
  44835. this.effectBorderInstanced = null;
  44836. }
  44837. Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
  44838. // Do nothing if the shader is still loading/preparing
  44839. if (!this.effectsReady) {
  44840. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  44841. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  44842. return false;
  44843. }
  44844. this.effectsReady = true;
  44845. }
  44846. var canvas = instanceInfo.owner.owner;
  44847. var engine = canvas.engine;
  44848. var depthFunction = 0;
  44849. if (this.effectFill && this.effectBorder) {
  44850. depthFunction = engine.getDepthFunction();
  44851. engine.setDepthFunctionToLessOrEqual();
  44852. }
  44853. var curAlphaMode = engine.getAlphaMode();
  44854. if (this.effectFill) {
  44855. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  44856. var pid = context.groupInfoPartData[partIndex];
  44857. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44858. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  44859. }
  44860. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  44861. engine.enableEffect(effect);
  44862. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  44863. if (context.useInstancing) {
  44864. if (!this.instancingFillAttributes) {
  44865. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  44866. }
  44867. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44868. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44869. canvas._addDrawCallCount(1, context.renderMode);
  44870. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  44871. engine.draw(true, 0, this.fillIndicesCount, count);
  44872. engine.unbindInstanceAttributes();
  44873. }
  44874. else {
  44875. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44876. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44877. this.setupUniforms(effect, partIndex, pid._partData, i);
  44878. engine.draw(true, 0, this.fillIndicesCount);
  44879. }
  44880. }
  44881. }
  44882. if (this.effectBorder) {
  44883. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  44884. var pid = context.groupInfoPartData[partIndex];
  44885. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44886. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  44887. }
  44888. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  44889. engine.enableEffect(effect);
  44890. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  44891. if (context.useInstancing) {
  44892. if (!this.instancingBorderAttributes) {
  44893. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  44894. }
  44895. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44896. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44897. canvas._addDrawCallCount(1, context.renderMode);
  44898. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  44899. engine.draw(true, 0, this.borderIndicesCount, count);
  44900. engine.unbindInstanceAttributes();
  44901. }
  44902. else {
  44903. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44904. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44905. this.setupUniforms(effect, partIndex, pid._partData, i);
  44906. engine.draw(true, 0, this.borderIndicesCount);
  44907. }
  44908. }
  44909. }
  44910. engine.setAlphaMode(curAlphaMode, true);
  44911. if (this.effectFill && this.effectBorder) {
  44912. engine.setDepthFunction(depthFunction);
  44913. }
  44914. return true;
  44915. };
  44916. Rectangle2DRenderCache.prototype.dispose = function () {
  44917. if (!_super.prototype.dispose.call(this)) {
  44918. return false;
  44919. }
  44920. if (this.fillVB) {
  44921. this._engine._releaseBuffer(this.fillVB);
  44922. this.fillVB = null;
  44923. }
  44924. if (this.fillIB) {
  44925. this._engine._releaseBuffer(this.fillIB);
  44926. this.fillIB = null;
  44927. }
  44928. this.effectFill = null;
  44929. this.effectFillInstanced = null;
  44930. this.effectBorder = null;
  44931. this.effectBorderInstanced = null;
  44932. if (this.borderVB) {
  44933. this._engine._releaseBuffer(this.borderVB);
  44934. this.borderVB = null;
  44935. }
  44936. if (this.borderIB) {
  44937. this._engine._releaseBuffer(this.borderIB);
  44938. this.borderIB = null;
  44939. }
  44940. return true;
  44941. };
  44942. return Rectangle2DRenderCache;
  44943. })(BABYLON.ModelRenderCache);
  44944. BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
  44945. var Rectangle2DInstanceData = (function (_super) {
  44946. __extends(Rectangle2DInstanceData, _super);
  44947. function Rectangle2DInstanceData(partId) {
  44948. _super.call(this, partId, 1);
  44949. }
  44950. Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
  44951. get: function () {
  44952. return null;
  44953. },
  44954. enumerable: true,
  44955. configurable: true
  44956. });
  44957. __decorate([
  44958. BABYLON.instanceData()
  44959. ], Rectangle2DInstanceData.prototype, "properties", null);
  44960. return Rectangle2DInstanceData;
  44961. })(BABYLON.Shape2DInstanceData);
  44962. BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
  44963. var Rectangle2D = (function (_super) {
  44964. __extends(Rectangle2D, _super);
  44965. /**
  44966. * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
  44967. * @param settings a combination of settings, possible ones are
  44968. * - 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)
  44969. * - children: an array of direct children
  44970. * - id a text identifier, for information purpose
  44971. * - position: the X & Y positions relative to its parent. Alternatively the x and y settings can be set. Default is [0;0]
  44972. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  44973. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  44974. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  44975. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  44976. * - zOrder: override the zOrder with the specified value
  44977. * - origin: define the normalized origin point location, default [0.5;0.5]
  44978. * - size: the size of the group. Alternatively the width and height settings can be set. Default will be [10;10].
  44979. * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp edges rectangle).
  44980. * - 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)
  44981. * - 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)
  44982. * - borderThickness: the thickness of the drawn border, default is 1.
  44983. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  44984. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  44985. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  44986. * - 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!
  44987. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44988. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44989. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44990. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44991. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  44992. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  44993. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  44994. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  44995. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44996. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44997. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44998. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44999. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  45000. */
  45001. function Rectangle2D(settings) {
  45002. // Avoid checking every time if the object exists
  45003. if (settings == null) {
  45004. settings = {};
  45005. }
  45006. _super.call(this, settings);
  45007. if (settings.size != null) {
  45008. this.size = settings.size;
  45009. }
  45010. else if (settings.width || settings.height) {
  45011. var size = new BABYLON.Size(settings.width, settings.height);
  45012. this.size = size;
  45013. }
  45014. //let size = settings.size || (new Size((settings.width === null) ? null : (settings.width || 10), (settings.height === null) ? null : (settings.height || 10)));
  45015. var roundRadius = (settings.roundRadius == null) ? 0 : settings.roundRadius;
  45016. var borderThickness = (settings.borderThickness == null) ? 1 : settings.borderThickness;
  45017. //this.size = size;
  45018. this.roundRadius = roundRadius;
  45019. this.borderThickness = borderThickness;
  45020. }
  45021. Object.defineProperty(Rectangle2D.prototype, "actualSize", {
  45022. get: function () {
  45023. if (this._actualSize) {
  45024. return this._actualSize;
  45025. }
  45026. return this.size;
  45027. },
  45028. set: function (value) {
  45029. this._actualSize = value;
  45030. },
  45031. enumerable: true,
  45032. configurable: true
  45033. });
  45034. Object.defineProperty(Rectangle2D.prototype, "notRounded", {
  45035. get: function () {
  45036. return this._notRounded;
  45037. },
  45038. set: function (value) {
  45039. this._notRounded = value;
  45040. },
  45041. enumerable: true,
  45042. configurable: true
  45043. });
  45044. Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
  45045. get: function () {
  45046. return this._roundRadius;
  45047. },
  45048. set: function (value) {
  45049. this._roundRadius = value;
  45050. this.notRounded = value === 0;
  45051. this._positioningDirty();
  45052. },
  45053. enumerable: true,
  45054. configurable: true
  45055. });
  45056. Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
  45057. // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
  45058. if (this.notRounded) {
  45059. return true;
  45060. }
  45061. // 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.
  45062. // 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)
  45063. // 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.
  45064. // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
  45065. var size = this.size;
  45066. Rectangle2D._i0.x = intersectInfo._localPickPosition.x;
  45067. Rectangle2D._i0.y = intersectInfo._localPickPosition.y;
  45068. var rr = this.roundRadius;
  45069. var rrs = rr * rr;
  45070. // Check if the point is in the bottom/left quarter area
  45071. Rectangle2D._i1.x = rr;
  45072. Rectangle2D._i1.y = rr;
  45073. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  45074. // Compute the intersection point in the quarter local space
  45075. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  45076. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  45077. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  45078. return Rectangle2D._i2.lengthSquared() <= rrs;
  45079. }
  45080. // Check if the point is in the top/left quarter area
  45081. Rectangle2D._i1.x = rr;
  45082. Rectangle2D._i1.y = size.height - rr;
  45083. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  45084. // Compute the intersection point in the quarter local space
  45085. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  45086. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  45087. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  45088. return Rectangle2D._i2.lengthSquared() <= rrs;
  45089. }
  45090. // Check if the point is in the top/right quarter area
  45091. Rectangle2D._i1.x = size.width - rr;
  45092. Rectangle2D._i1.y = size.height - rr;
  45093. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  45094. // Compute the intersection point in the quarter local space
  45095. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  45096. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  45097. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  45098. return Rectangle2D._i2.lengthSquared() <= rrs;
  45099. }
  45100. // Check if the point is in the bottom/right quarter area
  45101. Rectangle2D._i1.x = size.width - rr;
  45102. Rectangle2D._i1.y = rr;
  45103. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  45104. // Compute the intersection point in the quarter local space
  45105. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  45106. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  45107. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  45108. return Rectangle2D._i2.lengthSquared() <= rrs;
  45109. }
  45110. // At any other locations the point is guarantied to be inside
  45111. return true;
  45112. };
  45113. Rectangle2D.prototype.updateLevelBoundingInfo = function () {
  45114. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  45115. };
  45116. Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
  45117. var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
  45118. return renderCache;
  45119. };
  45120. Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  45121. var renderCache = modelRenderCache;
  45122. var engine = this.owner.engine;
  45123. // Need to create WebGL resources for fill part?
  45124. if (this.fill) {
  45125. var vbSize = ((this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4) + 1;
  45126. var vb = new Float32Array(vbSize);
  45127. for (var i = 0; i < vbSize; i++) {
  45128. vb[i] = i;
  45129. }
  45130. renderCache.fillVB = engine.createVertexBuffer(vb);
  45131. var triCount = vbSize - 1;
  45132. var ib = new Float32Array(triCount * 3);
  45133. for (var i = 0; i < triCount; i++) {
  45134. ib[i * 3 + 0] = 0;
  45135. ib[i * 3 + 2] = i + 1;
  45136. ib[i * 3 + 1] = i + 2;
  45137. }
  45138. ib[triCount * 3 - 2] = 1;
  45139. renderCache.fillIB = engine.createIndexBuffer(ib);
  45140. renderCache.fillIndicesCount = triCount * 3;
  45141. // 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
  45142. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
  45143. if (ei) {
  45144. renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45145. }
  45146. // Get the non instanced version
  45147. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
  45148. renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45149. }
  45150. // Need to create WebGL resource for border part?
  45151. if (this.border) {
  45152. var vbSize = (this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4 * 2;
  45153. var vb = new Float32Array(vbSize);
  45154. for (var i = 0; i < vbSize; i++) {
  45155. vb[i] = i;
  45156. }
  45157. renderCache.borderVB = engine.createVertexBuffer(vb);
  45158. var triCount = vbSize;
  45159. var rs = triCount / 2;
  45160. var ib = new Float32Array(triCount * 3);
  45161. for (var i = 0; i < rs; i++) {
  45162. var r0 = i;
  45163. var r1 = (i + 1) % rs;
  45164. ib[i * 6 + 0] = rs + r1;
  45165. ib[i * 6 + 1] = rs + r0;
  45166. ib[i * 6 + 2] = r0;
  45167. ib[i * 6 + 3] = r1;
  45168. ib[i * 6 + 4] = rs + r1;
  45169. ib[i * 6 + 5] = r0;
  45170. }
  45171. renderCache.borderIB = engine.createIndexBuffer(ib);
  45172. renderCache.borderIndicesCount = triCount * 3;
  45173. // 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
  45174. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
  45175. if (ei) {
  45176. renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45177. }
  45178. // Get the non instanced version
  45179. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
  45180. renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45181. }
  45182. return renderCache;
  45183. };
  45184. // 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
  45185. Rectangle2D.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  45186. // Fall back to default implementation if there's no round Radius
  45187. if (this._notRounded) {
  45188. _super.prototype._getInitialContentAreaToRef.call(this, primSize, initialContentPosition, initialContentArea);
  45189. }
  45190. else {
  45191. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  45192. initialContentPosition.x = initialContentPosition.y = rr;
  45193. initialContentArea.width = Math.max(0, primSize.width - (rr * 2));
  45194. initialContentArea.height = Math.max(0, primSize.height - (rr * 2));
  45195. }
  45196. };
  45197. Rectangle2D.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  45198. // Fall back to default implementation if there's no round Radius
  45199. if (this._notRounded) {
  45200. _super.prototype._getActualSizeFromContentToRef.call(this, primSize, newPrimSize);
  45201. }
  45202. else {
  45203. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  45204. newPrimSize.copyFrom(primSize);
  45205. newPrimSize.width += rr * 2;
  45206. newPrimSize.height += rr * 2;
  45207. }
  45208. };
  45209. Rectangle2D.prototype.createInstanceDataParts = function () {
  45210. var res = new Array();
  45211. if (this.border) {
  45212. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  45213. }
  45214. if (this.fill) {
  45215. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  45216. }
  45217. return res;
  45218. };
  45219. Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
  45220. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  45221. return false;
  45222. }
  45223. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  45224. var d = part;
  45225. var size = this.actualSize;
  45226. var s = this.actualScale;
  45227. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.roundRadius || 0);
  45228. }
  45229. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  45230. var d = part;
  45231. var size = this.actualSize;
  45232. var s = this.actualScale;
  45233. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.roundRadius || 0);
  45234. }
  45235. return true;
  45236. };
  45237. Rectangle2D._i0 = BABYLON.Vector2.Zero();
  45238. Rectangle2D._i1 = BABYLON.Vector2.Zero();
  45239. Rectangle2D._i2 = BABYLON.Vector2.Zero();
  45240. Rectangle2D.roundSubdivisions = 16;
  45241. __decorate([
  45242. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D.actualSizeProperty = pi; }, false, true)
  45243. ], Rectangle2D.prototype, "actualSize", null);
  45244. __decorate([
  45245. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D.notRoundedProperty = pi; })
  45246. ], Rectangle2D.prototype, "notRounded", null);
  45247. __decorate([
  45248. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D.roundRadiusProperty = pi; })
  45249. ], Rectangle2D.prototype, "roundRadius", null);
  45250. Rectangle2D = __decorate([
  45251. BABYLON.className("Rectangle2D")
  45252. ], Rectangle2D);
  45253. return Rectangle2D;
  45254. })(BABYLON.Shape2D);
  45255. BABYLON.Rectangle2D = Rectangle2D;
  45256. })(BABYLON || (BABYLON = {}));
  45257. var BABYLON;
  45258. (function (BABYLON) {
  45259. var Ellipse2DRenderCache = (function (_super) {
  45260. __extends(Ellipse2DRenderCache, _super);
  45261. function Ellipse2DRenderCache(engine, modelKey) {
  45262. _super.call(this, engine, modelKey);
  45263. this.effectsReady = false;
  45264. this.fillVB = null;
  45265. this.fillIB = null;
  45266. this.fillIndicesCount = 0;
  45267. this.instancingFillAttributes = null;
  45268. this.effectFillInstanced = null;
  45269. this.effectFill = null;
  45270. this.borderVB = null;
  45271. this.borderIB = null;
  45272. this.borderIndicesCount = 0;
  45273. this.instancingBorderAttributes = null;
  45274. this.effectBorderInstanced = null;
  45275. this.effectBorder = null;
  45276. }
  45277. Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
  45278. // Do nothing if the shader is still loading/preparing
  45279. if (!this.effectsReady) {
  45280. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  45281. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  45282. return false;
  45283. }
  45284. this.effectsReady = true;
  45285. }
  45286. var canvas = instanceInfo.owner.owner;
  45287. var engine = canvas.engine;
  45288. var depthFunction = 0;
  45289. if (this.effectFill && this.effectBorder) {
  45290. depthFunction = engine.getDepthFunction();
  45291. engine.setDepthFunctionToLessOrEqual();
  45292. }
  45293. var curAlphaMode = engine.getAlphaMode();
  45294. if (this.effectFill) {
  45295. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  45296. var pid = context.groupInfoPartData[partIndex];
  45297. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  45298. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45299. }
  45300. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  45301. engine.enableEffect(effect);
  45302. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  45303. if (context.useInstancing) {
  45304. if (!this.instancingFillAttributes) {
  45305. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  45306. }
  45307. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  45308. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45309. canvas._addDrawCallCount(1, context.renderMode);
  45310. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  45311. engine.draw(true, 0, this.fillIndicesCount, count);
  45312. engine.unbindInstanceAttributes();
  45313. }
  45314. else {
  45315. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45316. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45317. this.setupUniforms(effect, partIndex, pid._partData, i);
  45318. engine.draw(true, 0, this.fillIndicesCount);
  45319. }
  45320. }
  45321. }
  45322. if (this.effectBorder) {
  45323. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  45324. var pid = context.groupInfoPartData[partIndex];
  45325. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  45326. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45327. }
  45328. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  45329. engine.enableEffect(effect);
  45330. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  45331. if (context.useInstancing) {
  45332. if (!this.instancingBorderAttributes) {
  45333. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  45334. }
  45335. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  45336. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45337. canvas._addDrawCallCount(1, context.renderMode);
  45338. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  45339. engine.draw(true, 0, this.borderIndicesCount, count);
  45340. engine.unbindInstanceAttributes();
  45341. }
  45342. else {
  45343. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45344. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45345. this.setupUniforms(effect, partIndex, pid._partData, i);
  45346. engine.draw(true, 0, this.borderIndicesCount);
  45347. }
  45348. }
  45349. }
  45350. engine.setAlphaMode(curAlphaMode, true);
  45351. if (this.effectFill && this.effectBorder) {
  45352. engine.setDepthFunction(depthFunction);
  45353. }
  45354. return true;
  45355. };
  45356. Ellipse2DRenderCache.prototype.dispose = function () {
  45357. if (!_super.prototype.dispose.call(this)) {
  45358. return false;
  45359. }
  45360. if (this.fillVB) {
  45361. this._engine._releaseBuffer(this.fillVB);
  45362. this.fillVB = null;
  45363. }
  45364. if (this.fillIB) {
  45365. this._engine._releaseBuffer(this.fillIB);
  45366. this.fillIB = null;
  45367. }
  45368. this.effectFill = null;
  45369. this.effectFillInstanced = null;
  45370. this.effectBorder = null;
  45371. this.effectBorderInstanced = null;
  45372. if (this.borderVB) {
  45373. this._engine._releaseBuffer(this.borderVB);
  45374. this.borderVB = null;
  45375. }
  45376. if (this.borderIB) {
  45377. this._engine._releaseBuffer(this.borderIB);
  45378. this.borderIB = null;
  45379. }
  45380. return true;
  45381. };
  45382. return Ellipse2DRenderCache;
  45383. })(BABYLON.ModelRenderCache);
  45384. BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
  45385. var Ellipse2DInstanceData = (function (_super) {
  45386. __extends(Ellipse2DInstanceData, _super);
  45387. function Ellipse2DInstanceData(partId) {
  45388. _super.call(this, partId, 1);
  45389. }
  45390. Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
  45391. get: function () {
  45392. return null;
  45393. },
  45394. enumerable: true,
  45395. configurable: true
  45396. });
  45397. __decorate([
  45398. BABYLON.instanceData()
  45399. ], Ellipse2DInstanceData.prototype, "properties", null);
  45400. return Ellipse2DInstanceData;
  45401. })(BABYLON.Shape2DInstanceData);
  45402. BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
  45403. var Ellipse2D = (function (_super) {
  45404. __extends(Ellipse2D, _super);
  45405. /**
  45406. * Create an Ellipse 2D Shape primitive
  45407. * @param settings a combination of settings, possible ones are
  45408. * - 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)
  45409. * - children: an array of direct children
  45410. * - id: a text identifier, for information purpose
  45411. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  45412. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  45413. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  45414. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  45415. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  45416. * - zOrder: override the zOrder with the specified value
  45417. * - origin: define the normalized origin point location, default [0.5;0.5]
  45418. * - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
  45419. * - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
  45420. * - 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)
  45421. * - 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)
  45422. * - borderThickness: the thickness of the drawn border, default is 1.
  45423. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  45424. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  45425. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  45426. * - 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!
  45427. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45428. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45429. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45430. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45431. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  45432. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  45433. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  45434. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  45435. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45436. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45437. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45438. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45439. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  45440. */
  45441. function Ellipse2D(settings) {
  45442. // Avoid checking every time if the object exists
  45443. if (settings == null) {
  45444. settings = {};
  45445. }
  45446. _super.call(this, settings);
  45447. if (settings.size != null) {
  45448. this.size = settings.size;
  45449. }
  45450. else if (settings.width || settings.height) {
  45451. var size = new BABYLON.Size(settings.width, settings.height);
  45452. this.size = size;
  45453. }
  45454. var sub = (settings.subdivisions == null) ? 64 : settings.subdivisions;
  45455. this.subdivisions = sub;
  45456. }
  45457. Object.defineProperty(Ellipse2D.prototype, "actualSize", {
  45458. get: function () {
  45459. if (this._actualSize) {
  45460. return this._actualSize;
  45461. }
  45462. return this.size;
  45463. },
  45464. set: function (value) {
  45465. this._actualSize = value;
  45466. },
  45467. enumerable: true,
  45468. configurable: true
  45469. });
  45470. Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
  45471. get: function () {
  45472. return this._subdivisions;
  45473. },
  45474. set: function (value) {
  45475. this._subdivisions = value;
  45476. },
  45477. enumerable: true,
  45478. configurable: true
  45479. });
  45480. Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
  45481. var w = this.size.width / 2;
  45482. var h = this.size.height / 2;
  45483. var x = intersectInfo._localPickPosition.x - w;
  45484. var y = intersectInfo._localPickPosition.y - h;
  45485. return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
  45486. };
  45487. Ellipse2D.prototype.updateLevelBoundingInfo = function () {
  45488. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  45489. };
  45490. Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
  45491. var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
  45492. return renderCache;
  45493. };
  45494. Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  45495. var renderCache = modelRenderCache;
  45496. var engine = this.owner.engine;
  45497. // Need to create WebGL resources for fill part?
  45498. if (this.fill) {
  45499. var vbSize = this.subdivisions + 1;
  45500. var vb = new Float32Array(vbSize);
  45501. for (var i = 0; i < vbSize; i++) {
  45502. vb[i] = i;
  45503. }
  45504. renderCache.fillVB = engine.createVertexBuffer(vb);
  45505. var triCount = vbSize - 1;
  45506. var ib = new Float32Array(triCount * 3);
  45507. for (var i = 0; i < triCount; i++) {
  45508. ib[i * 3 + 0] = 0;
  45509. ib[i * 3 + 2] = i + 1;
  45510. ib[i * 3 + 1] = i + 2;
  45511. }
  45512. ib[triCount * 3 - 2] = 1;
  45513. renderCache.fillIB = engine.createIndexBuffer(ib);
  45514. renderCache.fillIndicesCount = triCount * 3;
  45515. // 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
  45516. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
  45517. if (ei) {
  45518. renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  45519. }
  45520. // Get the non instanced version
  45521. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
  45522. renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  45523. }
  45524. // Need to create WebGL resource for border part?
  45525. if (this.border) {
  45526. var vbSize = this.subdivisions * 2;
  45527. var vb = new Float32Array(vbSize);
  45528. for (var i = 0; i < vbSize; i++) {
  45529. vb[i] = i;
  45530. }
  45531. renderCache.borderVB = engine.createVertexBuffer(vb);
  45532. var triCount = vbSize;
  45533. var rs = triCount / 2;
  45534. var ib = new Float32Array(triCount * 3);
  45535. for (var i = 0; i < rs; i++) {
  45536. var r0 = i;
  45537. var r1 = (i + 1) % rs;
  45538. ib[i * 6 + 0] = rs + r1;
  45539. ib[i * 6 + 1] = rs + r0;
  45540. ib[i * 6 + 2] = r0;
  45541. ib[i * 6 + 3] = r1;
  45542. ib[i * 6 + 4] = rs + r1;
  45543. ib[i * 6 + 5] = r0;
  45544. }
  45545. renderCache.borderIB = engine.createIndexBuffer(ib);
  45546. renderCache.borderIndicesCount = (triCount * 3);
  45547. // 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
  45548. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
  45549. if (ei) {
  45550. renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45551. }
  45552. // Get the non instanced version
  45553. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
  45554. renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45555. }
  45556. return renderCache;
  45557. };
  45558. Ellipse2D.prototype.createInstanceDataParts = function () {
  45559. var res = new Array();
  45560. if (this.border) {
  45561. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  45562. }
  45563. if (this.fill) {
  45564. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  45565. }
  45566. return res;
  45567. };
  45568. Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
  45569. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  45570. return false;
  45571. }
  45572. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  45573. var d = part;
  45574. var size = this.actualSize;
  45575. var s = this.actualScale;
  45576. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.subdivisions);
  45577. }
  45578. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  45579. var d = part;
  45580. var size = this.actualSize;
  45581. var s = this.actualScale;
  45582. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.subdivisions);
  45583. }
  45584. return true;
  45585. };
  45586. __decorate([
  45587. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Ellipse2D.acutalSizeProperty = pi; }, false, true)
  45588. ], Ellipse2D.prototype, "actualSize", null);
  45589. __decorate([
  45590. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D.subdivisionsProperty = pi; })
  45591. ], Ellipse2D.prototype, "subdivisions", null);
  45592. Ellipse2D = __decorate([
  45593. BABYLON.className("Ellipse2D")
  45594. ], Ellipse2D);
  45595. return Ellipse2D;
  45596. })(BABYLON.Shape2D);
  45597. BABYLON.Ellipse2D = Ellipse2D;
  45598. })(BABYLON || (BABYLON = {}));
  45599. var BABYLON;
  45600. (function (BABYLON) {
  45601. var Sprite2DRenderCache = (function (_super) {
  45602. __extends(Sprite2DRenderCache, _super);
  45603. function Sprite2DRenderCache() {
  45604. _super.apply(this, arguments);
  45605. this.effectsReady = false;
  45606. this.vb = null;
  45607. this.ib = null;
  45608. this.instancingAttributes = null;
  45609. this.texture = null;
  45610. this.effect = null;
  45611. this.effectInstanced = null;
  45612. }
  45613. Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
  45614. // Do nothing if the shader is still loading/preparing
  45615. if (!this.effectsReady) {
  45616. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  45617. return false;
  45618. }
  45619. this.effectsReady = true;
  45620. }
  45621. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  45622. var canvas = instanceInfo.owner.owner;
  45623. var engine = canvas.engine;
  45624. var cur = engine.getAlphaMode();
  45625. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  45626. engine.enableEffect(effect);
  45627. effect.setTexture("diffuseSampler", this.texture);
  45628. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  45629. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  45630. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45631. }
  45632. effect.setBool("alphaTest", context.renderMode === BABYLON.Render2DContext.RenderModeAlphaTest);
  45633. var pid = context.groupInfoPartData[0];
  45634. if (context.useInstancing) {
  45635. if (!this.instancingAttributes) {
  45636. this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, effect);
  45637. }
  45638. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  45639. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45640. canvas._addDrawCallCount(1, context.renderMode);
  45641. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  45642. engine.draw(true, 0, 6, count);
  45643. engine.unbindInstanceAttributes();
  45644. }
  45645. else {
  45646. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45647. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45648. this.setupUniforms(effect, 0, pid._partData, i);
  45649. engine.draw(true, 0, 6);
  45650. }
  45651. }
  45652. engine.setAlphaMode(cur, true);
  45653. return true;
  45654. };
  45655. Sprite2DRenderCache.prototype.dispose = function () {
  45656. if (!_super.prototype.dispose.call(this)) {
  45657. return false;
  45658. }
  45659. if (this.vb) {
  45660. this._engine._releaseBuffer(this.vb);
  45661. this.vb = null;
  45662. }
  45663. if (this.ib) {
  45664. this._engine._releaseBuffer(this.ib);
  45665. this.ib = null;
  45666. }
  45667. //if (this.texture) {
  45668. // this.texture.dispose();
  45669. // this.texture = null;
  45670. //}
  45671. this.effect = null;
  45672. this.effectInstanced = null;
  45673. return true;
  45674. };
  45675. return Sprite2DRenderCache;
  45676. })(BABYLON.ModelRenderCache);
  45677. BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
  45678. var Sprite2DInstanceData = (function (_super) {
  45679. __extends(Sprite2DInstanceData, _super);
  45680. function Sprite2DInstanceData(partId) {
  45681. _super.call(this, partId, 1);
  45682. }
  45683. Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
  45684. get: function () {
  45685. return null;
  45686. },
  45687. enumerable: true,
  45688. configurable: true
  45689. });
  45690. Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
  45691. get: function () {
  45692. return null;
  45693. },
  45694. enumerable: true,
  45695. configurable: true
  45696. });
  45697. Object.defineProperty(Sprite2DInstanceData.prototype, "scaleFactor", {
  45698. get: function () {
  45699. return null;
  45700. },
  45701. enumerable: true,
  45702. configurable: true
  45703. });
  45704. Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
  45705. get: function () {
  45706. return null;
  45707. },
  45708. enumerable: true,
  45709. configurable: true
  45710. });
  45711. Object.defineProperty(Sprite2DInstanceData.prototype, "properties", {
  45712. // 3 floats being:
  45713. // - x: frame number to display
  45714. // - y: invertY setting
  45715. // - z: alignToPixel setting
  45716. get: function () {
  45717. return null;
  45718. },
  45719. enumerable: true,
  45720. configurable: true
  45721. });
  45722. __decorate([
  45723. BABYLON.instanceData()
  45724. ], Sprite2DInstanceData.prototype, "topLeftUV", null);
  45725. __decorate([
  45726. BABYLON.instanceData()
  45727. ], Sprite2DInstanceData.prototype, "sizeUV", null);
  45728. __decorate([
  45729. BABYLON.instanceData()
  45730. ], Sprite2DInstanceData.prototype, "scaleFactor", null);
  45731. __decorate([
  45732. BABYLON.instanceData()
  45733. ], Sprite2DInstanceData.prototype, "textureSize", null);
  45734. __decorate([
  45735. BABYLON.instanceData()
  45736. ], Sprite2DInstanceData.prototype, "properties", null);
  45737. return Sprite2DInstanceData;
  45738. })(BABYLON.InstanceDataBase);
  45739. BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
  45740. var Sprite2D = (function (_super) {
  45741. __extends(Sprite2D, _super);
  45742. /**
  45743. * Create an 2D Sprite primitive
  45744. * @param texture the texture that stores the sprite to render
  45745. * @param settings a combination of settings, possible ones are
  45746. * - 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)
  45747. * - children: an array of direct children
  45748. * - id a text identifier, for information purpose
  45749. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  45750. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  45751. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  45752. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  45753. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  45754. * - zOrder: override the zOrder with the specified value
  45755. * - origin: define the normalized origin point location, default [0.5;0.5]
  45756. * - spriteSize: the size of the sprite (in pixels), if null the size of the given texture will be used, default is null.
  45757. * - spriteLocation: the location (in pixels) in the texture of the top/left corner of the Sprite to display, default is null (0,0)
  45758. * - spriteScaleFactor: say you want to display a sprite twice as big as its bitmap which is 64,64, you set the spriteSize to 128,128 and have to set the spriteScaleFactory to 0.5,0.5 in order to address only the 64,64 pixels of the bitmaps. Default is 1,1.
  45759. * - invertY: if true the texture Y will be inverted, default is false.
  45760. * - 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.
  45761. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  45762. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  45763. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  45764. * - 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!
  45765. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45766. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45767. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45768. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45769. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  45770. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  45771. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  45772. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  45773. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45774. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45775. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45776. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45777. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  45778. */
  45779. function Sprite2D(texture, settings) {
  45780. var _this = this;
  45781. if (!settings) {
  45782. settings = {};
  45783. }
  45784. _super.call(this, settings);
  45785. this.texture = texture;
  45786. this.texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45787. this.texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45788. this.size = settings.spriteSize;
  45789. this.spriteLocation = settings.spriteLocation || new BABYLON.Vector2(0, 0);
  45790. this.spriteScaleFactor = settings.spriteScaleFactor || new BABYLON.Vector2(1, 1);
  45791. this.spriteFrame = 0;
  45792. this.invertY = (settings.invertY == null) ? false : settings.invertY;
  45793. this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  45794. this.useAlphaFromTexture = true;
  45795. if (settings.spriteSize == null || !texture.isReady()) {
  45796. if (texture.isReady()) {
  45797. this.size = texture.getBaseSize();
  45798. }
  45799. else {
  45800. texture.onLoadObservable.add(function () {
  45801. if (settings.spriteSize == null) {
  45802. _this.size = texture.getBaseSize();
  45803. }
  45804. _this._positioningDirty();
  45805. _this._instanceDirtyFlags |= BABYLON.Prim2DBase.originProperty.flagId | Sprite2D.textureProperty.flagId; // To make sure the sprite is issued again for render
  45806. });
  45807. }
  45808. }
  45809. }
  45810. Object.defineProperty(Sprite2D.prototype, "texture", {
  45811. get: function () {
  45812. return this._texture;
  45813. },
  45814. set: function (value) {
  45815. this._texture = value;
  45816. this._oldTextureHasAlpha = this._texture && this.texture.hasAlpha;
  45817. },
  45818. enumerable: true,
  45819. configurable: true
  45820. });
  45821. Object.defineProperty(Sprite2D.prototype, "useAlphaFromTexture", {
  45822. get: function () {
  45823. return this._useAlphaFromTexture;
  45824. },
  45825. set: function (value) {
  45826. if (this._useAlphaFromTexture === value) {
  45827. return;
  45828. }
  45829. this._useAlphaFromTexture = value;
  45830. this._updateRenderMode();
  45831. },
  45832. enumerable: true,
  45833. configurable: true
  45834. });
  45835. Object.defineProperty(Sprite2D.prototype, "actualSize", {
  45836. get: function () {
  45837. if (this._actualSize) {
  45838. return this._actualSize;
  45839. }
  45840. return this.size;
  45841. },
  45842. set: function (value) {
  45843. this._actualSize = value;
  45844. },
  45845. enumerable: true,
  45846. configurable: true
  45847. });
  45848. Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
  45849. get: function () {
  45850. return this._location;
  45851. },
  45852. set: function (value) {
  45853. this._location = value;
  45854. },
  45855. enumerable: true,
  45856. configurable: true
  45857. });
  45858. Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
  45859. get: function () {
  45860. return this._spriteFrame;
  45861. },
  45862. set: function (value) {
  45863. this._spriteFrame = value;
  45864. },
  45865. enumerable: true,
  45866. configurable: true
  45867. });
  45868. Object.defineProperty(Sprite2D.prototype, "invertY", {
  45869. get: function () {
  45870. return this._invertY;
  45871. },
  45872. set: function (value) {
  45873. this._invertY = value;
  45874. },
  45875. enumerable: true,
  45876. configurable: true
  45877. });
  45878. Object.defineProperty(Sprite2D.prototype, "spriteScaleFactor", {
  45879. get: function () {
  45880. return this._spriteScaleFactor;
  45881. },
  45882. set: function (value) {
  45883. this._spriteScaleFactor = value;
  45884. },
  45885. enumerable: true,
  45886. configurable: true
  45887. });
  45888. /**
  45889. * Sets the scale of the sprite using a BABYLON.Size(w,h).
  45890. * Keeps proportion by taking the maximum of the two scale for x and y.
  45891. * @param {Size} size Size(width,height)
  45892. */
  45893. Sprite2D.prototype.scaleToSize = function (size) {
  45894. var baseSize = this.size;
  45895. if (baseSize == null || !this.texture.isReady()) {
  45896. // we're probably at initiation of the scene, size is not set
  45897. if (this.texture.isReady()) {
  45898. baseSize = this.texture.getBaseSize();
  45899. }
  45900. else {
  45901. // the texture is not ready, wait for it to load before calling scaleToSize again
  45902. var thisObject = this;
  45903. this.texture.onLoadObservable.add(function () {
  45904. thisObject.scaleToSize(size);
  45905. });
  45906. return;
  45907. }
  45908. }
  45909. this.scale = Math.max(size.height / baseSize.height, size.width / baseSize.width);
  45910. };
  45911. Object.defineProperty(Sprite2D.prototype, "alignToPixel", {
  45912. /**
  45913. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  45914. */
  45915. get: function () {
  45916. return this._alignToPixel;
  45917. },
  45918. set: function (value) {
  45919. this._alignToPixel = value;
  45920. },
  45921. enumerable: true,
  45922. configurable: true
  45923. });
  45924. Sprite2D.prototype.updateLevelBoundingInfo = function () {
  45925. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo);
  45926. };
  45927. /**
  45928. * Get the animatable array (see http://doc.babylonjs.com/tutorials/Animations)
  45929. */
  45930. Sprite2D.prototype.getAnimatables = function () {
  45931. var res = new Array();
  45932. if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
  45933. res.push(this.texture);
  45934. }
  45935. return res;
  45936. };
  45937. Sprite2D.prototype.levelIntersect = function (intersectInfo) {
  45938. // 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
  45939. return true;
  45940. };
  45941. Sprite2D._createCachedCanvasSprite = function (owner, texture, size, pos) {
  45942. var sprite = new Sprite2D(texture, { parent: owner, id: "__cachedCanvasSprite__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), spriteSize: size, spriteLocation: pos, alignToPixel: true });
  45943. return sprite;
  45944. };
  45945. Sprite2D.prototype.createModelRenderCache = function (modelKey) {
  45946. var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey);
  45947. return renderCache;
  45948. };
  45949. Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  45950. var renderCache = modelRenderCache;
  45951. var engine = this.owner.engine;
  45952. var vb = new Float32Array(4);
  45953. for (var i = 0; i < 4; i++) {
  45954. vb[i] = i;
  45955. }
  45956. renderCache.vb = engine.createVertexBuffer(vb);
  45957. var ib = new Float32Array(6);
  45958. ib[0] = 0;
  45959. ib[1] = 2;
  45960. ib[2] = 1;
  45961. ib[3] = 0;
  45962. ib[4] = 3;
  45963. ib[5] = 2;
  45964. renderCache.ib = engine.createIndexBuffer(ib);
  45965. renderCache.texture = this.texture;
  45966. // 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
  45967. var ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], true);
  45968. if (ei) {
  45969. renderCache.effectInstanced = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  45970. }
  45971. ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], false);
  45972. renderCache.effect = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  45973. return renderCache;
  45974. };
  45975. Sprite2D.prototype.createInstanceDataParts = function () {
  45976. return [new Sprite2DInstanceData(Sprite2D.SPRITE2D_MAINPARTID)];
  45977. };
  45978. Sprite2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  45979. Sprite2D.layoutConstructMode = true;
  45980. };
  45981. // if obj contains something, we restore the _text property
  45982. Sprite2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  45983. Sprite2D.layoutConstructMode = false;
  45984. };
  45985. Sprite2D.prototype.refreshInstanceDataPart = function (part) {
  45986. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  45987. return false;
  45988. }
  45989. if (!this.texture.isReady() && !Sprite2D.layoutConstructMode) {
  45990. return false;
  45991. }
  45992. if (part.id === Sprite2D.SPRITE2D_MAINPARTID) {
  45993. var d = this._instanceDataParts[0];
  45994. if (Sprite2D.layoutConstructMode) {
  45995. d.topLeftUV = BABYLON.Vector2.Zero();
  45996. d.sizeUV = BABYLON.Vector2.Zero();
  45997. d.properties = BABYLON.Vector3.Zero();
  45998. d.textureSize = BABYLON.Vector2.Zero();
  45999. d.scaleFactor = BABYLON.Vector2.Zero();
  46000. }
  46001. else {
  46002. var ts = this.texture.getBaseSize();
  46003. var sl = this.spriteLocation;
  46004. var ss = this.actualSize;
  46005. var ssf = this.spriteScaleFactor;
  46006. d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
  46007. var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
  46008. d.sizeUV = suv;
  46009. d.scaleFactor = ssf;
  46010. Sprite2D._prop.x = this.spriteFrame;
  46011. Sprite2D._prop.y = this.invertY ? 1 : 0;
  46012. Sprite2D._prop.z = this.alignToPixel ? 1 : 0;
  46013. d.properties = Sprite2D._prop;
  46014. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  46015. }
  46016. }
  46017. return true;
  46018. };
  46019. Sprite2D.prototype._mustUpdateInstance = function () {
  46020. var res = this._oldTextureHasAlpha !== (this.texture != null && this.texture.hasAlpha);
  46021. this._oldTextureHasAlpha = this.texture != null && this.texture.hasAlpha;
  46022. if (res) {
  46023. this._updateRenderMode();
  46024. }
  46025. return res;
  46026. };
  46027. Sprite2D.prototype._useTextureAlpha = function () {
  46028. return this.texture != null && this.texture.hasAlpha;
  46029. };
  46030. Sprite2D.prototype._shouldUseAlphaFromTexture = function () {
  46031. return this.texture != null && this.texture.hasAlpha && this.useAlphaFromTexture;
  46032. };
  46033. Sprite2D.SPRITE2D_MAINPARTID = 1;
  46034. Sprite2D._prop = BABYLON.Vector3.Zero();
  46035. Sprite2D.layoutConstructMode = false;
  46036. __decorate([
  46037. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D.textureProperty = pi; })
  46038. ], Sprite2D.prototype, "texture", null);
  46039. __decorate([
  46040. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D.useAlphaFromTextureProperty = pi; })
  46041. ], Sprite2D.prototype, "useAlphaFromTexture", null);
  46042. __decorate([
  46043. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Sprite2D.actualSizeProperty = pi; }, false, true)
  46044. ], Sprite2D.prototype, "actualSize", null);
  46045. __decorate([
  46046. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D.spriteLocationProperty = pi; })
  46047. ], Sprite2D.prototype, "spriteLocation", null);
  46048. __decorate([
  46049. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D.spriteFrameProperty = pi; })
  46050. ], Sprite2D.prototype, "spriteFrame", null);
  46051. __decorate([
  46052. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Sprite2D.invertYProperty = pi; })
  46053. ], Sprite2D.prototype, "invertY", null);
  46054. __decorate([
  46055. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 7, function (pi) { return Sprite2D.spriteScaleFactorProperty = pi; })
  46056. ], Sprite2D.prototype, "spriteScaleFactor", null);
  46057. Sprite2D = __decorate([
  46058. BABYLON.className("Sprite2D")
  46059. ], Sprite2D);
  46060. return Sprite2D;
  46061. })(BABYLON.RenderablePrim2D);
  46062. BABYLON.Sprite2D = Sprite2D;
  46063. })(BABYLON || (BABYLON = {}));
  46064. var BABYLON;
  46065. (function (BABYLON) {
  46066. var Text2DRenderCache = (function (_super) {
  46067. __extends(Text2DRenderCache, _super);
  46068. function Text2DRenderCache() {
  46069. _super.apply(this, arguments);
  46070. this.effectsReady = false;
  46071. this.vb = null;
  46072. this.ib = null;
  46073. this.instancingAttributes = null;
  46074. this.fontTexture = null;
  46075. this.effect = null;
  46076. this.effectInstanced = null;
  46077. }
  46078. Text2DRenderCache.prototype.render = function (instanceInfo, context) {
  46079. // Do nothing if the shader is still loading/preparing
  46080. if (!this.effectsReady) {
  46081. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  46082. return false;
  46083. }
  46084. this.effectsReady = true;
  46085. }
  46086. var canvas = instanceInfo.owner.owner;
  46087. var engine = canvas.engine;
  46088. this.fontTexture.update();
  46089. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  46090. engine.enableEffect(effect);
  46091. effect.setTexture("diffuseSampler", this.fontTexture);
  46092. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  46093. var curAlphaMode = engine.getAlphaMode();
  46094. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  46095. var pid = context.groupInfoPartData[0];
  46096. if (context.useInstancing) {
  46097. if (!this.instancingAttributes) {
  46098. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
  46099. }
  46100. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  46101. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  46102. canvas._addDrawCallCount(1, context.renderMode);
  46103. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  46104. engine.draw(true, 0, 6, count);
  46105. engine.unbindInstanceAttributes();
  46106. }
  46107. else {
  46108. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  46109. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  46110. this.setupUniforms(effect, 0, pid._partData, i);
  46111. engine.draw(true, 0, 6);
  46112. }
  46113. }
  46114. engine.setAlphaMode(curAlphaMode, true);
  46115. return true;
  46116. };
  46117. Text2DRenderCache.prototype.dispose = function () {
  46118. if (!_super.prototype.dispose.call(this)) {
  46119. return false;
  46120. }
  46121. if (this.vb) {
  46122. this._engine._releaseBuffer(this.vb);
  46123. this.vb = null;
  46124. }
  46125. if (this.ib) {
  46126. this._engine._releaseBuffer(this.ib);
  46127. this.ib = null;
  46128. }
  46129. if (this.fontTexture) {
  46130. this.fontTexture.decCachedFontTextureCounter();
  46131. this.fontTexture = null;
  46132. }
  46133. this.effect = null;
  46134. this.effectInstanced = null;
  46135. return true;
  46136. };
  46137. return Text2DRenderCache;
  46138. })(BABYLON.ModelRenderCache);
  46139. BABYLON.Text2DRenderCache = Text2DRenderCache;
  46140. var Text2DInstanceData = (function (_super) {
  46141. __extends(Text2DInstanceData, _super);
  46142. function Text2DInstanceData(partId, dataElementCount) {
  46143. _super.call(this, partId, dataElementCount);
  46144. }
  46145. Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
  46146. get: function () {
  46147. return null;
  46148. },
  46149. enumerable: true,
  46150. configurable: true
  46151. });
  46152. Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
  46153. get: function () {
  46154. return null;
  46155. },
  46156. enumerable: true,
  46157. configurable: true
  46158. });
  46159. Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
  46160. get: function () {
  46161. return null;
  46162. },
  46163. enumerable: true,
  46164. configurable: true
  46165. });
  46166. Object.defineProperty(Text2DInstanceData.prototype, "color", {
  46167. get: function () {
  46168. return null;
  46169. },
  46170. enumerable: true,
  46171. configurable: true
  46172. });
  46173. Object.defineProperty(Text2DInstanceData.prototype, "superSampleFactor", {
  46174. get: function () {
  46175. return null;
  46176. },
  46177. enumerable: true,
  46178. configurable: true
  46179. });
  46180. __decorate([
  46181. BABYLON.instanceData()
  46182. ], Text2DInstanceData.prototype, "topLeftUV", null);
  46183. __decorate([
  46184. BABYLON.instanceData()
  46185. ], Text2DInstanceData.prototype, "sizeUV", null);
  46186. __decorate([
  46187. BABYLON.instanceData()
  46188. ], Text2DInstanceData.prototype, "textureSize", null);
  46189. __decorate([
  46190. BABYLON.instanceData()
  46191. ], Text2DInstanceData.prototype, "color", null);
  46192. __decorate([
  46193. BABYLON.instanceData()
  46194. ], Text2DInstanceData.prototype, "superSampleFactor", null);
  46195. return Text2DInstanceData;
  46196. })(BABYLON.InstanceDataBase);
  46197. BABYLON.Text2DInstanceData = Text2DInstanceData;
  46198. var Text2D = (function (_super) {
  46199. __extends(Text2D, _super);
  46200. /**
  46201. * Create a Text primitive
  46202. * @param text the text to display
  46203. * @param settings a combination of settings, possible ones are
  46204. * - 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)
  46205. * - children: an array of direct children
  46206. * - id a text identifier, for information purpose
  46207. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  46208. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  46209. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  46210. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  46211. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  46212. * - zOrder: override the zOrder with the specified value
  46213. * - origin: define the normalized origin point location, default [0.5;0.5]
  46214. * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
  46215. * - 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.
  46216. * - defaultFontColor: the color by default to apply on each letter of the text to display, default is plain white.
  46217. * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
  46218. * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
  46219. * - isVisible: true if the text must be visible, false for hidden. Default is true.
  46220. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  46221. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  46222. * - 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!
  46223. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46224. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46225. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46226. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46227. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  46228. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  46229. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  46230. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  46231. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46232. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46233. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46234. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46235. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  46236. */
  46237. function Text2D(text, settings) {
  46238. if (!settings) {
  46239. settings = {};
  46240. }
  46241. _super.call(this, settings);
  46242. this.fontName = (settings.fontName == null) ? "12pt Arial" : settings.fontName;
  46243. this._fontSuperSample = (settings.fontSuperSample != null && settings.fontSuperSample);
  46244. this.defaultFontColor = (settings.defaultFontColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : settings.defaultFontColor;
  46245. this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize;
  46246. this._textSize = null;
  46247. this.text = text;
  46248. this.size = (settings.size == null) ? null : settings.size;
  46249. this._updateRenderMode();
  46250. }
  46251. Object.defineProperty(Text2D.prototype, "fontName", {
  46252. get: function () {
  46253. return this._fontName;
  46254. },
  46255. set: function (value) {
  46256. if (this._fontName) {
  46257. throw new Error("Font Name change is not supported right now.");
  46258. }
  46259. this._fontName = value;
  46260. },
  46261. enumerable: true,
  46262. configurable: true
  46263. });
  46264. Object.defineProperty(Text2D.prototype, "defaultFontColor", {
  46265. get: function () {
  46266. return this._defaultFontColor;
  46267. },
  46268. set: function (value) {
  46269. this._defaultFontColor = value;
  46270. },
  46271. enumerable: true,
  46272. configurable: true
  46273. });
  46274. Object.defineProperty(Text2D.prototype, "text", {
  46275. get: function () {
  46276. return this._text;
  46277. },
  46278. set: function (value) {
  46279. this._text = value;
  46280. this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used
  46281. this._size = null;
  46282. this._updateCharCount();
  46283. // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute
  46284. var s = this.textSize;
  46285. },
  46286. enumerable: true,
  46287. configurable: true
  46288. });
  46289. Object.defineProperty(Text2D.prototype, "size", {
  46290. get: function () {
  46291. if (this._size != null) {
  46292. return this._size;
  46293. }
  46294. return this.textSize;
  46295. },
  46296. set: function (value) {
  46297. this._size = value;
  46298. },
  46299. enumerable: true,
  46300. configurable: true
  46301. });
  46302. Object.defineProperty(Text2D.prototype, "actualSize", {
  46303. /**
  46304. * Get the actual size of the Text2D primitive
  46305. */
  46306. get: function () {
  46307. if (this._actualSize) {
  46308. return this._actualSize;
  46309. }
  46310. return this.size;
  46311. },
  46312. enumerable: true,
  46313. configurable: true
  46314. });
  46315. Object.defineProperty(Text2D.prototype, "textSize", {
  46316. /**
  46317. * Get the area that bounds the text associated to the primitive
  46318. */
  46319. get: function () {
  46320. if (!this._textSize) {
  46321. if (this.owner) {
  46322. var newSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  46323. if (!newSize.equals(this._textSize)) {
  46324. this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  46325. this._positioningDirty();
  46326. }
  46327. this._textSize = newSize;
  46328. }
  46329. else {
  46330. return Text2D.nullSize;
  46331. }
  46332. }
  46333. return this._textSize;
  46334. },
  46335. enumerable: true,
  46336. configurable: true
  46337. });
  46338. Object.defineProperty(Text2D.prototype, "fontTexture", {
  46339. get: function () {
  46340. if (this._fontTexture) {
  46341. return this._fontTexture;
  46342. }
  46343. if (this.fontName == null || this.owner == null || this.owner.scene == null) {
  46344. return null;
  46345. }
  46346. this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  46347. return this._fontTexture;
  46348. },
  46349. enumerable: true,
  46350. configurable: true
  46351. });
  46352. /**
  46353. * Dispose the primitive, remove it from its parent
  46354. */
  46355. Text2D.prototype.dispose = function () {
  46356. if (!_super.prototype.dispose.call(this)) {
  46357. return false;
  46358. }
  46359. if (this._fontTexture) {
  46360. BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  46361. this._fontTexture = null;
  46362. }
  46363. return true;
  46364. };
  46365. Text2D.prototype.updateLevelBoundingInfo = function () {
  46366. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  46367. };
  46368. Text2D.prototype.levelIntersect = function (intersectInfo) {
  46369. // 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...
  46370. return true;
  46371. };
  46372. Text2D.prototype.createModelRenderCache = function (modelKey) {
  46373. var renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
  46374. return renderCache;
  46375. };
  46376. Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  46377. var renderCache = modelRenderCache;
  46378. var engine = this.owner.engine;
  46379. renderCache.fontTexture = this.fontTexture;
  46380. renderCache.fontTexture.incCachedFontTextureCounter();
  46381. var vb = new Float32Array(4);
  46382. for (var i = 0; i < 4; i++) {
  46383. vb[i] = i;
  46384. }
  46385. renderCache.vb = engine.createVertexBuffer(vb);
  46386. var ib = new Float32Array(6);
  46387. ib[0] = 0;
  46388. ib[1] = 2;
  46389. ib[2] = 1;
  46390. ib[3] = 0;
  46391. ib[4] = 3;
  46392. ib[5] = 2;
  46393. renderCache.ib = engine.createIndexBuffer(ib);
  46394. // 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
  46395. var ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], null, true);
  46396. if (ei) {
  46397. renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  46398. }
  46399. ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], null, false);
  46400. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  46401. return renderCache;
  46402. };
  46403. Text2D.prototype.createInstanceDataParts = function () {
  46404. return [new Text2DInstanceData(Text2D.TEXT2D_MAINPARTID, this._charCount)];
  46405. };
  46406. // Looks like a hack!? Yes! Because that's what it is!
  46407. // 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
  46408. // 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)
  46409. Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  46410. if (!this._charCount) {
  46411. var curText = this._text;
  46412. this.text = "A";
  46413. return curText;
  46414. }
  46415. };
  46416. // if obj contains something, we restore the _text property
  46417. Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  46418. if (obj !== undefined) {
  46419. this.text = obj;
  46420. }
  46421. };
  46422. Text2D.prototype.refreshInstanceDataPart = function (part) {
  46423. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  46424. return false;
  46425. }
  46426. if (part.id === Text2D.TEXT2D_MAINPARTID) {
  46427. var d = part;
  46428. var texture = this.fontTexture;
  46429. var superSampleFactor = texture.isSuperSampled ? 0.5 : 1;
  46430. var ts = texture.getSize();
  46431. var offset = BABYLON.Vector2.Zero();
  46432. var lh = this.fontTexture.lineHeight;
  46433. 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
  46434. var charxpos = 0;
  46435. d.dataElementCount = this._charCount;
  46436. d.curElement = 0;
  46437. for (var _i = 0, _a = this.text; _i < _a.length; _i++) {
  46438. var char = _a[_i];
  46439. // Line feed
  46440. if (char === "\n") {
  46441. offset.x = 0;
  46442. offset.y -= texture.lineHeight;
  46443. }
  46444. // Tabulation ?
  46445. if (char === "\t") {
  46446. var nextPos = charxpos + this._tabulationSize;
  46447. nextPos = nextPos - (nextPos % this._tabulationSize);
  46448. offset.x += (nextPos - charxpos) * texture.spaceWidth;
  46449. charxpos = nextPos;
  46450. continue;
  46451. }
  46452. if (char < " ") {
  46453. continue;
  46454. }
  46455. this.updateInstanceDataPart(d, offset);
  46456. var ci = texture.getChar(char);
  46457. offset.x += ci.charWidth;
  46458. d.topLeftUV = ci.topLeftUV;
  46459. var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  46460. d.sizeUV = suv;
  46461. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  46462. d.color = this.defaultFontColor;
  46463. d.superSampleFactor = superSampleFactor;
  46464. ++d.curElement;
  46465. }
  46466. }
  46467. return true;
  46468. };
  46469. Text2D.prototype._updateCharCount = function () {
  46470. var count = 0;
  46471. for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
  46472. var char = _a[_i];
  46473. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  46474. continue;
  46475. }
  46476. ++count;
  46477. }
  46478. this._charCount = count;
  46479. };
  46480. Text2D.prototype._useTextureAlpha = function () {
  46481. return this.fontTexture != null && this.fontTexture.hasAlpha;
  46482. };
  46483. Text2D.prototype._shouldUseAlphaFromTexture = function () {
  46484. return true;
  46485. };
  46486. Text2D.TEXT2D_MAINPARTID = 1;
  46487. __decorate([
  46488. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D.fontProperty = pi; }, false, true)
  46489. ], Text2D.prototype, "fontName", null);
  46490. __decorate([
  46491. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D.defaultFontColorProperty = pi; })
  46492. ], Text2D.prototype, "defaultFontColor", null);
  46493. __decorate([
  46494. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D.textProperty = pi; }, false, true)
  46495. ], Text2D.prototype, "text", null);
  46496. __decorate([
  46497. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D.sizeProperty = pi; })
  46498. ], Text2D.prototype, "size", null);
  46499. Text2D = __decorate([
  46500. BABYLON.className("Text2D")
  46501. ], Text2D);
  46502. return Text2D;
  46503. })(BABYLON.RenderablePrim2D);
  46504. BABYLON.Text2D = Text2D;
  46505. })(BABYLON || (BABYLON = {}));
  46506. var BABYLON;
  46507. (function (BABYLON) {
  46508. var Lines2DRenderCache = (function (_super) {
  46509. __extends(Lines2DRenderCache, _super);
  46510. function Lines2DRenderCache(engine, modelKey) {
  46511. _super.call(this, engine, modelKey);
  46512. this.effectsReady = false;
  46513. this.fillVB = null;
  46514. this.fillIB = null;
  46515. this.fillIndicesCount = 0;
  46516. this.instancingFillAttributes = null;
  46517. this.effectFill = null;
  46518. this.effectFillInstanced = null;
  46519. this.borderVB = null;
  46520. this.borderIB = null;
  46521. this.borderIndicesCount = 0;
  46522. this.instancingBorderAttributes = null;
  46523. this.effectBorder = null;
  46524. this.effectBorderInstanced = null;
  46525. }
  46526. Lines2DRenderCache.prototype.render = function (instanceInfo, context) {
  46527. // Do nothing if the shader is still loading/preparing
  46528. if (!this.effectsReady) {
  46529. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  46530. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  46531. return false;
  46532. }
  46533. this.effectsReady = true;
  46534. }
  46535. var canvas = instanceInfo.owner.owner;
  46536. var engine = canvas.engine;
  46537. var depthFunction = 0;
  46538. if (this.effectFill && this.effectBorder) {
  46539. depthFunction = engine.getDepthFunction();
  46540. engine.setDepthFunctionToLessOrEqual();
  46541. }
  46542. var curAlphaMode = engine.getAlphaMode();
  46543. if (this.effectFill) {
  46544. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  46545. var pid = context.groupInfoPartData[partIndex];
  46546. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  46547. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  46548. }
  46549. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  46550. engine.enableEffect(effect);
  46551. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [2], 2 * 4, effect);
  46552. if (context.useInstancing) {
  46553. if (!this.instancingFillAttributes) {
  46554. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  46555. }
  46556. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  46557. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  46558. canvas._addDrawCallCount(1, context.renderMode);
  46559. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  46560. engine.draw(true, 0, this.fillIndicesCount, count);
  46561. engine.unbindInstanceAttributes();
  46562. }
  46563. else {
  46564. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  46565. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  46566. this.setupUniforms(effect, partIndex, pid._partData, i);
  46567. engine.draw(true, 0, this.fillIndicesCount);
  46568. }
  46569. }
  46570. }
  46571. if (this.effectBorder) {
  46572. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  46573. var pid = context.groupInfoPartData[partIndex];
  46574. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  46575. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  46576. }
  46577. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  46578. engine.enableEffect(effect);
  46579. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [2], 2 * 4, effect);
  46580. if (context.useInstancing) {
  46581. if (!this.instancingBorderAttributes) {
  46582. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  46583. }
  46584. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  46585. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  46586. canvas._addDrawCallCount(1, context.renderMode);
  46587. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  46588. engine.draw(true, 0, this.borderIndicesCount, count);
  46589. engine.unbindInstanceAttributes();
  46590. }
  46591. else {
  46592. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  46593. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  46594. this.setupUniforms(effect, partIndex, pid._partData, i);
  46595. engine.draw(true, 0, this.borderIndicesCount);
  46596. }
  46597. }
  46598. }
  46599. engine.setAlphaMode(curAlphaMode, true);
  46600. if (this.effectFill && this.effectBorder) {
  46601. engine.setDepthFunction(depthFunction);
  46602. }
  46603. return true;
  46604. };
  46605. Lines2DRenderCache.prototype.dispose = function () {
  46606. if (!_super.prototype.dispose.call(this)) {
  46607. return false;
  46608. }
  46609. if (this.fillVB) {
  46610. this._engine._releaseBuffer(this.fillVB);
  46611. this.fillVB = null;
  46612. }
  46613. if (this.fillIB) {
  46614. this._engine._releaseBuffer(this.fillIB);
  46615. this.fillIB = null;
  46616. }
  46617. this.effectFill = null;
  46618. this.effectFillInstanced = null;
  46619. this.effectBorder = null;
  46620. this.effectBorderInstanced = null;
  46621. if (this.borderVB) {
  46622. this._engine._releaseBuffer(this.borderVB);
  46623. this.borderVB = null;
  46624. }
  46625. if (this.borderIB) {
  46626. this._engine._releaseBuffer(this.borderIB);
  46627. this.borderIB = null;
  46628. }
  46629. return true;
  46630. };
  46631. return Lines2DRenderCache;
  46632. })(BABYLON.ModelRenderCache);
  46633. BABYLON.Lines2DRenderCache = Lines2DRenderCache;
  46634. var Lines2DInstanceData = (function (_super) {
  46635. __extends(Lines2DInstanceData, _super);
  46636. function Lines2DInstanceData(partId) {
  46637. _super.call(this, partId, 1);
  46638. }
  46639. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMin", {
  46640. get: function () {
  46641. return null;
  46642. },
  46643. enumerable: true,
  46644. configurable: true
  46645. });
  46646. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMax", {
  46647. get: function () {
  46648. return null;
  46649. },
  46650. enumerable: true,
  46651. configurable: true
  46652. });
  46653. __decorate([
  46654. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  46655. ], Lines2DInstanceData.prototype, "boundingMin", null);
  46656. __decorate([
  46657. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  46658. ], Lines2DInstanceData.prototype, "boundingMax", null);
  46659. return Lines2DInstanceData;
  46660. })(BABYLON.Shape2DInstanceData);
  46661. BABYLON.Lines2DInstanceData = Lines2DInstanceData;
  46662. var Lines2D = (function (_super) {
  46663. __extends(Lines2D, _super);
  46664. /**
  46665. * Create an 2D Lines Shape primitive. The defined lines may be opened or closed (see below)
  46666. * @param points an array that describe the points to use to draw the line, must contain at least two entries.
  46667. * @param settings a combination of settings, possible ones are
  46668. * - 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)
  46669. * - children: an array of direct children
  46670. * - id a text identifier, for information purpose
  46671. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  46672. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  46673. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  46674. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  46675. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  46676. * - zOrder: override the zOrder with the specified value
  46677. * - origin: define the normalized origin point location, default [0.5;0.5]
  46678. * - 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.
  46679. * - 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.
  46680. * - 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.
  46681. * - 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.
  46682. * - 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)
  46683. * - 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)
  46684. * - borderThickness: the thickness of the drawn border, default is 1.
  46685. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  46686. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  46687. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  46688. * - 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!
  46689. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46690. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46691. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46692. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46693. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  46694. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  46695. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  46696. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  46697. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46698. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46699. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46700. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46701. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  46702. */
  46703. function Lines2D(points, settings) {
  46704. if (!settings) {
  46705. settings = {};
  46706. }
  46707. _super.call(this, settings);
  46708. this._fillVB = null;
  46709. this._fillIB = null;
  46710. this._borderVB = null;
  46711. this._borderIB = null;
  46712. this._size = BABYLON.Size.Zero();
  46713. this._boundingMin = null;
  46714. this._boundingMax = null;
  46715. var fillThickness = (settings.fillThickness == null) ? 1 : settings.fillThickness;
  46716. var startCap = (settings.startCap == null) ? 0 : settings.startCap;
  46717. var endCap = (settings.endCap == null) ? 0 : settings.endCap;
  46718. var closed = (settings.closed == null) ? false : settings.closed;
  46719. this.points = points;
  46720. this.fillThickness = fillThickness;
  46721. this.startCap = startCap;
  46722. this.endCap = endCap;
  46723. this.closed = closed;
  46724. }
  46725. Object.defineProperty(Lines2D, "NoCap", {
  46726. /**
  46727. * No Cap to apply on the extremity
  46728. */
  46729. get: function () { return Lines2D._noCap; },
  46730. enumerable: true,
  46731. configurable: true
  46732. });
  46733. Object.defineProperty(Lines2D, "RoundCap", {
  46734. /**
  46735. * A round cap, will use the line thickness as diameter
  46736. */
  46737. get: function () { return Lines2D._roundCap; },
  46738. enumerable: true,
  46739. configurable: true
  46740. });
  46741. Object.defineProperty(Lines2D, "TriangleCap", {
  46742. /**
  46743. * Creates a triangle at the extremity.
  46744. */
  46745. get: function () { return Lines2D._triangleCap; },
  46746. enumerable: true,
  46747. configurable: true
  46748. });
  46749. Object.defineProperty(Lines2D, "SquareAnchorCap", {
  46750. /**
  46751. * Creates a Square anchor at the extremity, the square size is twice the thickness of the line
  46752. */
  46753. get: function () { return Lines2D._squareAnchorCap; },
  46754. enumerable: true,
  46755. configurable: true
  46756. });
  46757. Object.defineProperty(Lines2D, "RoundAnchorCap", {
  46758. /**
  46759. * Creates a round anchor at the extremity, the diameter is twice the thickness of the line
  46760. */
  46761. get: function () { return Lines2D._roundAnchorCap; },
  46762. enumerable: true,
  46763. configurable: true
  46764. });
  46765. Object.defineProperty(Lines2D, "DiamondAnchorCap", {
  46766. /**
  46767. * Creates a diamond anchor at the extremity.
  46768. */
  46769. get: function () { return Lines2D._diamondAnchorCap; },
  46770. enumerable: true,
  46771. configurable: true
  46772. });
  46773. Object.defineProperty(Lines2D, "ArrowCap", {
  46774. /**
  46775. * Creates an arrow anchor at the extremity. the arrow base size is twice the thickness of the line
  46776. */
  46777. get: function () { return Lines2D._arrowCap; },
  46778. enumerable: true,
  46779. configurable: true
  46780. });
  46781. Object.defineProperty(Lines2D.prototype, "points", {
  46782. get: function () {
  46783. return this._points;
  46784. },
  46785. set: function (value) {
  46786. this._points = value;
  46787. this._contour = null;
  46788. this._boundingBoxDirty();
  46789. },
  46790. enumerable: true,
  46791. configurable: true
  46792. });
  46793. Object.defineProperty(Lines2D.prototype, "fillThickness", {
  46794. get: function () {
  46795. return this._fillThickness;
  46796. },
  46797. set: function (value) {
  46798. this._fillThickness = value;
  46799. },
  46800. enumerable: true,
  46801. configurable: true
  46802. });
  46803. Object.defineProperty(Lines2D.prototype, "closed", {
  46804. get: function () {
  46805. return this._closed;
  46806. },
  46807. set: function (value) {
  46808. this._closed = value;
  46809. },
  46810. enumerable: true,
  46811. configurable: true
  46812. });
  46813. Object.defineProperty(Lines2D.prototype, "startCap", {
  46814. get: function () {
  46815. return this._startCap;
  46816. },
  46817. set: function (value) {
  46818. this._startCap = value;
  46819. },
  46820. enumerable: true,
  46821. configurable: true
  46822. });
  46823. Object.defineProperty(Lines2D.prototype, "endCap", {
  46824. get: function () {
  46825. return this._endCap;
  46826. },
  46827. set: function (value) {
  46828. this._endCap = value;
  46829. },
  46830. enumerable: true,
  46831. configurable: true
  46832. });
  46833. Lines2D.prototype.levelIntersect = function (intersectInfo) {
  46834. var _this = this;
  46835. if (this._contour == null) {
  46836. this._computeLines2D();
  46837. }
  46838. var pl = this.points.length;
  46839. var l = this.closed ? pl + 1 : pl;
  46840. var p = intersectInfo._localPickPosition;
  46841. this.transformPointWithOriginToRef(this._contour[0], null, Lines2D._prevA);
  46842. this.transformPointWithOriginToRef(this._contour[1], null, Lines2D._prevB);
  46843. for (var i = 1; i < l; i++) {
  46844. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 0], null, Lines2D._curA);
  46845. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 1], null, Lines2D._curB);
  46846. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curA)) {
  46847. return true;
  46848. }
  46849. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._curA, Lines2D._prevB, Lines2D._curB)) {
  46850. return true;
  46851. }
  46852. Lines2D._prevA.x = Lines2D._curA.x;
  46853. Lines2D._prevA.y = Lines2D._curA.y;
  46854. Lines2D._prevB.x = Lines2D._curB.x;
  46855. Lines2D._prevB.y = Lines2D._curB.y;
  46856. }
  46857. var capIntersect = function (tri, points) {
  46858. var l = tri.length;
  46859. for (var i = 0; i < l; i += 3) {
  46860. Lines2D._curA.x = points[tri[i + 0] * 2 + 0];
  46861. Lines2D._curA.y = points[tri[i + 0] * 2 + 1];
  46862. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._curB);
  46863. Lines2D._curA.x = points[tri[i + 1] * 2 + 0];
  46864. Lines2D._curA.y = points[tri[i + 1] * 2 + 1];
  46865. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevA);
  46866. Lines2D._curA.x = points[tri[i + 2] * 2 + 0];
  46867. Lines2D._curA.y = points[tri[i + 2] * 2 + 1];
  46868. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevB);
  46869. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curB)) {
  46870. return true;
  46871. }
  46872. }
  46873. return false;
  46874. };
  46875. if (this._startCapTriIndices) {
  46876. if (this._startCapTriIndices && capIntersect(this._startCapTriIndices, this._startCapContour)) {
  46877. return true;
  46878. }
  46879. if (this._endCapTriIndices && capIntersect(this._endCapTriIndices, this._endCapContour)) {
  46880. return true;
  46881. }
  46882. }
  46883. return false;
  46884. };
  46885. Object.defineProperty(Lines2D.prototype, "boundingMin", {
  46886. get: function () {
  46887. if (!this._boundingMin) {
  46888. this._computeLines2D();
  46889. }
  46890. return this._boundingMin;
  46891. },
  46892. enumerable: true,
  46893. configurable: true
  46894. });
  46895. Object.defineProperty(Lines2D.prototype, "boundingMax", {
  46896. get: function () {
  46897. if (!this._boundingMax) {
  46898. this._computeLines2D();
  46899. }
  46900. return this._boundingMax;
  46901. },
  46902. enumerable: true,
  46903. configurable: true
  46904. });
  46905. Lines2D.prototype.getUsedShaderCategories = function (dataPart) {
  46906. var res = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  46907. // Remove the BORDER category, we don't use it in the VertexShader
  46908. var i = res.indexOf(BABYLON.Shape2D.SHAPE2D_CATEGORY_BORDER);
  46909. if (i !== -1) {
  46910. res.splice(i, 1);
  46911. }
  46912. return res;
  46913. };
  46914. Lines2D.prototype.updateLevelBoundingInfo = function () {
  46915. if (!this._boundingMin) {
  46916. this._computeLines2D();
  46917. }
  46918. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(this._boundingMin.x, this._boundingMax.x, this._boundingMin.y, this._boundingMax.y, this._levelBoundingInfo);
  46919. };
  46920. Lines2D.prototype.createModelRenderCache = function (modelKey) {
  46921. var renderCache = new Lines2DRenderCache(this.owner.engine, modelKey);
  46922. return renderCache;
  46923. };
  46924. ///////////////////////////////////////////////////////////////////////////////////
  46925. // Methods for Lines building
  46926. Lines2D.prototype._perp = function (v, res) {
  46927. res.x = v.y;
  46928. res.y = -v.x;
  46929. };
  46930. ;
  46931. Lines2D.prototype._direction = function (a, b, res) {
  46932. a.subtractToRef(b, res);
  46933. res.normalize();
  46934. };
  46935. Lines2D.prototype._computeMiter = function (tangent, miter, a, b) {
  46936. a.addToRef(b, tangent);
  46937. tangent.normalize();
  46938. miter.x = -tangent.y;
  46939. miter.y = tangent.x;
  46940. Lines2D._miterTps.x = -a.y;
  46941. Lines2D._miterTps.y = a.x;
  46942. return 1 / BABYLON.Vector2.Dot(miter, Lines2D._miterTps);
  46943. };
  46944. Lines2D.prototype._intersect = function (x1, y1, x2, y2, x3, y3, x4, y4) {
  46945. var d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  46946. if (d === 0)
  46947. return false;
  46948. var xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; // Intersection point is xi/yi, just in case...
  46949. //let yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; // That's why I left it commented
  46950. if (xi < Math.min(x1, x2) || xi > Math.max(x1, x2))
  46951. return false;
  46952. if (xi < Math.min(x3, x4) || xi > Math.max(x3, x4))
  46953. return false;
  46954. return true;
  46955. };
  46956. Lines2D.prototype._updateMinMax = function (array, offset) {
  46957. if (offset >= array.length) {
  46958. return;
  46959. }
  46960. this._boundingMin.x = Math.min(this._boundingMin.x, array[offset]);
  46961. this._boundingMax.x = Math.max(this._boundingMax.x, array[offset]);
  46962. this._boundingMin.y = Math.min(this._boundingMin.y, array[offset + 1]);
  46963. this._boundingMax.y = Math.max(this._boundingMax.y, array[offset + 1]);
  46964. };
  46965. Lines2D.prototype._store = function (array, contour, index, max, p, n, halfThickness, borderThickness, detectFlip) {
  46966. var borderMode = borderThickness != null && !isNaN(borderThickness);
  46967. var off = index * (borderMode ? 8 : 4);
  46968. // 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)
  46969. if (off >= array.length) {
  46970. return;
  46971. }
  46972. // Store start/end normal, we need it for the cap construction
  46973. if (index === 0) {
  46974. this._perp(n, Lines2D._startDir);
  46975. }
  46976. else if (index === max - 1) {
  46977. this._perp(n, Lines2D._endDir);
  46978. Lines2D._endDir.x *= -1;
  46979. Lines2D._endDir.y *= -1;
  46980. }
  46981. var swap = false;
  46982. array[off + 0] = p.x + n.x * halfThickness;
  46983. array[off + 1] = p.y + n.y * halfThickness;
  46984. array[off + 2] = p.x + n.x * -halfThickness;
  46985. array[off + 3] = p.y + n.y * -halfThickness;
  46986. this._updateMinMax(array, off);
  46987. this._updateMinMax(array, off + 2);
  46988. // If an index is given we check if the two segments formed between [index+0;detectFlip+0] and [index+2;detectFlip+2] intersect themselves.
  46989. // 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
  46990. if (detectFlip !== undefined) {
  46991. // Flip if intersect
  46992. var flipOff = detectFlip * (borderMode ? 8 : 4);
  46993. 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])) {
  46994. swap = true;
  46995. var tps = array[off + 0];
  46996. array[off + 0] = array[off + 2];
  46997. array[off + 2] = tps;
  46998. tps = array[off + 1];
  46999. array[off + 1] = array[off + 3];
  47000. array[off + 3] = tps;
  47001. }
  47002. }
  47003. if (borderMode) {
  47004. var t = halfThickness + borderThickness;
  47005. array[off + 4] = p.x + n.x * (swap ? -t : t);
  47006. array[off + 5] = p.y + n.y * (swap ? -t : t);
  47007. array[off + 6] = p.x + n.x * (swap ? t : -t);
  47008. array[off + 7] = p.y + n.y * (swap ? t : -t);
  47009. this._updateMinMax(array, off + 4);
  47010. this._updateMinMax(array, off + 6);
  47011. }
  47012. if (contour) {
  47013. off += borderMode ? 4 : 0;
  47014. contour.push(new BABYLON.Vector2(array[off + 0], array[off + 1]));
  47015. contour.push(new BABYLON.Vector2(array[off + 2], array[off + 3]));
  47016. }
  47017. };
  47018. Lines2D.prototype._getCapSize = function (type, border) {
  47019. if (border === void 0) { border = false; }
  47020. var sd = Lines2D._roundCapSubDiv;
  47021. // If no array given, we call this to get the size
  47022. var vbsize = 0, ibsize = 0;
  47023. switch (type) {
  47024. case Lines2D.NoCap:
  47025. {
  47026. // If the line is not close and we're computing border, we add the size to generate the edge border
  47027. if (!this.closed && border) {
  47028. vbsize = 4;
  47029. ibsize = 6;
  47030. }
  47031. else {
  47032. vbsize = ibsize = 0;
  47033. }
  47034. break;
  47035. }
  47036. case Lines2D.RoundCap:
  47037. {
  47038. if (border) {
  47039. vbsize = sd;
  47040. ibsize = (sd - 2) * 3;
  47041. }
  47042. else {
  47043. vbsize = (sd / 2) + 1;
  47044. ibsize = (sd / 2) * 3;
  47045. }
  47046. break;
  47047. }
  47048. case Lines2D.ArrowCap:
  47049. {
  47050. if (border) {
  47051. vbsize = 12;
  47052. ibsize = 24;
  47053. }
  47054. else {
  47055. vbsize = 3;
  47056. ibsize = 3;
  47057. }
  47058. break;
  47059. }
  47060. case Lines2D.TriangleCap:
  47061. {
  47062. if (border) {
  47063. vbsize = 6;
  47064. ibsize = 12;
  47065. }
  47066. else {
  47067. vbsize = 3;
  47068. ibsize = 3;
  47069. }
  47070. break;
  47071. }
  47072. case Lines2D.DiamondAnchorCap:
  47073. {
  47074. if (border) {
  47075. vbsize = 10;
  47076. ibsize = 24;
  47077. }
  47078. else {
  47079. vbsize = 5;
  47080. ibsize = 9;
  47081. }
  47082. break;
  47083. }
  47084. case Lines2D.SquareAnchorCap:
  47085. {
  47086. if (border) {
  47087. vbsize = 12;
  47088. ibsize = 30;
  47089. }
  47090. else {
  47091. vbsize = 4;
  47092. ibsize = 6;
  47093. }
  47094. break;
  47095. }
  47096. case Lines2D.RoundAnchorCap:
  47097. {
  47098. if (border) {
  47099. vbsize = sd * 2;
  47100. ibsize = (sd - 1) * 6;
  47101. }
  47102. else {
  47103. vbsize = sd + 1;
  47104. ibsize = (sd + 1) * 3;
  47105. }
  47106. break;
  47107. }
  47108. }
  47109. return { vbsize: vbsize * 2, ibsize: ibsize };
  47110. };
  47111. Lines2D.prototype._storeVertex = function (vb, baseOffset, index, basePos, rotation, vertex, contour) {
  47112. var c = Math.cos(rotation);
  47113. var s = Math.sin(rotation);
  47114. Lines2D._tpsV.x = (c * vertex.x) + (-s * vertex.y) + basePos.x;
  47115. Lines2D._tpsV.y = (s * vertex.x) + (c * vertex.y) + basePos.y;
  47116. var offset = baseOffset + (index * 2);
  47117. vb[offset + 0] = Lines2D._tpsV.x;
  47118. vb[offset + 1] = Lines2D._tpsV.y;
  47119. if (contour) {
  47120. contour.push(Lines2D._tpsV.x);
  47121. contour.push(Lines2D._tpsV.y);
  47122. }
  47123. this._updateMinMax(vb, offset);
  47124. return (baseOffset + index * 2) / 2;
  47125. };
  47126. Lines2D.prototype._storeIndex = function (ib, baseOffset, index, vertexIndex) {
  47127. ib[baseOffset + index] = vertexIndex;
  47128. };
  47129. Lines2D.prototype._buildCap = function (vb, vbi, ib, ibi, pos, thickness, borderThickness, type, capDir, contour) {
  47130. // 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
  47131. var sd = Lines2D._roundCapSubDiv;
  47132. var dir = new BABYLON.Vector2(1, 0);
  47133. var angle = Math.atan2(capDir.y, capDir.x) - Math.atan2(dir.y, dir.x);
  47134. var ht = thickness / 2;
  47135. var t = thickness;
  47136. var borderMode = borderThickness != null;
  47137. var bt = borderThickness;
  47138. switch (type) {
  47139. case Lines2D.NoCap:
  47140. if (borderMode && !this.closed) {
  47141. var vi = 0;
  47142. var ii = 0;
  47143. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), contour);
  47144. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, ht + bt), contour);
  47145. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, -(ht + bt)), contour);
  47146. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), contour);
  47147. this._storeIndex(ib, ibi, ii++, v1);
  47148. this._storeIndex(ib, ibi, ii++, v2);
  47149. this._storeIndex(ib, ibi, ii++, v3);
  47150. this._storeIndex(ib, ibi, ii++, v1);
  47151. this._storeIndex(ib, ibi, ii++, v3);
  47152. this._storeIndex(ib, ibi, ii++, v4);
  47153. }
  47154. break;
  47155. case Lines2D.ArrowCap:
  47156. ht *= 2;
  47157. case Lines2D.TriangleCap:
  47158. {
  47159. if (borderMode) {
  47160. var f = type === Lines2D.TriangleCap ? bt : Math.sqrt(bt * bt * 2);
  47161. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), null);
  47162. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), null);
  47163. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), null);
  47164. var v4 = this._storeVertex(vb, vbi, 3, pos, angle, new BABYLON.Vector2(0, ht + f), contour);
  47165. var v5 = this._storeVertex(vb, vbi, 4, pos, angle, new BABYLON.Vector2(ht + f, 0), contour);
  47166. var v6 = this._storeVertex(vb, vbi, 5, pos, angle, new BABYLON.Vector2(0, -(ht + f)), contour);
  47167. var ii = 0;
  47168. this._storeIndex(ib, ibi, ii++, v1);
  47169. this._storeIndex(ib, ibi, ii++, v4);
  47170. this._storeIndex(ib, ibi, ii++, v5);
  47171. this._storeIndex(ib, ibi, ii++, v1);
  47172. this._storeIndex(ib, ibi, ii++, v5);
  47173. this._storeIndex(ib, ibi, ii++, v2);
  47174. this._storeIndex(ib, ibi, ii++, v6);
  47175. this._storeIndex(ib, ibi, ii++, v3);
  47176. this._storeIndex(ib, ibi, ii++, v2);
  47177. this._storeIndex(ib, ibi, ii++, v6);
  47178. this._storeIndex(ib, ibi, ii++, v2);
  47179. this._storeIndex(ib, ibi, ii++, v5);
  47180. if (type === Lines2D.ArrowCap) {
  47181. var rht = thickness / 2;
  47182. var v10 = this._storeVertex(vb, vbi, 9, pos, angle, new BABYLON.Vector2(0, -(rht + bt)), null);
  47183. var v12 = this._storeVertex(vb, vbi, 11, pos, angle, new BABYLON.Vector2(-bt, -(ht + f)), contour);
  47184. var v11 = this._storeVertex(vb, vbi, 10, pos, angle, new BABYLON.Vector2(-bt, -(rht + bt)), contour);
  47185. var v7 = this._storeVertex(vb, vbi, 6, pos, angle, new BABYLON.Vector2(0, rht + bt), null);
  47186. var v8 = this._storeVertex(vb, vbi, 7, pos, angle, new BABYLON.Vector2(-bt, rht + bt), contour);
  47187. var v9 = this._storeVertex(vb, vbi, 8, pos, angle, new BABYLON.Vector2(-bt, ht + f), contour);
  47188. this._storeIndex(ib, ibi, ii++, v7);
  47189. this._storeIndex(ib, ibi, ii++, v8);
  47190. this._storeIndex(ib, ibi, ii++, v9);
  47191. this._storeIndex(ib, ibi, ii++, v7);
  47192. this._storeIndex(ib, ibi, ii++, v9);
  47193. this._storeIndex(ib, ibi, ii++, v4);
  47194. this._storeIndex(ib, ibi, ii++, v10);
  47195. this._storeIndex(ib, ibi, ii++, v12);
  47196. this._storeIndex(ib, ibi, ii++, v11);
  47197. this._storeIndex(ib, ibi, ii++, v10);
  47198. this._storeIndex(ib, ibi, ii++, v6);
  47199. this._storeIndex(ib, ibi, ii++, v12);
  47200. }
  47201. }
  47202. else {
  47203. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), contour);
  47204. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), contour);
  47205. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), contour);
  47206. this._storeIndex(ib, ibi, 0, v1);
  47207. this._storeIndex(ib, ibi, 1, v2);
  47208. this._storeIndex(ib, ibi, 2, v3);
  47209. }
  47210. break;
  47211. }
  47212. case Lines2D.RoundCap:
  47213. {
  47214. if (borderMode) {
  47215. var curA = -Math.PI / 2;
  47216. var incA = Math.PI / (sd / 2 - 1);
  47217. var ii = 0;
  47218. for (var i = 0; i < (sd / 2); i++) {
  47219. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  47220. 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);
  47221. if (i > 0) {
  47222. this._storeIndex(ib, ibi, ii++, v1 - 2);
  47223. this._storeIndex(ib, ibi, ii++, v2 - 2);
  47224. this._storeIndex(ib, ibi, ii++, v2);
  47225. this._storeIndex(ib, ibi, ii++, v1 - 2);
  47226. this._storeIndex(ib, ibi, ii++, v2);
  47227. this._storeIndex(ib, ibi, ii++, v1);
  47228. }
  47229. curA += incA;
  47230. }
  47231. }
  47232. else {
  47233. var c = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, 0), null);
  47234. var curA = -Math.PI / 2;
  47235. var incA = Math.PI / (sd / 2 - 1);
  47236. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  47237. curA += incA;
  47238. for (var i = 1; i < (sd / 2); i++) {
  47239. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), contour);
  47240. this._storeIndex(ib, ibi, i * 3 + 0, c);
  47241. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  47242. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  47243. curA += incA;
  47244. }
  47245. }
  47246. break;
  47247. }
  47248. case Lines2D.SquareAnchorCap:
  47249. {
  47250. var vi = 0;
  47251. var c = borderMode ? null : contour;
  47252. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, t), c);
  47253. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, t), c);
  47254. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, -t), c);
  47255. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -t), c);
  47256. if (borderMode) {
  47257. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), null);
  47258. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, ht + bt), contour);
  47259. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, t + bt), contour);
  47260. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, t + bt), contour);
  47261. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, -(t + bt)), contour);
  47262. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(t + bt)), contour);
  47263. var v11 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(ht + bt)), contour);
  47264. var v12 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), null);
  47265. var ii = 0;
  47266. this._storeIndex(ib, ibi, ii++, v6);
  47267. this._storeIndex(ib, ibi, ii++, v1);
  47268. this._storeIndex(ib, ibi, ii++, v5);
  47269. this._storeIndex(ib, ibi, ii++, v6);
  47270. this._storeIndex(ib, ibi, ii++, v7);
  47271. this._storeIndex(ib, ibi, ii++, v1);
  47272. this._storeIndex(ib, ibi, ii++, v1);
  47273. this._storeIndex(ib, ibi, ii++, v7);
  47274. this._storeIndex(ib, ibi, ii++, v8);
  47275. this._storeIndex(ib, ibi, ii++, v1);
  47276. this._storeIndex(ib, ibi, ii++, v8);
  47277. this._storeIndex(ib, ibi, ii++, v2);
  47278. this._storeIndex(ib, ibi, ii++, v2);
  47279. this._storeIndex(ib, ibi, ii++, v8);
  47280. this._storeIndex(ib, ibi, ii++, v9);
  47281. this._storeIndex(ib, ibi, ii++, v2);
  47282. this._storeIndex(ib, ibi, ii++, v9);
  47283. this._storeIndex(ib, ibi, ii++, v3);
  47284. this._storeIndex(ib, ibi, ii++, v3);
  47285. this._storeIndex(ib, ibi, ii++, v9);
  47286. this._storeIndex(ib, ibi, ii++, v10);
  47287. this._storeIndex(ib, ibi, ii++, v3);
  47288. this._storeIndex(ib, ibi, ii++, v10);
  47289. this._storeIndex(ib, ibi, ii++, v4);
  47290. this._storeIndex(ib, ibi, ii++, v10);
  47291. this._storeIndex(ib, ibi, ii++, v11);
  47292. this._storeIndex(ib, ibi, ii++, v4);
  47293. this._storeIndex(ib, ibi, ii++, v11);
  47294. this._storeIndex(ib, ibi, ii++, v12);
  47295. this._storeIndex(ib, ibi, ii++, v4);
  47296. }
  47297. else {
  47298. this._storeIndex(ib, ibi, 0, v1);
  47299. this._storeIndex(ib, ibi, 1, v2);
  47300. this._storeIndex(ib, ibi, 2, v3);
  47301. this._storeIndex(ib, ibi, 3, v1);
  47302. this._storeIndex(ib, ibi, 4, v3);
  47303. this._storeIndex(ib, ibi, 5, v4);
  47304. }
  47305. break;
  47306. }
  47307. case Lines2D.RoundAnchorCap:
  47308. {
  47309. var cpos = Math.sqrt(t * t - ht * ht);
  47310. var center = new BABYLON.Vector2(cpos, 0);
  47311. var curA = BABYLON.Tools.ToRadians(-150);
  47312. var incA = BABYLON.Tools.ToRadians(300) / (sd - 1);
  47313. if (borderMode) {
  47314. var ii = 0;
  47315. for (var i = 0; i < sd; i++) {
  47316. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  47317. 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);
  47318. if (i > 0) {
  47319. this._storeIndex(ib, ibi, ii++, v1 - 2);
  47320. this._storeIndex(ib, ibi, ii++, v2 - 2);
  47321. this._storeIndex(ib, ibi, ii++, v2);
  47322. this._storeIndex(ib, ibi, ii++, v1 - 2);
  47323. this._storeIndex(ib, ibi, ii++, v2);
  47324. this._storeIndex(ib, ibi, ii++, v1);
  47325. }
  47326. curA += incA;
  47327. }
  47328. }
  47329. else {
  47330. var c = this._storeVertex(vb, vbi, 0, pos, angle, center, null);
  47331. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  47332. curA += incA;
  47333. for (var i = 1; i < sd; i++) {
  47334. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), contour);
  47335. this._storeIndex(ib, ibi, i * 3 + 0, c);
  47336. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  47337. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  47338. curA += incA;
  47339. }
  47340. this._storeIndex(ib, ibi, sd * 3 + 0, c);
  47341. this._storeIndex(ib, ibi, sd * 3 + 1, c + 1);
  47342. this._storeIndex(ib, ibi, sd * 3 + 2, c + sd);
  47343. }
  47344. break;
  47345. }
  47346. case Lines2D.DiamondAnchorCap:
  47347. {
  47348. var vi = 0;
  47349. var c = borderMode ? null : contour;
  47350. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht), c);
  47351. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t), c);
  47352. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3, 0), c);
  47353. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -t), c);
  47354. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -ht), c);
  47355. if (borderMode) {
  47356. var f = Math.sqrt(bt * bt * 2);
  47357. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, ht), contour);
  47358. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t + f), contour);
  47359. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3 + f, 0), contour);
  47360. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -(t + f)), contour);
  47361. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, -ht), contour);
  47362. var ii = 0;
  47363. this._storeIndex(ib, ibi, ii++, v6);
  47364. this._storeIndex(ib, ibi, ii++, v7);
  47365. this._storeIndex(ib, ibi, ii++, v1);
  47366. this._storeIndex(ib, ibi, ii++, v1);
  47367. this._storeIndex(ib, ibi, ii++, v7);
  47368. this._storeIndex(ib, ibi, ii++, v2);
  47369. this._storeIndex(ib, ibi, ii++, v2);
  47370. this._storeIndex(ib, ibi, ii++, v7);
  47371. this._storeIndex(ib, ibi, ii++, v8);
  47372. this._storeIndex(ib, ibi, ii++, v2);
  47373. this._storeIndex(ib, ibi, ii++, v8);
  47374. this._storeIndex(ib, ibi, ii++, v3);
  47375. this._storeIndex(ib, ibi, ii++, v3);
  47376. this._storeIndex(ib, ibi, ii++, v8);
  47377. this._storeIndex(ib, ibi, ii++, v9);
  47378. this._storeIndex(ib, ibi, ii++, v3);
  47379. this._storeIndex(ib, ibi, ii++, v9);
  47380. this._storeIndex(ib, ibi, ii++, v4);
  47381. this._storeIndex(ib, ibi, ii++, v4);
  47382. this._storeIndex(ib, ibi, ii++, v9);
  47383. this._storeIndex(ib, ibi, ii++, v10);
  47384. this._storeIndex(ib, ibi, ii++, v4);
  47385. this._storeIndex(ib, ibi, ii++, v10);
  47386. this._storeIndex(ib, ibi, ii++, v5);
  47387. }
  47388. else {
  47389. this._storeIndex(ib, ibi, 0, v1);
  47390. this._storeIndex(ib, ibi, 1, v2);
  47391. this._storeIndex(ib, ibi, 2, v3);
  47392. this._storeIndex(ib, ibi, 3, v1);
  47393. this._storeIndex(ib, ibi, 4, v3);
  47394. this._storeIndex(ib, ibi, 5, v5);
  47395. this._storeIndex(ib, ibi, 6, v5);
  47396. this._storeIndex(ib, ibi, 7, v3);
  47397. this._storeIndex(ib, ibi, 8, v4);
  47398. }
  47399. break;
  47400. }
  47401. }
  47402. return null;
  47403. };
  47404. Lines2D.prototype._buildLine = function (vb, contour, ht, bt) {
  47405. var lineA = BABYLON.Vector2.Zero();
  47406. var lineB = BABYLON.Vector2.Zero();
  47407. var tangent = BABYLON.Vector2.Zero();
  47408. var miter = BABYLON.Vector2.Zero();
  47409. var curNormal = null;
  47410. if (this.closed) {
  47411. this.points.push(this.points[0]);
  47412. }
  47413. var total = this.points.length;
  47414. for (var i = 1; i < total; i++) {
  47415. var last = this.points[i - 1];
  47416. var cur = this.points[i];
  47417. var next = (i < (this.points.length - 1)) ? this.points[i + 1] : null;
  47418. this._direction(cur, last, lineA);
  47419. if (!curNormal) {
  47420. curNormal = BABYLON.Vector2.Zero();
  47421. this._perp(lineA, curNormal);
  47422. }
  47423. if (i === 1) {
  47424. this._store(vb, contour, 0, total, this.points[0], curNormal, ht, bt);
  47425. }
  47426. if (!next) {
  47427. this._perp(lineA, curNormal);
  47428. this._store(vb, contour, i, total, this.points[i], curNormal, ht, bt, i - 1);
  47429. }
  47430. else {
  47431. this._direction(next, cur, lineB);
  47432. var miterLen = this._computeMiter(tangent, miter, lineA, lineB);
  47433. this._store(vb, contour, i, total, this.points[i], miter, miterLen * ht, miterLen * bt, i - 1);
  47434. }
  47435. }
  47436. if (this.points.length > 2 && this.closed) {
  47437. var last2 = this.points[total - 2];
  47438. var cur2 = this.points[0];
  47439. var next2 = this.points[1];
  47440. this._direction(cur2, last2, lineA);
  47441. this._direction(next2, cur2, lineB);
  47442. this._perp(lineA, curNormal);
  47443. var miterLen2 = this._computeMiter(tangent, miter, lineA, lineB);
  47444. this._store(vb, null, 0, total, this.points[0], miter, miterLen2 * ht, miterLen2 * bt, 1);
  47445. // Patch contour
  47446. if (contour) {
  47447. var off = (bt == null) ? 0 : 4;
  47448. contour[0].x = vb[off + 0];
  47449. contour[0].y = vb[off + 1];
  47450. contour[1].x = vb[off + 2];
  47451. contour[1].y = vb[off + 3];
  47452. }
  47453. }
  47454. // Remove the point we added at the beginning
  47455. if (this.closed) {
  47456. this.points.splice(total - 1);
  47457. }
  47458. };
  47459. // Methods for Lines building
  47460. ///////////////////////////////////////////////////////////////////////////////////
  47461. Lines2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  47462. var renderCache = modelRenderCache;
  47463. var engine = this.owner.engine;
  47464. if (this._fillVB === null) {
  47465. this._computeLines2D();
  47466. }
  47467. // Need to create WebGL resources for fill part?
  47468. if (this.fill) {
  47469. renderCache.fillVB = engine.createVertexBuffer(this._fillVB);
  47470. renderCache.fillIB = engine.createIndexBuffer(this._fillIB);
  47471. renderCache.fillIndicesCount = this._fillIB.length;
  47472. // 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
  47473. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, true);
  47474. if (ei) {
  47475. renderCache.effectFillInstanced = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  47476. }
  47477. // Get the non instanced version
  47478. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, false);
  47479. renderCache.effectFill = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  47480. }
  47481. // Need to create WebGL resources for border part?
  47482. if (this.border) {
  47483. renderCache.borderVB = engine.createVertexBuffer(this._borderVB);
  47484. renderCache.borderIB = engine.createIndexBuffer(this._borderIB);
  47485. renderCache.borderIndicesCount = this._borderIB.length;
  47486. // 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
  47487. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, true);
  47488. if (ei) {
  47489. renderCache.effectBorderInstanced = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  47490. }
  47491. // Get the non instanced version
  47492. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, false);
  47493. renderCache.effectBorder = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  47494. }
  47495. this._fillVB = null;
  47496. this._fillIB = null;
  47497. this._borderVB = null;
  47498. this._borderIB = null;
  47499. return renderCache;
  47500. };
  47501. Lines2D.prototype._computeLines2D = function () {
  47502. // Init min/max because their being computed here
  47503. this._boundingMin = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  47504. this._boundingMax = new BABYLON.Vector2(Number.MIN_VALUE, Number.MIN_VALUE);
  47505. var contour = new Array();
  47506. var startCapContour = new Array();
  47507. var endCapContour = new Array();
  47508. // Need to create WebGL resources for fill part?
  47509. if (this.fill) {
  47510. var startCapInfo = this._getCapSize(this.startCap);
  47511. var endCapInfo = this._getCapSize(this.endCap);
  47512. var count = this.points.length;
  47513. var vbSize = (count * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  47514. this._fillVB = new Float32Array(vbSize);
  47515. var vb = this._fillVB;
  47516. var ht = this.fillThickness / 2;
  47517. var total = this.points.length;
  47518. this._buildLine(vb, this.border ? null : contour, ht);
  47519. var max = total * 2;
  47520. var triCount = (count - (this.closed ? 0 : 1)) * 2;
  47521. this._fillIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  47522. var ib = this._fillIB;
  47523. for (var i = 0; i < triCount; i += 2) {
  47524. ib[i * 3 + 0] = i + 0;
  47525. ib[i * 3 + 1] = i + 1;
  47526. ib[i * 3 + 2] = (i + 2) % max;
  47527. ib[i * 3 + 3] = i + 1;
  47528. ib[i * 3 + 4] = (i + 3) % max;
  47529. ib[i * 3 + 5] = (i + 2) % max;
  47530. }
  47531. this._buildCap(vb, count * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, null, this.startCap, Lines2D._startDir, this.border ? null : startCapContour);
  47532. 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);
  47533. }
  47534. // Need to create WebGL resources for border part?
  47535. if (this.border) {
  47536. var startCapInfo = this._getCapSize(this.startCap, true);
  47537. var endCapInfo = this._getCapSize(this.endCap, true);
  47538. var count = this.points.length;
  47539. var vbSize = (count * 2 * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  47540. this._borderVB = new Float32Array(vbSize);
  47541. var vb = this._borderVB;
  47542. var ht = this.fillThickness / 2;
  47543. var bt = this.borderThickness;
  47544. var total = this.points.length;
  47545. this._buildLine(vb, contour, ht, bt);
  47546. var max = total * 2 * 2;
  47547. var triCount = (count - (this.closed ? 0 : 1)) * 2 * 2;
  47548. this._borderIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  47549. var ib = this._borderIB;
  47550. for (var i = 0; i < triCount; i += 4) {
  47551. ib[i * 3 + 0] = i + 0;
  47552. ib[i * 3 + 1] = i + 2;
  47553. ib[i * 3 + 2] = (i + 6) % max;
  47554. ib[i * 3 + 3] = i + 0;
  47555. ib[i * 3 + 4] = (i + 6) % max;
  47556. ib[i * 3 + 5] = (i + 4) % max;
  47557. ib[i * 3 + 6] = i + 3;
  47558. ib[i * 3 + 7] = i + 1;
  47559. ib[i * 3 + 8] = (i + 5) % max;
  47560. ib[i * 3 + 9] = i + 3;
  47561. ib[i * 3 + 10] = (i + 5) % max;
  47562. ib[i * 3 + 11] = (i + 7) % max;
  47563. }
  47564. this._buildCap(vb, count * 2 * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, this.borderThickness, this.startCap, Lines2D._startDir, startCapContour);
  47565. 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);
  47566. }
  47567. this._contour = contour;
  47568. if (startCapContour.length > 0) {
  47569. var startCapTri = Earcut.earcut(startCapContour, null, 2);
  47570. this._startCapTriIndices = startCapTri;
  47571. this._startCapContour = startCapContour;
  47572. }
  47573. else {
  47574. this._startCapTriIndices = null;
  47575. this._startCapContour = null;
  47576. }
  47577. if (endCapContour.length > 0) {
  47578. var endCapTri = Earcut.earcut(endCapContour, null, 2);
  47579. this._endCapContour = endCapContour;
  47580. this._endCapTriIndices = endCapTri;
  47581. }
  47582. else {
  47583. this._endCapContour = null;
  47584. this._endCapTriIndices = null;
  47585. }
  47586. var bs = this._boundingMax.subtract(this._boundingMin);
  47587. this._size.width = bs.x;
  47588. this._size.height = bs.y;
  47589. };
  47590. Object.defineProperty(Lines2D.prototype, "size", {
  47591. get: function () {
  47592. if (this._size == null) {
  47593. this._computeLines2D();
  47594. }
  47595. return this._size;
  47596. },
  47597. enumerable: true,
  47598. configurable: true
  47599. });
  47600. Lines2D.prototype.createInstanceDataParts = function () {
  47601. var res = new Array();
  47602. if (this.border) {
  47603. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  47604. }
  47605. if (this.fill) {
  47606. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  47607. }
  47608. return res;
  47609. };
  47610. Lines2D.prototype.applyActualScaleOnTransform = function () {
  47611. return true;
  47612. };
  47613. Lines2D.prototype.refreshInstanceDataPart = function (part) {
  47614. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  47615. return false;
  47616. }
  47617. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  47618. var d = part;
  47619. if (this.border instanceof BABYLON.GradientColorBrush2D) {
  47620. d.boundingMin = this.boundingMin;
  47621. d.boundingMax = this.boundingMax;
  47622. }
  47623. }
  47624. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  47625. var d = part;
  47626. if (this.fill instanceof BABYLON.GradientColorBrush2D) {
  47627. d.boundingMin = this.boundingMin;
  47628. d.boundingMax = this.boundingMax;
  47629. }
  47630. }
  47631. return true;
  47632. };
  47633. Lines2D._prevA = BABYLON.Vector2.Zero();
  47634. Lines2D._prevB = BABYLON.Vector2.Zero();
  47635. Lines2D._curA = BABYLON.Vector2.Zero();
  47636. Lines2D._curB = BABYLON.Vector2.Zero();
  47637. Lines2D._miterTps = BABYLON.Vector2.Zero();
  47638. Lines2D._startDir = BABYLON.Vector2.Zero();
  47639. Lines2D._endDir = BABYLON.Vector2.Zero();
  47640. Lines2D._tpsV = BABYLON.Vector2.Zero();
  47641. Lines2D._noCap = 0;
  47642. Lines2D._roundCap = 1;
  47643. Lines2D._triangleCap = 2;
  47644. Lines2D._squareAnchorCap = 3;
  47645. Lines2D._roundAnchorCap = 4;
  47646. Lines2D._diamondAnchorCap = 5;
  47647. Lines2D._arrowCap = 6;
  47648. Lines2D._roundCapSubDiv = 36;
  47649. __decorate([
  47650. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Lines2D.pointsProperty = pi; })
  47651. ], Lines2D.prototype, "points", null);
  47652. __decorate([
  47653. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Lines2D.fillThicknessProperty = pi; })
  47654. ], Lines2D.prototype, "fillThickness", null);
  47655. __decorate([
  47656. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Lines2D.closedProperty = pi; })
  47657. ], Lines2D.prototype, "closed", null);
  47658. __decorate([
  47659. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 4, function (pi) { return Lines2D.startCapProperty = pi; })
  47660. ], Lines2D.prototype, "startCap", null);
  47661. __decorate([
  47662. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 5, function (pi) { return Lines2D.endCapProperty = pi; })
  47663. ], Lines2D.prototype, "endCap", null);
  47664. Lines2D = __decorate([
  47665. BABYLON.className("Lines2D")
  47666. ], Lines2D);
  47667. return Lines2D;
  47668. })(BABYLON.Shape2D);
  47669. BABYLON.Lines2D = Lines2D;
  47670. })(BABYLON || (BABYLON = {}));
  47671. var BABYLON;
  47672. (function (BABYLON) {
  47673. // This class contains data that lifetime is bounding to the Babylon Engine object
  47674. var Canvas2DEngineBoundData = (function () {
  47675. function Canvas2DEngineBoundData() {
  47676. this._modelCache = new BABYLON.StringDictionary();
  47677. }
  47678. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  47679. return this._modelCache.getOrAddWithFactory(key, factory);
  47680. };
  47681. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  47682. if (!modelRenderCache.isDisposed) {
  47683. return false;
  47684. }
  47685. this._modelCache.remove(modelRenderCache.modelKey);
  47686. return true;
  47687. };
  47688. return Canvas2DEngineBoundData;
  47689. })();
  47690. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  47691. var Canvas2D = (function (_super) {
  47692. __extends(Canvas2D, _super);
  47693. function Canvas2D(scene, settings) {
  47694. var _this = this;
  47695. _super.call(this, settings);
  47696. /**
  47697. * 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.
  47698. * Beware that you have to take under consideration the origin in your calculations! Good luck!
  47699. */
  47700. this.worldSpaceToNodeLocal = function (worldPos) {
  47701. var node = _this._worldSpaceNode;
  47702. if (!node) {
  47703. return;
  47704. }
  47705. var mtx = node.getWorldMatrix().clone();
  47706. mtx.invert();
  47707. var v = BABYLON.Vector3.TransformCoordinates(worldPos, mtx);
  47708. var res = new BABYLON.Vector2(v.x, v.y);
  47709. var size = _this.actualSize;
  47710. res.x += size.width * 0.5; // res is centered, make it relative to bottom/left
  47711. res.y += size.height * 0.5;
  47712. return res;
  47713. };
  47714. /**
  47715. * 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
  47716. */
  47717. this.worldSpaceCacheChanged = function () {
  47718. var plane = _this.worldSpaceCanvasNode;
  47719. var vd = BABYLON.VertexData.ExtractFromMesh(plane); //new VertexData();
  47720. vd.uvs = new Float32Array(8);
  47721. var material = plane.material;
  47722. var tex = _this._renderableData._cacheTexture;
  47723. if (material.diffuseTexture !== tex) {
  47724. material.diffuseTexture = tex;
  47725. tex.hasAlpha = true;
  47726. }
  47727. var nodeuv = _this._renderableData._cacheNodeUVs;
  47728. for (var i = 0; i < 4; i++) {
  47729. vd.uvs[i * 2 + 0] = nodeuv[i].x;
  47730. vd.uvs[i * 2 + 1] = nodeuv[i].y;
  47731. }
  47732. vd.applyToMesh(plane);
  47733. };
  47734. this._notifDebugMode = false;
  47735. this._mapCounter = 0;
  47736. this._drawCallsOpaqueCounter = new BABYLON.PerfCounter();
  47737. this._drawCallsAlphaTestCounter = new BABYLON.PerfCounter();
  47738. this._drawCallsTransparentCounter = new BABYLON.PerfCounter();
  47739. this._groupRenderCounter = new BABYLON.PerfCounter();
  47740. this._updateTransparentDataCounter = new BABYLON.PerfCounter();
  47741. this._cachedGroupRenderCounter = new BABYLON.PerfCounter();
  47742. this._updateCachedStateCounter = new BABYLON.PerfCounter();
  47743. this._updateLayoutCounter = new BABYLON.PerfCounter();
  47744. this._updatePositioningCounter = new BABYLON.PerfCounter();
  47745. this._updateLocalTransformCounter = new BABYLON.PerfCounter();
  47746. this._updateGlobalTransformCounter = new BABYLON.PerfCounter();
  47747. this._boundingInfoRecomputeCounter = new BABYLON.PerfCounter();
  47748. this._cachedCanvasGroup = null;
  47749. this._profileInfoText = null;
  47750. BABYLON.Prim2DBase._isCanvasInit = false;
  47751. if (!settings) {
  47752. settings = {};
  47753. }
  47754. if (this._cachingStrategy !== Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  47755. this._background = new BABYLON.Rectangle2D({ parent: this, id: "###CANVAS BACKGROUND###", size: settings.size }); //TODO CHECK when size is null
  47756. this._background.zOrder = 1.0;
  47757. this._background.isPickable = false;
  47758. this._background.origin = BABYLON.Vector2.Zero();
  47759. this._background.levelVisible = false;
  47760. if (settings.backgroundRoundRadius != null) {
  47761. this.backgroundRoundRadius = settings.backgroundRoundRadius;
  47762. }
  47763. if (settings.backgroundBorder != null) {
  47764. if (typeof (settings.backgroundBorder) === "string") {
  47765. this.backgroundBorder = Canvas2D.GetBrushFromString(settings.backgroundBorder);
  47766. }
  47767. else {
  47768. this.backgroundBorder = settings.backgroundBorder;
  47769. }
  47770. }
  47771. if (settings.backgroundBorderThickNess != null) {
  47772. this.backgroundBorderThickness = settings.backgroundBorderThickNess;
  47773. }
  47774. if (settings.backgroundFill != null) {
  47775. if (typeof (settings.backgroundFill) === "string") {
  47776. this.backgroundFill = Canvas2D.GetBrushFromString(settings.backgroundFill);
  47777. }
  47778. else {
  47779. this.backgroundFill = settings.backgroundFill;
  47780. }
  47781. }
  47782. // Put a handler to resize the background whenever the canvas is resizing
  47783. this.propertyChanged.add(function (e, s) {
  47784. _this._background.size = _this.size;
  47785. }, BABYLON.Group2D.sizeProperty.flagId);
  47786. this._background._patchHierarchy(this);
  47787. }
  47788. var engine = scene.getEngine();
  47789. this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  47790. this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  47791. this._capturedPointers = new BABYLON.StringDictionary();
  47792. this._pickStartingPosition = BABYLON.Vector2.Zero();
  47793. this._hierarchyLevelMaxSiblingCount = 50;
  47794. this._hierarchyDepth = 0;
  47795. this._zOrder = 0;
  47796. this._zMax = 1;
  47797. this._scene = scene;
  47798. this._engine = engine;
  47799. this._renderingSize = new BABYLON.Size(0, 0);
  47800. this._designSize = settings.designSize || null;
  47801. this._designUseHorizAxis = settings.designUseHorizAxis === true;
  47802. this._trackedGroups = new Array();
  47803. this._maxAdaptiveWorldSpaceCanvasSize = null;
  47804. this._groupCacheMaps = new BABYLON.StringDictionary();
  47805. this._patchHierarchy(this);
  47806. var enableInteraction = (settings.enableInteraction == null) ? true : settings.enableInteraction;
  47807. this._fitRenderingDevice = !settings.size;
  47808. if (!settings.size) {
  47809. settings.size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  47810. }
  47811. // Register scene dispose to also dispose the canvas when it'll happens
  47812. scene.onDisposeObservable.add(function (d, s) {
  47813. _this.dispose();
  47814. });
  47815. if (this._isScreenSpace) {
  47816. this._afterRenderObserver = this._scene.onAfterRenderObservable.add(function (d, s) {
  47817. _this._engine.clear(null, false, true, true);
  47818. _this._render();
  47819. });
  47820. }
  47821. else {
  47822. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function (d, s) {
  47823. _this._render();
  47824. });
  47825. }
  47826. this._supprtInstancedArray = this._engine.getCaps().instancedArrays !== null;
  47827. //this._supprtInstancedArray = false; // TODO REMOVE!!!
  47828. this._setupInteraction(enableInteraction);
  47829. }
  47830. Object.defineProperty(Canvas2D.prototype, "drawCallsOpaqueCounter", {
  47831. get: function () {
  47832. return this._drawCallsOpaqueCounter;
  47833. },
  47834. enumerable: true,
  47835. configurable: true
  47836. });
  47837. Object.defineProperty(Canvas2D.prototype, "drawCallsAlphaTestCounter", {
  47838. get: function () {
  47839. return this._drawCallsAlphaTestCounter;
  47840. },
  47841. enumerable: true,
  47842. configurable: true
  47843. });
  47844. Object.defineProperty(Canvas2D.prototype, "drawCallsTransparentCounter", {
  47845. get: function () {
  47846. return this._drawCallsTransparentCounter;
  47847. },
  47848. enumerable: true,
  47849. configurable: true
  47850. });
  47851. Object.defineProperty(Canvas2D.prototype, "groupRenderCounter", {
  47852. get: function () {
  47853. return this._groupRenderCounter;
  47854. },
  47855. enumerable: true,
  47856. configurable: true
  47857. });
  47858. Object.defineProperty(Canvas2D.prototype, "updateTransparentDataCounter", {
  47859. get: function () {
  47860. return this._updateTransparentDataCounter;
  47861. },
  47862. enumerable: true,
  47863. configurable: true
  47864. });
  47865. Object.defineProperty(Canvas2D.prototype, "cachedGroupRenderCounter", {
  47866. get: function () {
  47867. return this._cachedGroupRenderCounter;
  47868. },
  47869. enumerable: true,
  47870. configurable: true
  47871. });
  47872. Object.defineProperty(Canvas2D.prototype, "updateCachedStateCounter", {
  47873. get: function () {
  47874. return this._updateCachedStateCounter;
  47875. },
  47876. enumerable: true,
  47877. configurable: true
  47878. });
  47879. Object.defineProperty(Canvas2D.prototype, "updateLayoutCounter", {
  47880. get: function () {
  47881. return this._updateLayoutCounter;
  47882. },
  47883. enumerable: true,
  47884. configurable: true
  47885. });
  47886. Object.defineProperty(Canvas2D.prototype, "updatePositioningCounter", {
  47887. get: function () {
  47888. return this._updatePositioningCounter;
  47889. },
  47890. enumerable: true,
  47891. configurable: true
  47892. });
  47893. Object.defineProperty(Canvas2D.prototype, "updateLocalTransformCounter", {
  47894. get: function () {
  47895. return this._updateLocalTransformCounter;
  47896. },
  47897. enumerable: true,
  47898. configurable: true
  47899. });
  47900. Object.defineProperty(Canvas2D.prototype, "updateGlobalTransformCounter", {
  47901. get: function () {
  47902. return this._updateGlobalTransformCounter;
  47903. },
  47904. enumerable: true,
  47905. configurable: true
  47906. });
  47907. Object.defineProperty(Canvas2D.prototype, "boundingInfoRecomputeCounter", {
  47908. get: function () {
  47909. return this._boundingInfoRecomputeCounter;
  47910. },
  47911. enumerable: true,
  47912. configurable: true
  47913. });
  47914. Canvas2D.prototype._canvasPreInit = function (settings) {
  47915. var cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_DONTCACHE : settings.cachingStrategy;
  47916. this._cachingStrategy = cachingStrategy;
  47917. this._isScreenSpace = (settings.isScreenSpace == null) ? true : settings.isScreenSpace;
  47918. };
  47919. Canvas2D.prototype._setupInteraction = function (enable) {
  47920. var _this = this;
  47921. // No change detection
  47922. if (enable === this._interactionEnabled) {
  47923. return;
  47924. }
  47925. // Set the new state
  47926. this._interactionEnabled = enable;
  47927. // ScreenSpace mode
  47928. if (this._isScreenSpace) {
  47929. // Disable interaction
  47930. if (!enable) {
  47931. if (this._scenePrePointerObserver) {
  47932. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  47933. this._scenePrePointerObserver = null;
  47934. }
  47935. return;
  47936. }
  47937. // Enable Interaction
  47938. // Register the observable
  47939. this._scenePrePointerObserver = this.scene.onPrePointerObservable.add(function (e, s) {
  47940. if (_this.isVisible === false) {
  47941. return;
  47942. }
  47943. var hs = 1 / _this.engine.getHardwareScalingLevel();
  47944. var localPos = e.localPosition.multiplyByFloats(hs, hs);
  47945. _this._handlePointerEventForInteraction(e, localPos, s);
  47946. });
  47947. }
  47948. else {
  47949. var scene = this.scene;
  47950. if (enable) {
  47951. scene.constantlyUpdateMeshUnderPointer = true;
  47952. this._scenePointerObserver = scene.onPointerObservable.add(function (e, s) {
  47953. if (_this.isVisible === false) {
  47954. return;
  47955. }
  47956. if (e.pickInfo.hit && e.pickInfo.pickedMesh === _this._worldSpaceNode && _this.worldSpaceToNodeLocal) {
  47957. var localPos = _this.worldSpaceToNodeLocal(e.pickInfo.pickedPoint);
  47958. _this._handlePointerEventForInteraction(e, localPos, s);
  47959. }
  47960. });
  47961. }
  47962. else {
  47963. if (this._scenePointerObserver) {
  47964. this.scene.onPointerObservable.remove(this._scenePointerObserver);
  47965. this._scenePointerObserver = null;
  47966. }
  47967. }
  47968. }
  47969. };
  47970. /**
  47971. * Internal method, you should use the Prim2DBase version instead
  47972. */
  47973. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  47974. if (this.isPointerCaptured(pointerId)) {
  47975. return false;
  47976. }
  47977. // Try to capture the pointer on the HTML side
  47978. try {
  47979. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  47980. }
  47981. catch (e) {
  47982. }
  47983. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  47984. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  47985. this._capturedPointers.add(pointerId.toString(), primitive);
  47986. return true;
  47987. };
  47988. /**
  47989. * Internal method, you should use the Prim2DBase version instead
  47990. */
  47991. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  47992. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  47993. return false;
  47994. }
  47995. // Try to release the pointer on the HTML side
  47996. try {
  47997. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  47998. }
  47999. catch (e) {
  48000. }
  48001. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  48002. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  48003. this._capturedPointers.remove(pointerId.toString());
  48004. return true;
  48005. };
  48006. /**
  48007. * Determine if the given pointer is captured or not
  48008. * @param pointerId the Id of the pointer
  48009. * @return true if it's captured, false otherwise
  48010. */
  48011. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  48012. return this._capturedPointers.contains(pointerId.toString());
  48013. };
  48014. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  48015. // Avoid unnecessary lookup
  48016. if (this._capturedPointers.count === 0) {
  48017. return null;
  48018. }
  48019. return this._capturedPointers.get(pointerId.toString());
  48020. };
  48021. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, localPosition, eventState) {
  48022. // Dispose check
  48023. if (this.isDisposed) {
  48024. return;
  48025. }
  48026. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  48027. if (!this._updatePointerInfo(eventData, localPosition)) {
  48028. return;
  48029. }
  48030. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  48031. // 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.
  48032. // 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.
  48033. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, capturedPrim !== null);
  48034. // 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
  48035. this._updateOverStatus();
  48036. // Check if we have nothing to raise
  48037. if (!this._actualOverPrimitive && !capturedPrim) {
  48038. return;
  48039. }
  48040. // Update the relatedTarget info with the over primitive or the captured one (if any)
  48041. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  48042. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  48043. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  48044. // Analyze the pointer event type and fire proper events on the primitive
  48045. var skip = false;
  48046. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  48047. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData);
  48048. }
  48049. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48050. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData);
  48051. }
  48052. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  48053. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData);
  48054. }
  48055. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  48056. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData);
  48057. }
  48058. eventState.skipNextObservers = skip;
  48059. };
  48060. Canvas2D.prototype._updatePointerInfo = function (eventData, localPosition) {
  48061. var s = this.scale;
  48062. var pii = this._primPointerInfo;
  48063. if (!pii.canvasPointerPos) {
  48064. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  48065. }
  48066. var camera = this._scene.cameraToUseForPointers || this._scene.activeCamera;
  48067. if (!camera || !camera.viewport) {
  48068. return false;
  48069. }
  48070. var engine = this._scene.getEngine();
  48071. if (this._isScreenSpace) {
  48072. var cameraViewport = camera.viewport;
  48073. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  48074. // Moving coordinates to local viewport world
  48075. var x = localPosition.x - viewport.x;
  48076. var y = localPosition.y - viewport.y;
  48077. pii.canvasPointerPos.x = (x - this.actualPosition.x) / s;
  48078. pii.canvasPointerPos.y = (engine.getRenderHeight() - y - this.actualPosition.y) / s;
  48079. }
  48080. else {
  48081. pii.canvasPointerPos.x = localPosition.x / s;
  48082. pii.canvasPointerPos.y = localPosition.y / s;
  48083. }
  48084. //console.log(`UpdatePointerInfo for ${this.id}, X:${pii.canvasPointerPos.x}, Y:${pii.canvasPointerPos.y}`);
  48085. pii.mouseWheelDelta = 0;
  48086. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  48087. var event = eventData.event;
  48088. if (event.wheelDelta) {
  48089. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  48090. }
  48091. else if (event.detail) {
  48092. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  48093. }
  48094. }
  48095. else {
  48096. var pe = eventData.event;
  48097. pii.ctrlKey = pe.ctrlKey;
  48098. pii.altKey = pe.altKey;
  48099. pii.shiftKey = pe.shiftKey;
  48100. pii.metaKey = pe.metaKey;
  48101. pii.button = pe.button;
  48102. pii.buttons = pe.buttons;
  48103. pii.pointerId = pe.pointerId;
  48104. pii.width = pe.width;
  48105. pii.height = pe.height;
  48106. pii.presssure = pe.pressure;
  48107. pii.tilt.x = pe.tiltX;
  48108. pii.tilt.y = pe.tiltY;
  48109. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  48110. }
  48111. return true;
  48112. };
  48113. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture) {
  48114. if (this.scene.getRenderId() === this._intersectionRenderId) {
  48115. return;
  48116. }
  48117. // 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
  48118. if (!this._globalTransform) {
  48119. this.updateCachedStates(true);
  48120. }
  48121. var ii = Canvas2D._interInfo;
  48122. ii.pickPosition.x = mouseLocalPos.x;
  48123. ii.pickPosition.y = mouseLocalPos.y;
  48124. ii.findFirstOnly = false;
  48125. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  48126. if (!isCapture && !this.levelBoundingInfo.doesIntersect(ii.pickPosition)) {
  48127. this._previousIntersectionList = this._actualIntersectionList;
  48128. this._actualIntersectionList = null;
  48129. this._previousOverPrimitive = this._actualOverPrimitive;
  48130. this._actualOverPrimitive = null;
  48131. return;
  48132. }
  48133. this.intersect(ii);
  48134. this._previousIntersectionList = this._actualIntersectionList;
  48135. this._actualIntersectionList = ii.intersectedPrimitives;
  48136. this._previousOverPrimitive = this._actualOverPrimitive;
  48137. this._actualOverPrimitive = ii.topMostIntersectedPrimitive;
  48138. this._intersectionRenderId = this.scene.getRenderId();
  48139. };
  48140. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  48141. Canvas2D.prototype._updateOverStatus = function () {
  48142. if ((this.scene.getRenderId() === this._hoverStatusRenderId) || !this._previousIntersectionList || !this._actualIntersectionList) {
  48143. return;
  48144. }
  48145. // Detect a change of over
  48146. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  48147. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  48148. if (prevPrim !== actualPrim) {
  48149. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  48150. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  48151. // Notify the previous "over" prim that the pointer is no longer over it
  48152. if ((capturedPrim && capturedPrim === prevPrim) || (!capturedPrim && prevPrim)) {
  48153. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  48154. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  48155. }
  48156. // Notify the new "over" prim that the pointer is over it
  48157. if ((capturedPrim && capturedPrim === actualPrim) || (!capturedPrim && actualPrim)) {
  48158. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  48159. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  48160. }
  48161. }
  48162. this._hoverStatusRenderId = this.scene.getRenderId();
  48163. };
  48164. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  48165. if (this._primPointerInfo.isCaptured) {
  48166. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  48167. }
  48168. else {
  48169. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  48170. var pii = _a[_i];
  48171. if (pii.prim === prim) {
  48172. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  48173. return;
  48174. }
  48175. }
  48176. }
  48177. };
  48178. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  48179. if (!this._notifDebugMode) {
  48180. return;
  48181. }
  48182. var debug = "";
  48183. for (var i = 0; i < prim.hierarchyDepth; i++) {
  48184. debug += " ";
  48185. }
  48186. var pii = this._primPointerInfo;
  48187. 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();
  48188. console.log(debug);
  48189. };
  48190. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  48191. var ppi = this._primPointerInfo;
  48192. var event = eventData ? eventData.event : null;
  48193. // In case of PointerOver/Out we will first notify the parent with PointerEnter/Leave
  48194. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) !== 0) {
  48195. this._notifParents(prim, mask);
  48196. }
  48197. var bubbleCancelled = false;
  48198. var cur = prim;
  48199. while (cur) {
  48200. // Only trigger the observers if the primitive is intersected (except for out)
  48201. if (!bubbleCancelled) {
  48202. this._updatePrimPointerPos(cur);
  48203. // Exec the observers
  48204. this._debugExecObserver(cur, mask);
  48205. if (!cur._pointerEventObservable.notifyObservers(ppi, mask) && eventData instanceof BABYLON.PointerInfoPre) {
  48206. eventData.skipOnPointerObservable = true;
  48207. return false;
  48208. }
  48209. this._triggerActionManager(cur, ppi, mask, event);
  48210. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  48211. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  48212. if (ppi.cancelBubble) {
  48213. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) === 0) {
  48214. return false;
  48215. }
  48216. // We're dealing with PointerOver/Out, let's keep looping to fire PointerEnter/Leave, but not Over/Out anymore
  48217. bubbleCancelled = true;
  48218. }
  48219. }
  48220. // If bubble is cancel we didn't update the Primitive Pointer Pos yet, let's do it
  48221. if (bubbleCancelled) {
  48222. this._updatePrimPointerPos(cur);
  48223. }
  48224. // Trigger a PointerEnter corresponding to the PointerOver
  48225. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  48226. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerEnter);
  48227. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
  48228. }
  48229. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  48230. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerLeave);
  48231. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
  48232. }
  48233. // Loop to the parent
  48234. cur = cur.parent;
  48235. }
  48236. return true;
  48237. };
  48238. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  48239. var _this = this;
  48240. // 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
  48241. if (!this._globalTransform) {
  48242. this.updateCachedStates(true);
  48243. }
  48244. // Process Trigger related to PointerDown
  48245. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  48246. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  48247. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  48248. this._pickStartingTime = new Date().getTime();
  48249. this._pickedDownPrim = null;
  48250. if (prim.actionManager) {
  48251. this._pickedDownPrim = prim;
  48252. if (prim.actionManager.hasPickTriggers) {
  48253. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  48254. switch (eventData.button) {
  48255. case 0:
  48256. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  48257. break;
  48258. case 1:
  48259. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  48260. break;
  48261. case 2:
  48262. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  48263. break;
  48264. }
  48265. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  48266. }
  48267. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  48268. window.setTimeout(function () {
  48269. var ppi = _this._primPointerInfo;
  48270. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  48271. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null);
  48272. var ii = new BABYLON.IntersectInfo2D();
  48273. ii.pickPosition = ppi.canvasPointerPos.clone();
  48274. ii.findFirstOnly = false;
  48275. _this.intersect(ii);
  48276. if (ii.isPrimIntersected(prim) !== null) {
  48277. if (prim.actionManager) {
  48278. 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)) {
  48279. _this._pickStartingTime = 0;
  48280. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  48281. }
  48282. }
  48283. }
  48284. }, BABYLON.ActionManager.LongPressDelay);
  48285. }
  48286. }
  48287. }
  48288. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  48289. this._pickStartingTime = 0;
  48290. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  48291. if (prim.actionManager) {
  48292. // OnPickUpTrigger
  48293. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  48294. // OnPickTrigger
  48295. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  48296. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  48297. }
  48298. }
  48299. // OnPickOutTrigger
  48300. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  48301. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  48302. }
  48303. }
  48304. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  48305. if (prim.actionManager) {
  48306. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  48307. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  48308. }
  48309. }
  48310. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  48311. if (prim.actionManager) {
  48312. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  48313. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  48314. }
  48315. }
  48316. };
  48317. Canvas2D.prototype._notifParents = function (prim, mask) {
  48318. var pii = this._primPointerInfo;
  48319. var curPrim = this;
  48320. while (curPrim) {
  48321. this._updatePrimPointerPos(curPrim);
  48322. // Fire the proper notification
  48323. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  48324. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerEnter);
  48325. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerEnter);
  48326. }
  48327. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  48328. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerLeave);
  48329. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerLeave);
  48330. }
  48331. curPrim = curPrim.parent;
  48332. }
  48333. };
  48334. /**
  48335. * Don't forget to call the dispose method when you're done with the Canvas instance.
  48336. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  48337. */
  48338. Canvas2D.prototype.dispose = function () {
  48339. if (!_super.prototype.dispose.call(this)) {
  48340. return false;
  48341. }
  48342. if (this._profilingCanvas) {
  48343. this._profilingCanvas.dispose();
  48344. this._profilingCanvas = null;
  48345. }
  48346. if (this.interactionEnabled) {
  48347. this._setupInteraction(false);
  48348. }
  48349. if (this._beforeRenderObserver) {
  48350. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  48351. this._beforeRenderObserver = null;
  48352. }
  48353. if (this._afterRenderObserver) {
  48354. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  48355. this._afterRenderObserver = null;
  48356. }
  48357. if (this._groupCacheMaps) {
  48358. this._groupCacheMaps.forEach(function (k, m) { return m.forEach(function (e) { return e.dispose(); }); });
  48359. this._groupCacheMaps = null;
  48360. }
  48361. };
  48362. Object.defineProperty(Canvas2D.prototype, "scene", {
  48363. /**
  48364. * Accessor to the Scene that owns the Canvas
  48365. * @returns The instance of the Scene object
  48366. */
  48367. get: function () {
  48368. return this._scene;
  48369. },
  48370. enumerable: true,
  48371. configurable: true
  48372. });
  48373. Object.defineProperty(Canvas2D.prototype, "engine", {
  48374. /**
  48375. * Accessor to the Engine that drives the Scene used by this Canvas
  48376. * @returns The instance of the Engine object
  48377. */
  48378. get: function () {
  48379. return this._engine;
  48380. },
  48381. enumerable: true,
  48382. configurable: true
  48383. });
  48384. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  48385. /**
  48386. * Accessor of the Caching Strategy used by this Canvas.
  48387. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  48388. * @returns the value corresponding to the used strategy.
  48389. */
  48390. get: function () {
  48391. return this._cachingStrategy;
  48392. },
  48393. enumerable: true,
  48394. configurable: true
  48395. });
  48396. Object.defineProperty(Canvas2D.prototype, "isScreenSpace", {
  48397. /**
  48398. * Return true if the Canvas is a Screen Space one, false if it's a World Space one.
  48399. * @returns {}
  48400. */
  48401. get: function () {
  48402. return this._isScreenSpace;
  48403. },
  48404. enumerable: true,
  48405. configurable: true
  48406. });
  48407. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  48408. /**
  48409. * Only valid for World Space Canvas, returns the scene node that displays the canvas
  48410. */
  48411. get: function () {
  48412. return this._worldSpaceNode;
  48413. },
  48414. set: function (val) {
  48415. this._worldSpaceNode = val;
  48416. },
  48417. enumerable: true,
  48418. configurable: true
  48419. });
  48420. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  48421. /**
  48422. * Check if the WebGL Instanced Array extension is supported or not
  48423. */
  48424. get: function () {
  48425. return this._supprtInstancedArray;
  48426. },
  48427. enumerable: true,
  48428. configurable: true
  48429. });
  48430. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  48431. /**
  48432. * Property that defines the fill object used to draw the background of the Canvas.
  48433. * Note that Canvas with a Caching Strategy of
  48434. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  48435. */
  48436. get: function () {
  48437. if (!this._background || !this._background.isVisible) {
  48438. return null;
  48439. }
  48440. return this._background.fill;
  48441. },
  48442. set: function (value) {
  48443. this.checkBackgroundAvailability();
  48444. if (value === this._background.fill) {
  48445. return;
  48446. }
  48447. this._background.fill = value;
  48448. this._background.levelVisible = true;
  48449. },
  48450. enumerable: true,
  48451. configurable: true
  48452. });
  48453. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  48454. /**
  48455. * Property that defines the border object used to draw the background of the Canvas.
  48456. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  48457. */
  48458. get: function () {
  48459. if (!this._background || !this._background.isVisible) {
  48460. return null;
  48461. }
  48462. return this._background.border;
  48463. },
  48464. set: function (value) {
  48465. this.checkBackgroundAvailability();
  48466. if (value === this._background.border) {
  48467. return;
  48468. }
  48469. this._background.border = value;
  48470. this._background.levelVisible = true;
  48471. },
  48472. enumerable: true,
  48473. configurable: true
  48474. });
  48475. Object.defineProperty(Canvas2D.prototype, "backgroundBorderThickness", {
  48476. /**
  48477. * Property that defines the thickness of the border object used to draw the background of the Canvas.
  48478. * @returns If the background is not set, null will be returned, otherwise a valid number matching the thickness is returned.
  48479. */
  48480. get: function () {
  48481. if (!this._background || !this._background.isVisible) {
  48482. return null;
  48483. }
  48484. return this._background.borderThickness;
  48485. },
  48486. set: function (value) {
  48487. this.checkBackgroundAvailability();
  48488. if (value === this._background.borderThickness) {
  48489. return;
  48490. }
  48491. this._background.borderThickness = value;
  48492. },
  48493. enumerable: true,
  48494. configurable: true
  48495. });
  48496. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  48497. /**
  48498. * You can set the roundRadius of the background
  48499. * @returns The current roundRadius
  48500. */
  48501. get: function () {
  48502. if (!this._background || !this._background.isVisible) {
  48503. return null;
  48504. }
  48505. return this._background.roundRadius;
  48506. },
  48507. set: function (value) {
  48508. this.checkBackgroundAvailability();
  48509. if (value === this._background.roundRadius) {
  48510. return;
  48511. }
  48512. this._background.roundRadius = value;
  48513. this._background.levelVisible = true;
  48514. },
  48515. enumerable: true,
  48516. configurable: true
  48517. });
  48518. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  48519. /**
  48520. * Enable/Disable interaction for this Canvas
  48521. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  48522. */
  48523. get: function () {
  48524. return this._interactionEnabled;
  48525. },
  48526. set: function (enable) {
  48527. this._setupInteraction(enable);
  48528. },
  48529. enumerable: true,
  48530. configurable: true
  48531. });
  48532. Object.defineProperty(Canvas2D.prototype, "designSize", {
  48533. get: function () {
  48534. return this._designSize;
  48535. },
  48536. enumerable: true,
  48537. configurable: true
  48538. });
  48539. Object.defineProperty(Canvas2D.prototype, "designSizeUseHorizAxis", {
  48540. get: function () {
  48541. return this._designUseHorizAxis;
  48542. },
  48543. enumerable: true,
  48544. configurable: true
  48545. });
  48546. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  48547. /**
  48548. * Access the babylon.js' engine bound data, do not invoke this method, it's for internal purpose only
  48549. * @returns {}
  48550. */
  48551. get: function () {
  48552. return this.__engineData;
  48553. },
  48554. enumerable: true,
  48555. configurable: true
  48556. });
  48557. Canvas2D.prototype.createCanvasProfileInfoCanvas = function () {
  48558. if (this._profilingCanvas) {
  48559. return this._profilingCanvas;
  48560. }
  48561. var canvas = new ScreenSpaceCanvas2D(this.scene, {
  48562. id: "ProfileInfoCanvas", cachingStrategy: Canvas2D.CACHESTRATEGY_DONTCACHE, children: [
  48563. new BABYLON.Rectangle2D({
  48564. id: "ProfileBorder", border: "#FFFFFFFF", borderThickness: 2, roundRadius: 5, fill: "#C04040C0", marginAlignment: "h: left, v: top", margin: "10", padding: "10", children: [
  48565. new BABYLON.Text2D("Stats", { id: "ProfileInfoText", marginAlignment: "h: left, v: top", fontName: "10pt Lucida Console" })
  48566. ]
  48567. })
  48568. ]
  48569. });
  48570. this._profileInfoText = canvas.findById("ProfileInfoText");
  48571. this._profilingCanvas = canvas;
  48572. return canvas;
  48573. };
  48574. Canvas2D.prototype.checkBackgroundAvailability = function () {
  48575. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  48576. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  48577. }
  48578. };
  48579. Canvas2D.prototype._initPerfMetrics = function () {
  48580. this._drawCallsOpaqueCounter.fetchNewFrame();
  48581. this._drawCallsAlphaTestCounter.fetchNewFrame();
  48582. this._drawCallsTransparentCounter.fetchNewFrame();
  48583. this._groupRenderCounter.fetchNewFrame();
  48584. this._updateTransparentDataCounter.fetchNewFrame();
  48585. this._cachedGroupRenderCounter.fetchNewFrame();
  48586. this._updateCachedStateCounter.fetchNewFrame();
  48587. this._updateLayoutCounter.fetchNewFrame();
  48588. this._updatePositioningCounter.fetchNewFrame();
  48589. this._updateLocalTransformCounter.fetchNewFrame();
  48590. this._updateGlobalTransformCounter.fetchNewFrame();
  48591. this._boundingInfoRecomputeCounter.fetchNewFrame();
  48592. };
  48593. Canvas2D.prototype._fetchPerfMetrics = function () {
  48594. this._drawCallsOpaqueCounter.addCount(0, true);
  48595. this._drawCallsAlphaTestCounter.addCount(0, true);
  48596. this._drawCallsTransparentCounter.addCount(0, true);
  48597. this._groupRenderCounter.addCount(0, true);
  48598. this._updateTransparentDataCounter.addCount(0, true);
  48599. this._cachedGroupRenderCounter.addCount(0, true);
  48600. this._updateCachedStateCounter.addCount(0, true);
  48601. this._updateLayoutCounter.addCount(0, true);
  48602. this._updatePositioningCounter.addCount(0, true);
  48603. this._updateLocalTransformCounter.addCount(0, true);
  48604. this._updateGlobalTransformCounter.addCount(0, true);
  48605. this._boundingInfoRecomputeCounter.addCount(0, true);
  48606. };
  48607. Canvas2D.prototype._updateProfileCanvas = function () {
  48608. if (this._profileInfoText == null) {
  48609. return;
  48610. }
  48611. var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
  48612. var p = "Draw Calls:\n" +
  48613. (" - Opaque: " + format(this.drawCallsOpaqueCounter.current) + ", (avg:" + format(this.drawCallsOpaqueCounter.lastSecAverage) + ", t:" + format(this.drawCallsOpaqueCounter.total) + ")\n") +
  48614. (" - AlphaTest: " + format(this.drawCallsAlphaTestCounter.current) + ", (avg:" + format(this.drawCallsAlphaTestCounter.lastSecAverage) + ", t:" + format(this.drawCallsAlphaTestCounter.total) + ")\n") +
  48615. (" - Transparent: " + format(this.drawCallsTransparentCounter.current) + ", (avg:" + format(this.drawCallsTransparentCounter.lastSecAverage) + ", t:" + format(this.drawCallsTransparentCounter.total) + ")\n") +
  48616. ("Group Render: " + this.groupRenderCounter.current + ", (avg:" + format(this.groupRenderCounter.lastSecAverage) + ", t:" + format(this.groupRenderCounter.total) + ")\n") +
  48617. ("Update Transparent Data: " + this.updateTransparentDataCounter.current + ", (avg:" + format(this.updateTransparentDataCounter.lastSecAverage) + ", t:" + format(this.updateTransparentDataCounter.total) + ")\n") +
  48618. ("Cached Group Render: " + this.cachedGroupRenderCounter.current + ", (avg:" + format(this.cachedGroupRenderCounter.lastSecAverage) + ", t:" + format(this.cachedGroupRenderCounter.total) + ")\n") +
  48619. ("Update Cached States: " + this.updateCachedStateCounter.current + ", (avg:" + format(this.updateCachedStateCounter.lastSecAverage) + ", t:" + format(this.updateCachedStateCounter.total) + ")\n") +
  48620. (" - Update Layout: " + this.updateLayoutCounter.current + ", (avg:" + format(this.updateLayoutCounter.lastSecAverage) + ", t:" + format(this.updateLayoutCounter.total) + ")\n") +
  48621. (" - Update Positioning: " + this.updatePositioningCounter.current + ", (avg:" + format(this.updatePositioningCounter.lastSecAverage) + ", t:" + format(this.updatePositioningCounter.total) + ")\n") +
  48622. (" - Update Local Trans: " + this.updateLocalTransformCounter.current + ", (avg:" + format(this.updateLocalTransformCounter.lastSecAverage) + ", t:" + format(this.updateLocalTransformCounter.total) + ")\n") +
  48623. (" - Update Global Trans: " + this.updateGlobalTransformCounter.current + ", (avg:" + format(this.updateGlobalTransformCounter.lastSecAverage) + ", t:" + format(this.updateGlobalTransformCounter.total) + ")\n") +
  48624. (" - BoundingInfo Recompute: " + this.boundingInfoRecomputeCounter.current + ", (avg:" + format(this.boundingInfoRecomputeCounter.lastSecAverage) + ", t:" + format(this.boundingInfoRecomputeCounter.total) + ")\n");
  48625. this._profileInfoText.text = p;
  48626. };
  48627. Canvas2D.prototype._addDrawCallCount = function (count, renderMode) {
  48628. switch (renderMode) {
  48629. case BABYLON.Render2DContext.RenderModeOpaque:
  48630. this._drawCallsOpaqueCounter.addCount(count, false);
  48631. return;
  48632. case BABYLON.Render2DContext.RenderModeAlphaTest:
  48633. this._drawCallsAlphaTestCounter.addCount(count, false);
  48634. return;
  48635. case BABYLON.Render2DContext.RenderModeTransparent:
  48636. this._drawCallsTransparentCounter.addCount(count, false);
  48637. return;
  48638. }
  48639. };
  48640. Canvas2D.prototype._addGroupRenderCount = function (count) {
  48641. this._groupRenderCounter.addCount(count, false);
  48642. };
  48643. Canvas2D.prototype._addUpdateTransparentDataCount = function (count) {
  48644. this._updateTransparentDataCounter.addCount(count, false);
  48645. };
  48646. Canvas2D.prototype.addCachedGroupRenderCounter = function (count) {
  48647. this._cachedGroupRenderCounter.addCount(count, false);
  48648. };
  48649. Canvas2D.prototype.addUpdateCachedStateCounter = function (count) {
  48650. this._updateCachedStateCounter.addCount(count, false);
  48651. };
  48652. Canvas2D.prototype.addUpdateLayoutCounter = function (count) {
  48653. this._updateLayoutCounter.addCount(count, false);
  48654. };
  48655. Canvas2D.prototype.addUpdatePositioningCounter = function (count) {
  48656. this._updatePositioningCounter.addCount(count, false);
  48657. };
  48658. Canvas2D.prototype.addupdateLocalTransformCounter = function (count) {
  48659. this._updateLocalTransformCounter.addCount(count, false);
  48660. };
  48661. Canvas2D.prototype.addUpdateGlobalTransformCounter = function (count) {
  48662. this._updateGlobalTransformCounter.addCount(count, false);
  48663. };
  48664. Canvas2D.prototype._updateTrackedNodes = function () {
  48665. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  48666. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  48667. var rh = this.engine.getRenderHeight();
  48668. var v = cam.viewport.toGlobal(this.engine.getRenderWidth(), rh);
  48669. for (var _i = 0, _a = this._trackedGroups; _i < _a.length; _i++) {
  48670. var group = _a[_i];
  48671. if (group.isDisposed || !group.isVisible) {
  48672. continue;
  48673. }
  48674. var node = group.trackedNode;
  48675. var worldMtx = node.getWorldMatrix();
  48676. var proj = BABYLON.Vector3.Project(Canvas2D._v, worldMtx, Canvas2D._m, v);
  48677. var s = this.scale;
  48678. group.x = Math.round(proj.x / s);
  48679. group.y = Math.round((rh - proj.y) / s);
  48680. }
  48681. };
  48682. /**
  48683. * Call this method change you want to have layout related data computed and up to date (layout area, primitive area, local/global transformation matrices)
  48684. */
  48685. Canvas2D.prototype.updateCanvasLayout = function (forceRecompute) {
  48686. this._updateCanvasState(forceRecompute);
  48687. };
  48688. Canvas2D.prototype._updateAdaptiveSizeWorldCanvas = function () {
  48689. if (this._globalTransformStep < 2) {
  48690. return;
  48691. }
  48692. var n = this.worldSpaceCanvasNode;
  48693. var bi = n.getBoundingInfo().boundingBox;
  48694. var v = bi.vectorsWorld;
  48695. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  48696. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  48697. var vp = cam.viewport.toGlobal(this.engine.getRenderWidth(), this.engine.getRenderHeight());
  48698. var projPoints = new Array(4);
  48699. for (var i = 0; i < 4; i++) {
  48700. projPoints[i] = BABYLON.Vector3.Project(v[i], Canvas2D._mI, Canvas2D._m, vp);
  48701. }
  48702. var left = projPoints[3].subtract(projPoints[0]).length();
  48703. var top = projPoints[3].subtract(projPoints[1]).length();
  48704. var right = projPoints[1].subtract(projPoints[2]).length();
  48705. var bottom = projPoints[2].subtract(projPoints[0]).length();
  48706. var w = Math.round(Math.max(top, bottom));
  48707. var h = Math.round(Math.max(right, left));
  48708. var isW = w > h;
  48709. // Basically if it's under 256 we use 256, otherwise we take the biggest power of 2
  48710. var edge = Math.max(w, h);
  48711. if (edge < 256) {
  48712. edge = 256;
  48713. }
  48714. else {
  48715. edge = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  48716. }
  48717. // Clip values if needed
  48718. edge = Math.min(edge, this._maxAdaptiveWorldSpaceCanvasSize);
  48719. var newScale = edge / ((isW) ? this.size.width : this.size.height);
  48720. if (newScale !== this.scale) {
  48721. var scale = newScale;
  48722. // console.log(`New adaptive scale for Canvas ${this.id}, w: ${w}, h: ${h}, scale: ${scale}, edge: ${edge}, isW: ${isW}`);
  48723. this._setRenderingScale(scale);
  48724. }
  48725. };
  48726. Canvas2D.prototype._updateCanvasState = function (forceRecompute) {
  48727. // Check if the update has already been made for this render Frame
  48728. if (!forceRecompute && this.scene.getRenderId() === this._updateRenderId) {
  48729. return;
  48730. }
  48731. // Detect a change of rendering size
  48732. var renderingSizeChanged = false;
  48733. var newWidth = this.engine.getRenderWidth();
  48734. if (newWidth !== this._renderingSize.width) {
  48735. renderingSizeChanged = true;
  48736. }
  48737. this._renderingSize.width = newWidth;
  48738. var newHeight = this.engine.getRenderHeight();
  48739. if (newHeight !== this._renderingSize.height) {
  48740. renderingSizeChanged = true;
  48741. }
  48742. this._renderingSize.height = newHeight;
  48743. // If the canvas fit the rendering size and it changed, update
  48744. if (renderingSizeChanged && this._fitRenderingDevice) {
  48745. this.size = this._renderingSize;
  48746. if (this._background) {
  48747. this._background.size = this.size;
  48748. }
  48749. // Dirty the Layout at the Canvas level to recompute as the size changed
  48750. this._setLayoutDirty();
  48751. }
  48752. // If there's a design size, update the scale according to the renderingSize
  48753. if (this._designSize) {
  48754. var scale;
  48755. if (this._designUseHorizAxis) {
  48756. scale = this._renderingSize.width / this._designSize.width;
  48757. }
  48758. else {
  48759. scale = this._renderingSize.height / this._designSize.height;
  48760. }
  48761. this.size = this._designSize.clone();
  48762. this.scale = scale;
  48763. }
  48764. var context = new BABYLON.PrepareRender2DContext();
  48765. ++this._globalTransformProcessStep;
  48766. this.updateCachedStates(false);
  48767. this._prepareGroupRender(context);
  48768. this._updateRenderId = this.scene.getRenderId();
  48769. };
  48770. /**
  48771. * Method that renders the Canvas, you should not invoke
  48772. */
  48773. Canvas2D.prototype._render = function () {
  48774. this._initPerfMetrics();
  48775. this._updateCanvasState(false);
  48776. this._updateTrackedNodes();
  48777. // Nothing to do is the Canvas is not visible
  48778. if (this.isVisible === false) {
  48779. return;
  48780. }
  48781. if (!this._isScreenSpace) {
  48782. this._updateAdaptiveSizeWorldCanvas();
  48783. }
  48784. this._updateCanvasState(false);
  48785. if (this._primPointerInfo.canvasPointerPos) {
  48786. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false);
  48787. this._updateOverStatus(); // TODO this._primPointerInfo may not be up to date!
  48788. }
  48789. this.engine.setState(false);
  48790. this._groupRender();
  48791. if (!this._isScreenSpace) {
  48792. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagWorldCacheChanged)) {
  48793. this.worldSpaceCacheChanged();
  48794. this._clearFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  48795. }
  48796. }
  48797. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  48798. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  48799. this._cachedCanvasGroup._renderCachedCanvas();
  48800. }
  48801. this._fetchPerfMetrics();
  48802. this._updateProfileCanvas();
  48803. };
  48804. /**
  48805. * Internal method that allocate a cache for the given group.
  48806. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  48807. * @param group The group to allocate the cache of.
  48808. * @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.
  48809. */
  48810. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize, useMipMap, anisotropicLevel) {
  48811. if (useMipMap === void 0) { useMipMap = false; }
  48812. if (anisotropicLevel === void 0) { anisotropicLevel = 1; }
  48813. var key = (useMipMap ? "MipMap" : "NoMipMap") + "_" + anisotropicLevel;
  48814. var rd = group._renderableData;
  48815. var noResizeScale = rd._noResizeOnScale;
  48816. var isCanvas = parent == null;
  48817. var scale;
  48818. if (noResizeScale) {
  48819. scale = isCanvas ? Canvas2D._unS : group.parent.actualScale;
  48820. }
  48821. else {
  48822. scale = group.actualScale;
  48823. }
  48824. // Determine size
  48825. var size = group.actualSize;
  48826. size = new BABYLON.Size(Math.ceil(size.width * scale.x), Math.ceil(size.height * scale.y));
  48827. if (minSize) {
  48828. size.width = Math.max(minSize.width, size.width);
  48829. size.height = Math.max(minSize.height, size.height);
  48830. }
  48831. var mapArray = this._groupCacheMaps.getOrAddWithFactory(key, function () { return new Array(); });
  48832. // Try to find a spot in one of the cached texture
  48833. var res = null;
  48834. var map;
  48835. for (var _i = 0; _i < mapArray.length; _i++) {
  48836. var _map = mapArray[_i];
  48837. map = _map;
  48838. var node = map.allocateRect(size);
  48839. if (node) {
  48840. res = { node: node, texture: map };
  48841. break;
  48842. }
  48843. }
  48844. // Couldn't find a map that could fit the rect, create a new map for it
  48845. if (!res) {
  48846. var mapSize = new BABYLON.Size(Canvas2D._groupTextureCacheSize, Canvas2D._groupTextureCacheSize);
  48847. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  48848. if (size.width > mapSize.width || size.height > mapSize.height) {
  48849. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  48850. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  48851. }
  48852. var id = "groupsMapChache" + this._mapCounter++ + "forCanvas" + this.id;
  48853. map = new BABYLON.MapTexture(id, this._scene, mapSize, useMipMap ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE, useMipMap);
  48854. map.hasAlpha = true;
  48855. map.anisotropicFilteringLevel = 4;
  48856. mapArray.splice(0, 0, map);
  48857. var node = map.allocateRect(size);
  48858. res = { node: node, texture: map };
  48859. }
  48860. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  48861. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  48862. if (group !== this || this._isScreenSpace) {
  48863. var node = res.node;
  48864. // 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
  48865. var sprite;
  48866. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS) {
  48867. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  48868. sprite = new BABYLON.Sprite2D(map, { parent: this._cachedCanvasGroup, id: "__cachedCanvasSprite__", spriteSize: node.contentSize, spriteLocation: node.pos });
  48869. sprite.zOrder = 1;
  48870. sprite.origin = BABYLON.Vector2.Zero();
  48871. }
  48872. else {
  48873. 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, dontInheritParentScale: true });
  48874. sprite.origin = group.origin.clone();
  48875. sprite.addExternalData("__cachedGroup__", group);
  48876. sprite.pointerEventObservable.add(function (e, s) {
  48877. if (group.pointerEventObservable !== null) {
  48878. group.pointerEventObservable.notifyObservers(e, s.mask);
  48879. }
  48880. });
  48881. res.sprite = sprite;
  48882. }
  48883. if (sprite && noResizeScale) {
  48884. var relScale = isCanvas ? group.actualScale : group.actualScale.divide(group.parent.actualScale);
  48885. sprite.scaleX = relScale.x;
  48886. sprite.scaleY = relScale.y;
  48887. }
  48888. }
  48889. return res;
  48890. };
  48891. /**
  48892. * Internal method used to register a Scene Node to track position for the given group
  48893. * Do not invoke this method, for internal purpose only.
  48894. * @param group the group to track its associated Scene Node
  48895. */
  48896. Canvas2D.prototype._registerTrackedNode = function (group) {
  48897. if (group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  48898. return;
  48899. }
  48900. this._trackedGroups.push(group);
  48901. group._setFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  48902. };
  48903. /**
  48904. * Internal method used to unregister a tracked Scene Node
  48905. * Do not invoke this method, it's for internal purpose only.
  48906. * @param group the group to unregister its tracked Scene Node from.
  48907. */
  48908. Canvas2D.prototype._unregisterTrackedNode = function (group) {
  48909. if (!group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  48910. return;
  48911. }
  48912. var i = this._trackedGroups.indexOf(group);
  48913. if (i !== -1) {
  48914. this._trackedGroups.splice(i, 1);
  48915. }
  48916. group._clearFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  48917. };
  48918. /**
  48919. * Get a Solid Color Brush instance matching the given color.
  48920. * @param color The color to retrieve
  48921. * @return A shared instance of the SolidColorBrush2D class that use the given color
  48922. */
  48923. Canvas2D.GetSolidColorBrush = function (color) {
  48924. return Canvas2D._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  48925. };
  48926. /**
  48927. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  48928. * @param color The color to retrieve
  48929. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  48930. */
  48931. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  48932. return Canvas2D._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  48933. };
  48934. /**
  48935. * Get a Gradient Color Brush
  48936. * @param color1 starting color
  48937. * @param color2 engine color
  48938. * @param translation translation vector to apply. default is [0;0]
  48939. * @param rotation rotation in radian to apply to the brush, initial direction is top to bottom. rotation is counter clockwise. default is 0.
  48940. * @param scale scaling factor to apply. default is 1.
  48941. */
  48942. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  48943. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  48944. if (rotation === void 0) { rotation = 0; }
  48945. if (scale === void 0) { scale = 1; }
  48946. return Canvas2D._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  48947. };
  48948. /**
  48949. * Create a solid or gradient brush from a string value.
  48950. * @param brushString should be either
  48951. * - "solid: #RRGGBBAA" or "#RRGGBBAA"
  48952. * - "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.
  48953. */
  48954. Canvas2D.GetBrushFromString = function (brushString) {
  48955. // Note: yes, I hate/don't know RegEx.. Feel free to add your contribution to the cause!
  48956. brushString = brushString.trim();
  48957. var split = brushString.split(",");
  48958. // Solid, formatted as: "[solid:]#FF808080"
  48959. if (split.length === 1) {
  48960. var value = null;
  48961. if (brushString.indexOf("solid:") === 0) {
  48962. value = brushString.substr(6).trim();
  48963. }
  48964. else if (brushString.indexOf("#") === 0) {
  48965. value = brushString;
  48966. }
  48967. else {
  48968. return null;
  48969. }
  48970. return Canvas2D.GetSolidColorBrushFromHex(value);
  48971. }
  48972. else {
  48973. if (split[0].indexOf("gradient:") === 0) {
  48974. split[0] = split[0].substr(9).trim();
  48975. }
  48976. try {
  48977. var start = BABYLON.Color4.FromHexString(split[0].trim());
  48978. var end = BABYLON.Color4.FromHexString(split[1].trim());
  48979. var t = BABYLON.Vector2.Zero();
  48980. if (split.length > 2) {
  48981. var v = split[2].trim();
  48982. if (v.charAt(0) !== "[" || v.charAt(v.length - 1) !== "]") {
  48983. return null;
  48984. }
  48985. var sep = v.indexOf(":");
  48986. var x = parseFloat(v.substr(1, sep));
  48987. var y = parseFloat(v.substr(sep + 1, v.length - (sep + 1)));
  48988. t = new BABYLON.Vector2(x, y);
  48989. }
  48990. var r = 0;
  48991. if (split.length > 3) {
  48992. r = BABYLON.Tools.ToRadians(parseFloat(split[3].trim()));
  48993. }
  48994. var s = 1;
  48995. if (split.length > 4) {
  48996. s = parseFloat(split[4].trim());
  48997. }
  48998. return Canvas2D.GetGradientColorBrush(start, end, t, r, s);
  48999. }
  49000. catch (e) {
  49001. return null;
  49002. }
  49003. }
  49004. };
  49005. /**
  49006. * 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.
  49007. * This strategy doesn't allow primitives added directly as children of the Canvas.
  49008. * 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.
  49009. */
  49010. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  49011. /**
  49012. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  49013. * 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.
  49014. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  49015. * 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.
  49016. */
  49017. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  49018. /**
  49019. * 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).
  49020. */
  49021. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  49022. /**
  49023. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  49024. * 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).
  49025. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  49026. */
  49027. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  49028. Canvas2D._zMinDelta = 1 / (Math.pow(2, 24) - 1);
  49029. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  49030. Canvas2D._v = BABYLON.Vector3.Zero(); // Must stay zero
  49031. Canvas2D._m = BABYLON.Matrix.Identity();
  49032. Canvas2D._mI = BABYLON.Matrix.Identity(); // Must stay identity
  49033. Canvas2D._unS = new BABYLON.Vector2(1, 1);
  49034. /**
  49035. * Define the default size used for both the width and height of a MapTexture to allocate.
  49036. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  49037. */
  49038. Canvas2D._groupTextureCacheSize = 1024;
  49039. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  49040. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  49041. Canvas2D = __decorate([
  49042. BABYLON.className("Canvas2D")
  49043. ], Canvas2D);
  49044. return Canvas2D;
  49045. })(BABYLON.Group2D);
  49046. BABYLON.Canvas2D = Canvas2D;
  49047. var WorldSpaceCanvas2D = (function (_super) {
  49048. __extends(WorldSpaceCanvas2D, _super);
  49049. /**
  49050. * 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.
  49051. * 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.
  49052. * @param scene the Scene that owns the Canvas
  49053. * @param size the dimension of the Canvas in World Space
  49054. * @param settings a combination of settings, possible ones are
  49055. * - children: an array of direct children primitives
  49056. * - id: a text identifier, for information purpose only, default is null.
  49057. * - worldPosition the position of the Canvas in World Space, default is [0,0,0]
  49058. * - worldRotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
  49059. * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
  49060. * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
  49061. * - 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).
  49062. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  49063. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  49064. * - 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.
  49065. * - 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.
  49066. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  49067. * - 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.
  49068. * - 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.
  49069. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  49070. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  49071. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  49072. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  49073. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  49074. */
  49075. function WorldSpaceCanvas2D(scene, size, settings) {
  49076. BABYLON.Prim2DBase._isCanvasInit = true;
  49077. var s = settings;
  49078. s.isScreenSpace = false;
  49079. s.size = size.clone();
  49080. settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;
  49081. if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
  49082. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  49083. }
  49084. _super.call(this, scene, settings);
  49085. BABYLON.Prim2DBase._isCanvasInit = false;
  49086. this._renderableData._useMipMap = true;
  49087. this._renderableData._anisotropicLevel = 8;
  49088. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  49089. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  49090. //}
  49091. var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);
  49092. var id = settings ? settings.id || null : null;
  49093. // Set the max size of texture allowed for the adaptive render of the world space canvas cached bitmap
  49094. var capMaxTextSize = this.engine.getCaps().maxRenderTextureSize;
  49095. var defaultTextSize = (Math.min(capMaxTextSize, 1024)); // Default is 4K if allowed otherwise the max allowed
  49096. if (settings.maxAdaptiveCanvasSize == null) {
  49097. this._maxAdaptiveWorldSpaceCanvasSize = defaultTextSize;
  49098. }
  49099. else {
  49100. // We still clip the given value with the max allowed, the user may not be aware of these limitations
  49101. this._maxAdaptiveWorldSpaceCanvasSize = Math.min(settings.maxAdaptiveCanvasSize, capMaxTextSize);
  49102. }
  49103. if (createWorldSpaceNode) {
  49104. var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, this);
  49105. var vertexData = BABYLON.VertexData.CreatePlane({
  49106. width: size.width,
  49107. height: size.height,
  49108. sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
  49109. });
  49110. var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
  49111. this.applyCachedTexture(vertexData, mtl);
  49112. vertexData.applyToMesh(plane, true);
  49113. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  49114. mtl.disableLighting = true;
  49115. mtl.useAlphaFromDiffuseTexture = true;
  49116. plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();
  49117. plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();
  49118. plane.material = mtl;
  49119. this._worldSpaceNode = plane;
  49120. }
  49121. else {
  49122. this._worldSpaceNode = settings.customWorldSpaceNode;
  49123. this.applyCachedTexture(null, null);
  49124. }
  49125. }
  49126. WorldSpaceCanvas2D = __decorate([
  49127. BABYLON.className("WorldSpaceCanvas2D")
  49128. ], WorldSpaceCanvas2D);
  49129. return WorldSpaceCanvas2D;
  49130. })(Canvas2D);
  49131. BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
  49132. var ScreenSpaceCanvas2D = (function (_super) {
  49133. __extends(ScreenSpaceCanvas2D, _super);
  49134. /**
  49135. * 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.
  49136. * 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.
  49137. * All caching strategies will be available.
  49138. * 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]
  49139. * @param scene the Scene that owns the Canvas
  49140. * @param settings a combination of settings, possible ones are
  49141. * - children: an array of direct children primitives
  49142. * - id: a text identifier, for information purpose only
  49143. * - x: the position along the x axis (horizontal), relative to the left edge of the viewport. you can alternatively use the position setting.
  49144. * - y: the position along the y axis (vertically), relative to the bottom edge of the viewport. you can alternatively use the position setting.
  49145. * - 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]
  49146. * - width: the width of the Canvas. you can alternatively use the size setting.
  49147. * - height: the height of the Canvas. you can alternatively use the size setting.
  49148. * - 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
  49149. * - designSize: if you want to set the canvas content based on fixed coordinates whatever the final canvas dimension would be, set this. For instance a designSize of 360*640 will give you the possibility to specify all the children element in this frame. The Canvas' true size will be the HTMLCanvas' size: for instance it could be 720*1280, then a uniform scale of 2 will be applied on the Canvas to keep the absolute coordinates working as expecting. If the ratios of the designSize and the true Canvas size are not the same, then the scale is computed following the designUseHorizAxis member by using either the size of the horizontal axis or the vertical axis.
  49150. * - designUseHorizAxis: you can set this member if you use designSize to specify which axis is priority to compute the scale when the ratio of the canvas' size is different from the designSize's one.
  49151. * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_DONTCACHE
  49152. * - 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.
  49153. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  49154. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  49155. * - 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.
  49156. * - 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.
  49157. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  49158. * - 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.
  49159. * - paddingTop: top padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  49160. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  49161. * - paddingRight: right padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  49162. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  49163. * - padding: top, left, right and bottom padding formatted as a single string (see BABYLON.PrimitiveThickness.fromString)
  49164. */
  49165. function ScreenSpaceCanvas2D(scene, settings) {
  49166. BABYLON.Prim2DBase._isCanvasInit = true;
  49167. _super.call(this, scene, settings);
  49168. }
  49169. ScreenSpaceCanvas2D = __decorate([
  49170. BABYLON.className("ScreenSpaceCanvas2D")
  49171. ], ScreenSpaceCanvas2D);
  49172. return ScreenSpaceCanvas2D;
  49173. })(Canvas2D);
  49174. BABYLON.ScreenSpaceCanvas2D = ScreenSpaceCanvas2D;
  49175. })(BABYLON || (BABYLON = {}));
  49176. var BABYLON;
  49177. (function (BABYLON) {
  49178. /**
  49179. * This is the class that is used to display a World Space Canvas into a 3D scene
  49180. */
  49181. var WorldSpaceCanvas2DNode = (function (_super) {
  49182. __extends(WorldSpaceCanvas2DNode, _super);
  49183. function WorldSpaceCanvas2DNode(name, scene, canvas) {
  49184. _super.call(this, name, scene);
  49185. this._canvas = canvas;
  49186. }
  49187. WorldSpaceCanvas2DNode.prototype.dispose = function () {
  49188. _super.prototype.dispose.call(this);
  49189. if (this._canvas) {
  49190. this._canvas.dispose();
  49191. this._canvas = null;
  49192. }
  49193. };
  49194. return WorldSpaceCanvas2DNode;
  49195. })(BABYLON.Mesh);
  49196. BABYLON.WorldSpaceCanvas2DNode = WorldSpaceCanvas2DNode;
  49197. })(BABYLON || (BABYLON = {}));
  49198. var BABYLON;
  49199. (function (BABYLON) {
  49200. var LayoutEngineBase = (function () {
  49201. function LayoutEngineBase() {
  49202. this.layoutDirtyOnPropertyChangedMask = 0;
  49203. }
  49204. LayoutEngineBase.prototype.updateLayout = function (prim) {
  49205. };
  49206. Object.defineProperty(LayoutEngineBase.prototype, "isChildPositionAllowed", {
  49207. get: function () {
  49208. return false;
  49209. },
  49210. enumerable: true,
  49211. configurable: true
  49212. });
  49213. LayoutEngineBase.prototype.isLocked = function () {
  49214. return this._isLocked;
  49215. };
  49216. LayoutEngineBase.prototype.lock = function () {
  49217. if (this._isLocked) {
  49218. return false;
  49219. }
  49220. this._isLocked = true;
  49221. return true;
  49222. };
  49223. LayoutEngineBase = __decorate([
  49224. BABYLON.className("LayoutEngineBase")
  49225. ], LayoutEngineBase);
  49226. return LayoutEngineBase;
  49227. })();
  49228. BABYLON.LayoutEngineBase = LayoutEngineBase;
  49229. var CanvasLayoutEngine = (function (_super) {
  49230. __extends(CanvasLayoutEngine, _super);
  49231. function CanvasLayoutEngine() {
  49232. _super.apply(this, arguments);
  49233. }
  49234. // A very simple (no) layout computing...
  49235. // The Canvas and its direct children gets the Canvas' size as Layout Area
  49236. // Indirect children have their Layout Area to the actualSize (margin area) of their parent
  49237. CanvasLayoutEngine.prototype.updateLayout = function (prim) {
  49238. // If this prim is layoutDiry we update its layoutArea and also the one of its direct children
  49239. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  49240. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  49241. var child = _a[_i];
  49242. this._doUpdate(child);
  49243. }
  49244. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  49245. }
  49246. };
  49247. CanvasLayoutEngine.prototype._doUpdate = function (prim) {
  49248. // Canvas ?
  49249. if (prim instanceof BABYLON.Canvas2D) {
  49250. prim.layoutArea = prim.actualSize;
  49251. }
  49252. else if (prim.parent instanceof BABYLON.Canvas2D) {
  49253. prim.layoutArea = prim.owner.actualSize;
  49254. }
  49255. else {
  49256. prim.layoutArea = prim.parent.contentArea;
  49257. }
  49258. };
  49259. Object.defineProperty(CanvasLayoutEngine.prototype, "isChildPositionAllowed", {
  49260. get: function () {
  49261. return true;
  49262. },
  49263. enumerable: true,
  49264. configurable: true
  49265. });
  49266. CanvasLayoutEngine.Singleton = new CanvasLayoutEngine();
  49267. CanvasLayoutEngine = __decorate([
  49268. BABYLON.className("CanvasLayoutEngine")
  49269. ], CanvasLayoutEngine);
  49270. return CanvasLayoutEngine;
  49271. })(LayoutEngineBase);
  49272. BABYLON.CanvasLayoutEngine = CanvasLayoutEngine;
  49273. var StackPanelLayoutEngine = (function (_super) {
  49274. __extends(StackPanelLayoutEngine, _super);
  49275. function StackPanelLayoutEngine() {
  49276. _super.call(this);
  49277. this._isHorizontal = true;
  49278. this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId;
  49279. }
  49280. Object.defineProperty(StackPanelLayoutEngine, "Horizontal", {
  49281. get: function () {
  49282. if (!StackPanelLayoutEngine._horizontal) {
  49283. StackPanelLayoutEngine._horizontal = new StackPanelLayoutEngine();
  49284. StackPanelLayoutEngine._horizontal.isHorizontal = true;
  49285. StackPanelLayoutEngine._horizontal.lock();
  49286. }
  49287. return StackPanelLayoutEngine._horizontal;
  49288. },
  49289. enumerable: true,
  49290. configurable: true
  49291. });
  49292. Object.defineProperty(StackPanelLayoutEngine, "Vertical", {
  49293. get: function () {
  49294. if (!StackPanelLayoutEngine._vertical) {
  49295. StackPanelLayoutEngine._vertical = new StackPanelLayoutEngine();
  49296. StackPanelLayoutEngine._vertical.isHorizontal = false;
  49297. StackPanelLayoutEngine._vertical.lock();
  49298. }
  49299. return StackPanelLayoutEngine._vertical;
  49300. },
  49301. enumerable: true,
  49302. configurable: true
  49303. });
  49304. Object.defineProperty(StackPanelLayoutEngine.prototype, "isHorizontal", {
  49305. get: function () {
  49306. return this._isHorizontal;
  49307. },
  49308. set: function (val) {
  49309. if (this.isLocked()) {
  49310. return;
  49311. }
  49312. this._isHorizontal = val;
  49313. },
  49314. enumerable: true,
  49315. configurable: true
  49316. });
  49317. StackPanelLayoutEngine.prototype.updateLayout = function (prim) {
  49318. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  49319. var x = 0;
  49320. var y = 0;
  49321. var h = this.isHorizontal;
  49322. var max = 0;
  49323. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  49324. var child = _a[_i];
  49325. var layoutArea = void 0;
  49326. if (child._hasMargin) {
  49327. child.margin.computeWithAlignment(prim.layoutArea, child.actualSize, child.marginAlignment, StackPanelLayoutEngine.dstOffset, StackPanelLayoutEngine.dstArea, true);
  49328. layoutArea = StackPanelLayoutEngine.dstArea;
  49329. child.layoutArea = layoutArea;
  49330. }
  49331. else {
  49332. layoutArea = child.layoutArea;
  49333. child.margin.computeArea(child.actualSize, layoutArea);
  49334. }
  49335. max = Math.max(max, h ? layoutArea.height : layoutArea.width);
  49336. }
  49337. for (var _b = 0, _c = prim.children; _b < _c.length; _b++) {
  49338. var child = _c[_b];
  49339. child.layoutAreaPos = new BABYLON.Vector2(x, y);
  49340. var layoutArea = child.layoutArea;
  49341. if (h) {
  49342. x += layoutArea.width;
  49343. child.layoutArea = new BABYLON.Size(layoutArea.width, max);
  49344. }
  49345. else {
  49346. y += layoutArea.height;
  49347. child.layoutArea = new BABYLON.Size(max, layoutArea.height);
  49348. }
  49349. }
  49350. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  49351. }
  49352. };
  49353. Object.defineProperty(StackPanelLayoutEngine.prototype, "isChildPositionAllowed", {
  49354. get: function () {
  49355. return false;
  49356. },
  49357. enumerable: true,
  49358. configurable: true
  49359. });
  49360. StackPanelLayoutEngine._horizontal = null;
  49361. StackPanelLayoutEngine._vertical = null;
  49362. StackPanelLayoutEngine.dstOffset = BABYLON.Vector2.Zero();
  49363. StackPanelLayoutEngine.dstArea = BABYLON.Size.Zero();
  49364. StackPanelLayoutEngine = __decorate([
  49365. BABYLON.className("StackPanelLayoutEngine")
  49366. ], StackPanelLayoutEngine);
  49367. return StackPanelLayoutEngine;
  49368. })(LayoutEngineBase);
  49369. BABYLON.StackPanelLayoutEngine = StackPanelLayoutEngine;
  49370. })(BABYLON || (BABYLON = {}));
  49371. var BABYLON;
  49372. (function (BABYLON) {
  49373. var ShaderMaterial = (function (_super) {
  49374. __extends(ShaderMaterial, _super);
  49375. function ShaderMaterial(name, scene, shaderPath, options) {
  49376. _super.call(this, name, scene);
  49377. this._textures = {};
  49378. this._textureArrays = {};
  49379. this._floats = {};
  49380. this._floatsArrays = {};
  49381. this._colors3 = {};
  49382. this._colors4 = {};
  49383. this._vectors2 = {};
  49384. this._vectors3 = {};
  49385. this._vectors4 = {};
  49386. this._matrices = {};
  49387. this._matrices3x3 = {};
  49388. this._matrices2x2 = {};
  49389. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  49390. this._shaderPath = shaderPath;
  49391. options.needAlphaBlending = options.needAlphaBlending || false;
  49392. options.needAlphaTesting = options.needAlphaTesting || false;
  49393. options.attributes = options.attributes || ["position", "normal", "uv"];
  49394. options.uniforms = options.uniforms || ["worldViewProjection"];
  49395. options.samplers = options.samplers || [];
  49396. options.defines = options.defines || [];
  49397. this._options = options;
  49398. }
  49399. ShaderMaterial.prototype.needAlphaBlending = function () {
  49400. return this._options.needAlphaBlending;
  49401. };
  49402. ShaderMaterial.prototype.needAlphaTesting = function () {
  49403. return this._options.needAlphaTesting;
  49404. };
  49405. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  49406. if (this._options.uniforms.indexOf(uniformName) === -1) {
  49407. this._options.uniforms.push(uniformName);
  49408. }
  49409. };
  49410. ShaderMaterial.prototype.setTexture = function (name, texture) {
  49411. if (this._options.samplers.indexOf(name) === -1) {
  49412. this._options.samplers.push(name);
  49413. }
  49414. this._textures[name] = texture;
  49415. return this;
  49416. };
  49417. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  49418. if (this._options.samplers.indexOf(name) === -1) {
  49419. this._options.samplers.push(name);
  49420. }
  49421. this._checkUniform(name);
  49422. this._textureArrays[name] = textures;
  49423. return this;
  49424. };
  49425. ShaderMaterial.prototype.setFloat = function (name, value) {
  49426. this._checkUniform(name);
  49427. this._floats[name] = value;
  49428. return this;
  49429. };
  49430. ShaderMaterial.prototype.setFloats = function (name, value) {
  49431. this._checkUniform(name);
  49432. this._floatsArrays[name] = value;
  49433. return this;
  49434. };
  49435. ShaderMaterial.prototype.setColor3 = function (name, value) {
  49436. this._checkUniform(name);
  49437. this._colors3[name] = value;
  49438. return this;
  49439. };
  49440. ShaderMaterial.prototype.setColor4 = function (name, value) {
  49441. this._checkUniform(name);
  49442. this._colors4[name] = value;
  49443. return this;
  49444. };
  49445. ShaderMaterial.prototype.setVector2 = function (name, value) {
  49446. this._checkUniform(name);
  49447. this._vectors2[name] = value;
  49448. return this;
  49449. };
  49450. ShaderMaterial.prototype.setVector3 = function (name, value) {
  49451. this._checkUniform(name);
  49452. this._vectors3[name] = value;
  49453. return this;
  49454. };
  49455. ShaderMaterial.prototype.setVector4 = function (name, value) {
  49456. this._checkUniform(name);
  49457. this._vectors4[name] = value;
  49458. return this;
  49459. };
  49460. ShaderMaterial.prototype.setMatrix = function (name, value) {
  49461. this._checkUniform(name);
  49462. this._matrices[name] = value;
  49463. return this;
  49464. };
  49465. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  49466. this._checkUniform(name);
  49467. this._matrices3x3[name] = value;
  49468. return this;
  49469. };
  49470. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  49471. this._checkUniform(name);
  49472. this._matrices2x2[name] = value;
  49473. return this;
  49474. };
  49475. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  49476. var scene = this.getScene();
  49477. var engine = scene.getEngine();
  49478. if (!this.checkReadyOnEveryCall) {
  49479. if (this._renderId === scene.getRenderId()) {
  49480. return true;
  49481. }
  49482. }
  49483. // Instances
  49484. var defines = [];
  49485. var fallbacks = new BABYLON.EffectFallbacks();
  49486. if (useInstances) {
  49487. defines.push("#define INSTANCES");
  49488. }
  49489. for (var index = 0; index < this._options.defines.length; index++) {
  49490. defines.push(this._options.defines[index]);
  49491. }
  49492. // Bones
  49493. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  49494. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  49495. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  49496. fallbacks.addCPUSkinningFallback(0, mesh);
  49497. }
  49498. // Alpha test
  49499. if (engine.getAlphaTesting()) {
  49500. defines.push("#define ALPHATEST");
  49501. }
  49502. var previousEffect = this._effect;
  49503. var join = defines.join("\n");
  49504. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  49505. if (!this._effect.isReady()) {
  49506. return false;
  49507. }
  49508. if (previousEffect !== this._effect) {
  49509. scene.resetCachedMaterial();
  49510. }
  49511. this._renderId = scene.getRenderId();
  49512. return true;
  49513. };
  49514. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  49515. var scene = this.getScene();
  49516. if (this._options.uniforms.indexOf("world") !== -1) {
  49517. this._effect.setMatrix("world", world);
  49518. }
  49519. if (this._options.uniforms.indexOf("worldView") !== -1) {
  49520. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  49521. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  49522. }
  49523. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  49524. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  49525. }
  49526. };
  49527. ShaderMaterial.prototype.bind = function (world, mesh) {
  49528. // Std values
  49529. this.bindOnlyWorldMatrix(world);
  49530. if (this.getScene().getCachedMaterial() !== this) {
  49531. if (this._options.uniforms.indexOf("view") !== -1) {
  49532. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  49533. }
  49534. if (this._options.uniforms.indexOf("projection") !== -1) {
  49535. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  49536. }
  49537. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  49538. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  49539. }
  49540. // Bones
  49541. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  49542. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  49543. }
  49544. var name;
  49545. // Texture
  49546. for (name in this._textures) {
  49547. this._effect.setTexture(name, this._textures[name]);
  49548. }
  49549. // Texture arrays
  49550. for (name in this._textureArrays) {
  49551. this._effect.setTextureArray(name, this._textureArrays[name]);
  49552. }
  49553. // Float
  49554. for (name in this._floats) {
  49555. this._effect.setFloat(name, this._floats[name]);
  49556. }
  49557. // Float s
  49558. for (name in this._floatsArrays) {
  49559. this._effect.setArray(name, this._floatsArrays[name]);
  49560. }
  49561. // Color3
  49562. for (name in this._colors3) {
  49563. this._effect.setColor3(name, this._colors3[name]);
  49564. }
  49565. // Color4
  49566. for (name in this._colors4) {
  49567. var color = this._colors4[name];
  49568. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  49569. }
  49570. // Vector2
  49571. for (name in this._vectors2) {
  49572. this._effect.setVector2(name, this._vectors2[name]);
  49573. }
  49574. // Vector3
  49575. for (name in this._vectors3) {
  49576. this._effect.setVector3(name, this._vectors3[name]);
  49577. }
  49578. // Vector4
  49579. for (name in this._vectors4) {
  49580. this._effect.setVector4(name, this._vectors4[name]);
  49581. }
  49582. // Matrix
  49583. for (name in this._matrices) {
  49584. this._effect.setMatrix(name, this._matrices[name]);
  49585. }
  49586. // Matrix 3x3
  49587. for (name in this._matrices3x3) {
  49588. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  49589. }
  49590. // Matrix 2x2
  49591. for (name in this._matrices2x2) {
  49592. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  49593. }
  49594. }
  49595. _super.prototype.bind.call(this, world, mesh);
  49596. };
  49597. ShaderMaterial.prototype.clone = function (name) {
  49598. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  49599. return newShaderMaterial;
  49600. };
  49601. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  49602. if (forceDisposeTextures) {
  49603. var name;
  49604. for (name in this._textures) {
  49605. this._textures[name].dispose();
  49606. }
  49607. for (name in this._textureArrays) {
  49608. var array = this._textureArrays[name];
  49609. for (var index = 0; index < array.length; index++) {
  49610. array[index].dispose();
  49611. }
  49612. }
  49613. }
  49614. this._textures = {};
  49615. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  49616. };
  49617. ShaderMaterial.prototype.serialize = function () {
  49618. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  49619. serializationObject.customType = "BABYLON.ShaderMaterial";
  49620. serializationObject.options = this._options;
  49621. serializationObject.shaderPath = this._shaderPath;
  49622. var name;
  49623. // Texture
  49624. serializationObject.textures = {};
  49625. for (name in this._textures) {
  49626. serializationObject.textures[name] = this._textures[name].serialize();
  49627. }
  49628. // Texture arrays
  49629. serializationObject.textureArrays = {};
  49630. for (name in this._textureArrays) {
  49631. serializationObject.textureArrays[name] = [];
  49632. var array = this._textureArrays[name];
  49633. for (var index = 0; index < array.length; index++) {
  49634. serializationObject.textureArrays[name].push(array[index].serialize());
  49635. }
  49636. }
  49637. // Float
  49638. serializationObject.floats = {};
  49639. for (name in this._floats) {
  49640. serializationObject.floats[name] = this._floats[name];
  49641. }
  49642. // Float s
  49643. serializationObject.floatArrays = {};
  49644. for (name in this._floatsArrays) {
  49645. serializationObject.floatArrays[name] = this._floatsArrays[name];
  49646. }
  49647. // Color3
  49648. serializationObject.colors3 = {};
  49649. for (name in this._colors3) {
  49650. serializationObject.colors3[name] = this._colors3[name].asArray();
  49651. }
  49652. // Color4
  49653. serializationObject.colors4 = {};
  49654. for (name in this._colors4) {
  49655. serializationObject.colors4[name] = this._colors4[name].asArray();
  49656. }
  49657. // Vector2
  49658. serializationObject.vectors2 = {};
  49659. for (name in this._vectors2) {
  49660. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  49661. }
  49662. // Vector3
  49663. serializationObject.vectors3 = {};
  49664. for (name in this._vectors3) {
  49665. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  49666. }
  49667. // Vector4
  49668. serializationObject.vectors4 = {};
  49669. for (name in this._vectors4) {
  49670. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  49671. }
  49672. // Matrix
  49673. serializationObject.matrices = {};
  49674. for (name in this._matrices) {
  49675. serializationObject.matrices[name] = this._matrices[name].asArray();
  49676. }
  49677. // Matrix 3x3
  49678. serializationObject.matrices3x3 = {};
  49679. for (name in this._matrices3x3) {
  49680. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  49681. }
  49682. // Matrix 2x2
  49683. serializationObject.matrices2x2 = {};
  49684. for (name in this._matrices2x2) {
  49685. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  49686. }
  49687. return serializationObject;
  49688. };
  49689. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  49690. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  49691. var name;
  49692. // Texture
  49693. for (name in source.textures) {
  49694. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  49695. }
  49696. // Texture arrays
  49697. for (name in source.textureArrays) {
  49698. var array = source.textureArrays[name];
  49699. var textureArray = new Array();
  49700. for (var index = 0; index < array.length; index++) {
  49701. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  49702. }
  49703. material.setTextureArray(name, textureArray);
  49704. }
  49705. // Float
  49706. for (name in source.floats) {
  49707. material.setFloat(name, source.floats[name]);
  49708. }
  49709. // Float s
  49710. for (name in source.floatsArrays) {
  49711. material.setFloats(name, source.floatsArrays[name]);
  49712. }
  49713. // Color3
  49714. for (name in source.colors3) {
  49715. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  49716. }
  49717. // Color4
  49718. for (name in source.colors4) {
  49719. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  49720. }
  49721. // Vector2
  49722. for (name in source.vectors2) {
  49723. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  49724. }
  49725. // Vector3
  49726. for (name in source.vectors3) {
  49727. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  49728. }
  49729. // Vector4
  49730. for (name in source.vectors4) {
  49731. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  49732. }
  49733. // Matrix
  49734. for (name in source.matrices) {
  49735. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  49736. }
  49737. // Matrix 3x3
  49738. for (name in source.matrices3x3) {
  49739. material.setMatrix3x3(name, source.matrices3x3[name]);
  49740. }
  49741. // Matrix 2x2
  49742. for (name in source.matrices2x2) {
  49743. material.setMatrix2x2(name, source.matrices2x2[name]);
  49744. }
  49745. return material;
  49746. };
  49747. return ShaderMaterial;
  49748. })(BABYLON.Material);
  49749. BABYLON.ShaderMaterial = ShaderMaterial;
  49750. })(BABYLON || (BABYLON = {}));
  49751. var BABYLON;
  49752. (function (BABYLON) {
  49753. var Internals;
  49754. (function (Internals) {
  49755. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  49756. // All values and structures referenced from:
  49757. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  49758. var DDS_MAGIC = 0x20534444;
  49759. 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;
  49760. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  49761. 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;
  49762. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  49763. function FourCCToInt32(value) {
  49764. return value.charCodeAt(0) +
  49765. (value.charCodeAt(1) << 8) +
  49766. (value.charCodeAt(2) << 16) +
  49767. (value.charCodeAt(3) << 24);
  49768. }
  49769. function Int32ToFourCC(value) {
  49770. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  49771. }
  49772. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  49773. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  49774. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  49775. var headerLengthInt = 31; // The header length in 32 bit ints
  49776. // Offsets into the header array
  49777. var off_magic = 0;
  49778. var off_size = 1;
  49779. var off_flags = 2;
  49780. var off_height = 3;
  49781. var off_width = 4;
  49782. var off_mipmapCount = 7;
  49783. var off_pfFlags = 20;
  49784. var off_pfFourCC = 21;
  49785. var off_RGBbpp = 22;
  49786. var off_RMask = 23;
  49787. var off_GMask = 24;
  49788. var off_BMask = 25;
  49789. var off_AMask = 26;
  49790. var off_caps1 = 27;
  49791. var off_caps2 = 28;
  49792. ;
  49793. var DDSTools = (function () {
  49794. function DDSTools() {
  49795. }
  49796. DDSTools.GetDDSInfo = function (arrayBuffer) {
  49797. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  49798. var mipmapCount = 1;
  49799. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  49800. mipmapCount = Math.max(1, header[off_mipmapCount]);
  49801. }
  49802. return {
  49803. width: header[off_width],
  49804. height: header[off_height],
  49805. mipmapCount: mipmapCount,
  49806. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  49807. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  49808. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  49809. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  49810. };
  49811. };
  49812. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  49813. var byteArray = new Uint8Array(dataLength);
  49814. var srcData = new Uint8Array(arrayBuffer);
  49815. var index = 0;
  49816. for (var y = height - 1; y >= 0; y--) {
  49817. for (var x = 0; x < width; x++) {
  49818. var srcPos = dataOffset + (x + y * width) * 4;
  49819. byteArray[index + 2] = srcData[srcPos];
  49820. byteArray[index + 1] = srcData[srcPos + 1];
  49821. byteArray[index] = srcData[srcPos + 2];
  49822. byteArray[index + 3] = srcData[srcPos + 3];
  49823. index += 4;
  49824. }
  49825. }
  49826. return byteArray;
  49827. };
  49828. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  49829. var byteArray = new Uint8Array(dataLength);
  49830. var srcData = new Uint8Array(arrayBuffer);
  49831. var index = 0;
  49832. for (var y = height - 1; y >= 0; y--) {
  49833. for (var x = 0; x < width; x++) {
  49834. var srcPos = dataOffset + (x + y * width) * 3;
  49835. byteArray[index + 2] = srcData[srcPos];
  49836. byteArray[index + 1] = srcData[srcPos + 1];
  49837. byteArray[index] = srcData[srcPos + 2];
  49838. index += 3;
  49839. }
  49840. }
  49841. return byteArray;
  49842. };
  49843. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  49844. var byteArray = new Uint8Array(dataLength);
  49845. var srcData = new Uint8Array(arrayBuffer);
  49846. var index = 0;
  49847. for (var y = height - 1; y >= 0; y--) {
  49848. for (var x = 0; x < width; x++) {
  49849. var srcPos = dataOffset + (x + y * width);
  49850. byteArray[index] = srcData[srcPos];
  49851. index++;
  49852. }
  49853. }
  49854. return byteArray;
  49855. };
  49856. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  49857. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  49858. if (header[off_magic] != DDS_MAGIC) {
  49859. BABYLON.Tools.Error("Invalid magic number in DDS header");
  49860. return;
  49861. }
  49862. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  49863. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  49864. return;
  49865. }
  49866. if (info.isFourCC) {
  49867. fourCC = header[off_pfFourCC];
  49868. switch (fourCC) {
  49869. case FOURCC_DXT1:
  49870. blockBytes = 8;
  49871. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  49872. break;
  49873. case FOURCC_DXT3:
  49874. blockBytes = 16;
  49875. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  49876. break;
  49877. case FOURCC_DXT5:
  49878. blockBytes = 16;
  49879. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  49880. break;
  49881. default:
  49882. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  49883. return;
  49884. }
  49885. }
  49886. mipmapCount = 1;
  49887. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  49888. mipmapCount = Math.max(1, header[off_mipmapCount]);
  49889. }
  49890. var bpp = header[off_RGBbpp];
  49891. for (var face = 0; face < faces; face++) {
  49892. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  49893. width = header[off_width];
  49894. height = header[off_height];
  49895. dataOffset = header[off_size] + 4;
  49896. for (i = 0; i < mipmapCount; ++i) {
  49897. if (info.isRGB) {
  49898. if (bpp === 24) {
  49899. dataLength = width * height * 3;
  49900. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  49901. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  49902. }
  49903. else {
  49904. dataLength = width * height * 4;
  49905. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  49906. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  49907. }
  49908. }
  49909. else if (info.isLuminance) {
  49910. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  49911. var unpaddedRowSize = width;
  49912. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  49913. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  49914. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  49915. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  49916. }
  49917. else {
  49918. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  49919. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  49920. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  49921. }
  49922. dataOffset += dataLength;
  49923. width *= 0.5;
  49924. height *= 0.5;
  49925. width = Math.max(1.0, width);
  49926. height = Math.max(1.0, height);
  49927. }
  49928. }
  49929. };
  49930. return DDSTools;
  49931. })();
  49932. Internals.DDSTools = DDSTools;
  49933. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49934. })(BABYLON || (BABYLON = {}));
  49935. var BABYLON;
  49936. (function (BABYLON) {
  49937. var CannonJSPlugin = (function () {
  49938. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  49939. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  49940. if (iterations === void 0) { iterations = 10; }
  49941. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  49942. this.name = "CannonJSPlugin";
  49943. this._physicsMaterials = [];
  49944. this._fixedTimeStep = 1 / 60;
  49945. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  49946. this._currentCollisionGroup = 2;
  49947. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  49948. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  49949. this._tmpPosition = BABYLON.Vector3.Zero();
  49950. this._tmpQuaternion = new BABYLON.Quaternion();
  49951. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  49952. this._tmpDeltaRotation = new BABYLON.Quaternion();
  49953. this._tmpUnityRotation = new BABYLON.Quaternion();
  49954. if (!this.isSupported()) {
  49955. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  49956. return;
  49957. }
  49958. this.world = new CANNON.World();
  49959. this.world.broadphase = new CANNON.NaiveBroadphase();
  49960. this.world.solver.iterations = iterations;
  49961. }
  49962. CannonJSPlugin.prototype.setGravity = function (gravity) {
  49963. this.world.gravity.copy(gravity);
  49964. };
  49965. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  49966. this._fixedTimeStep = timeStep;
  49967. };
  49968. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  49969. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  49970. };
  49971. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  49972. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  49973. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  49974. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  49975. };
  49976. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  49977. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  49978. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  49979. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  49980. };
  49981. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  49982. //parent-child relationship. Does this impostor has a parent impostor?
  49983. if (impostor.parent) {
  49984. if (impostor.physicsBody) {
  49985. this.removePhysicsBody(impostor);
  49986. //TODO is that needed?
  49987. impostor.forceUpdate();
  49988. }
  49989. return;
  49990. }
  49991. //should a new body be created for this impostor?
  49992. if (impostor.isBodyInitRequired()) {
  49993. var shape = this._createShape(impostor);
  49994. //unregister events, if body is being changed
  49995. var oldBody = impostor.physicsBody;
  49996. if (oldBody) {
  49997. this.removePhysicsBody(impostor);
  49998. }
  49999. //create the body and material
  50000. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  50001. var bodyCreationObject = {
  50002. mass: impostor.getParam("mass"),
  50003. material: material
  50004. };
  50005. // A simple extend, in case native options were used.
  50006. var nativeOptions = impostor.getParam("nativeOptions");
  50007. for (var key in nativeOptions) {
  50008. if (nativeOptions.hasOwnProperty(key)) {
  50009. bodyCreationObject[key] = nativeOptions[key];
  50010. }
  50011. }
  50012. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  50013. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  50014. this.world.addEventListener("preStep", impostor.beforeStep);
  50015. this.world.addEventListener("postStep", impostor.afterStep);
  50016. impostor.physicsBody.addShape(shape);
  50017. this.world.add(impostor.physicsBody);
  50018. //try to keep the body moving in the right direction by taking old properties.
  50019. //Should be tested!
  50020. if (oldBody) {
  50021. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  50022. impostor.physicsBody[param].copy(oldBody[param]);
  50023. });
  50024. }
  50025. this._processChildMeshes(impostor);
  50026. }
  50027. //now update the body's transformation
  50028. this._updatePhysicsBodyTransformation(impostor);
  50029. };
  50030. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  50031. var _this = this;
  50032. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  50033. if (meshChildren.length) {
  50034. var processMesh = function (localPosition, mesh) {
  50035. var childImpostor = mesh.getPhysicsImpostor();
  50036. if (childImpostor) {
  50037. var parent = childImpostor.parent;
  50038. if (parent !== mainImpostor) {
  50039. var localPosition = mesh.position;
  50040. if (childImpostor.physicsBody) {
  50041. _this.removePhysicsBody(childImpostor);
  50042. childImpostor.physicsBody = null;
  50043. }
  50044. childImpostor.parent = mainImpostor;
  50045. childImpostor.resetUpdateFlags();
  50046. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  50047. //Add the mass of the children.
  50048. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  50049. }
  50050. }
  50051. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  50052. };
  50053. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  50054. }
  50055. };
  50056. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  50057. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  50058. this.world.removeEventListener("preStep", impostor.beforeStep);
  50059. this.world.removeEventListener("postStep", impostor.afterStep);
  50060. this.world.remove(impostor.physicsBody);
  50061. };
  50062. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  50063. var mainBody = impostorJoint.mainImpostor.physicsBody;
  50064. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  50065. if (!mainBody || !connectedBody) {
  50066. return;
  50067. }
  50068. var constraint;
  50069. var jointData = impostorJoint.joint.jointData;
  50070. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  50071. var constraintData = {
  50072. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  50073. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  50074. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  50075. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  50076. maxForce: jointData.nativeParams.maxForce,
  50077. collideConnected: !!jointData.collision
  50078. };
  50079. //Not needed, Cannon has a collideConnected flag
  50080. /*if (!jointData.collision) {
  50081. //add 1st body to a collision group of its own, if it is not in 1
  50082. if (mainBody.collisionFilterGroup === 1) {
  50083. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  50084. this._currentCollisionGroup <<= 1;
  50085. }
  50086. if (connectedBody.collisionFilterGroup === 1) {
  50087. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  50088. this._currentCollisionGroup <<= 1;
  50089. }
  50090. //add their mask to the collisionFilterMask of each other:
  50091. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  50092. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  50093. }*/
  50094. switch (impostorJoint.joint.type) {
  50095. case BABYLON.PhysicsJoint.HingeJoint:
  50096. case BABYLON.PhysicsJoint.Hinge2Joint:
  50097. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  50098. break;
  50099. case BABYLON.PhysicsJoint.DistanceJoint:
  50100. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  50101. break;
  50102. case BABYLON.PhysicsJoint.SpringJoint:
  50103. var springData = jointData;
  50104. constraint = new CANNON.Spring(mainBody, connectedBody, {
  50105. restLength: springData.length,
  50106. stiffness: springData.stiffness,
  50107. damping: springData.damping,
  50108. localAnchorA: constraintData.pivotA,
  50109. localAnchorB: constraintData.pivotB
  50110. });
  50111. break;
  50112. case BABYLON.PhysicsJoint.LockJoint:
  50113. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  50114. break;
  50115. case BABYLON.PhysicsJoint.PointToPointJoint:
  50116. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  50117. default:
  50118. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  50119. break;
  50120. }
  50121. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  50122. constraint.collideConnected = !!jointData.collision;
  50123. impostorJoint.joint.physicsJoint = constraint;
  50124. //don't add spring as constraint, as it is not one.
  50125. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  50126. this.world.addConstraint(constraint);
  50127. }
  50128. else {
  50129. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  50130. constraint.applyForce();
  50131. });
  50132. }
  50133. };
  50134. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  50135. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  50136. };
  50137. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  50138. var index;
  50139. var mat;
  50140. for (index = 0; index < this._physicsMaterials.length; index++) {
  50141. mat = this._physicsMaterials[index];
  50142. if (mat.friction === friction && mat.restitution === restitution) {
  50143. return mat;
  50144. }
  50145. }
  50146. var currentMat = new CANNON.Material(name);
  50147. currentMat.friction = friction;
  50148. currentMat.restitution = restitution;
  50149. this._physicsMaterials.push(currentMat);
  50150. return currentMat;
  50151. };
  50152. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  50153. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  50154. };
  50155. CannonJSPlugin.prototype._createShape = function (impostor) {
  50156. var object = impostor.object;
  50157. var returnValue;
  50158. var extendSize = impostor.getObjectExtendSize();
  50159. switch (impostor.type) {
  50160. case BABYLON.PhysicsEngine.SphereImpostor:
  50161. var radiusX = extendSize.x;
  50162. var radiusY = extendSize.y;
  50163. var radiusZ = extendSize.z;
  50164. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  50165. break;
  50166. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  50167. case BABYLON.PhysicsImpostor.CylinderImpostor:
  50168. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  50169. break;
  50170. case BABYLON.PhysicsImpostor.BoxImpostor:
  50171. var box = extendSize.scale(0.5);
  50172. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  50173. break;
  50174. case BABYLON.PhysicsImpostor.PlaneImpostor:
  50175. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  50176. returnValue = new CANNON.Plane();
  50177. break;
  50178. case BABYLON.PhysicsImpostor.MeshImpostor:
  50179. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  50180. var rawFaces = object.getIndices ? object.getIndices() : [];
  50181. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  50182. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  50183. break;
  50184. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  50185. returnValue = this._createHeightmap(object);
  50186. break;
  50187. case BABYLON.PhysicsImpostor.ParticleImpostor:
  50188. returnValue = new CANNON.Particle();
  50189. break;
  50190. }
  50191. return returnValue;
  50192. };
  50193. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  50194. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50195. var matrix = [];
  50196. //For now pointDepth will not be used and will be automatically calculated.
  50197. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  50198. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  50199. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  50200. var elementSize = dim * 2 / arraySize;
  50201. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  50202. for (var i = 0; i < pos.length; i = i + 3) {
  50203. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  50204. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  50205. var y = pos[i + 1] + minY;
  50206. if (!matrix[x]) {
  50207. matrix[x] = [];
  50208. }
  50209. if (!matrix[x][z]) {
  50210. matrix[x][z] = y;
  50211. }
  50212. matrix[x][z] = Math.max(y, matrix[x][z]);
  50213. }
  50214. for (var x = 0; x <= arraySize; ++x) {
  50215. if (!matrix[x]) {
  50216. var loc = 1;
  50217. while (!matrix[(x + loc) % arraySize]) {
  50218. loc++;
  50219. }
  50220. matrix[x] = matrix[(x + loc) % arraySize].slice();
  50221. }
  50222. for (var z = 0; z <= arraySize; ++z) {
  50223. if (!matrix[x][z]) {
  50224. var loc = 1;
  50225. var newValue;
  50226. while (newValue === undefined) {
  50227. newValue = matrix[x][(z + loc++) % arraySize];
  50228. }
  50229. matrix[x][z] = newValue;
  50230. }
  50231. }
  50232. }
  50233. var shape = new CANNON.Heightfield(matrix, {
  50234. elementSize: elementSize
  50235. });
  50236. //For future reference, needed for body transformation
  50237. shape.minY = minY;
  50238. return shape;
  50239. };
  50240. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  50241. var object = impostor.object;
  50242. //make sure it is updated...
  50243. object.computeWorldMatrix && object.computeWorldMatrix(true);
  50244. // The delta between the mesh position and the mesh bounding box center
  50245. var center = impostor.getObjectCenter();
  50246. var extendSize = impostor.getObjectExtendSize();
  50247. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  50248. this._tmpPosition.copyFrom(center);
  50249. var quaternion = object.rotationQuaternion;
  50250. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  50251. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  50252. //-90 DEG in X, precalculated
  50253. quaternion = quaternion.multiply(this._minus90X);
  50254. //Invert! (Precalculated, 90 deg in X)
  50255. //No need to clone. this will never change.
  50256. impostor.setDeltaRotation(this._plus90X);
  50257. }
  50258. //If it is a heightfield, if should be centered.
  50259. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  50260. var mesh = object;
  50261. //calculate the correct body position:
  50262. var rotationQuaternion = mesh.rotationQuaternion;
  50263. mesh.rotationQuaternion = this._tmpUnityRotation;
  50264. mesh.computeWorldMatrix(true);
  50265. //get original center with no rotation
  50266. var c = center.clone();
  50267. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  50268. //rotation is back
  50269. mesh.rotationQuaternion = rotationQuaternion;
  50270. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  50271. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  50272. mesh.setPivotMatrix(p);
  50273. mesh.computeWorldMatrix(true);
  50274. //calculate the translation
  50275. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  50276. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  50277. //add it inverted to the delta
  50278. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  50279. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  50280. mesh.setPivotMatrix(oldPivot);
  50281. mesh.computeWorldMatrix(true);
  50282. }
  50283. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  50284. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  50285. this._tmpPosition.copyFrom(object.position);
  50286. }
  50287. impostor.setDeltaPosition(this._tmpDeltaPosition);
  50288. //Now update the impostor object
  50289. impostor.physicsBody.position.copy(this._tmpPosition);
  50290. impostor.physicsBody.quaternion.copy(quaternion);
  50291. };
  50292. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  50293. impostor.object.position.copyFrom(impostor.physicsBody.position);
  50294. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  50295. };
  50296. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  50297. impostor.physicsBody.position.copy(newPosition);
  50298. impostor.physicsBody.quaternion.copy(newRotation);
  50299. };
  50300. CannonJSPlugin.prototype.isSupported = function () {
  50301. return window.CANNON !== undefined;
  50302. };
  50303. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  50304. impostor.physicsBody.velocity.copy(velocity);
  50305. };
  50306. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  50307. impostor.physicsBody.angularVelocity.copy(velocity);
  50308. };
  50309. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  50310. var v = impostor.physicsBody.velocity;
  50311. if (!v)
  50312. return null;
  50313. return new BABYLON.Vector3(v.x, v.y, v.z);
  50314. };
  50315. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  50316. var v = impostor.physicsBody.angularVelocity;
  50317. if (!v)
  50318. return null;
  50319. return new BABYLON.Vector3(v.x, v.y, v.z);
  50320. };
  50321. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  50322. impostor.physicsBody.mass = mass;
  50323. impostor.physicsBody.updateMassProperties();
  50324. };
  50325. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  50326. impostor.physicsBody.sleep();
  50327. };
  50328. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  50329. impostor.physicsBody.wakeUp();
  50330. };
  50331. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  50332. joint.physicsJoint.distance = maxDistance;
  50333. };
  50334. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  50335. if (!motorIndex) {
  50336. joint.physicsJoint.enableMotor();
  50337. }
  50338. };
  50339. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  50340. if (!motorIndex) {
  50341. joint.physicsJoint.disableMotor();
  50342. }
  50343. };
  50344. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  50345. if (!motorIndex) {
  50346. joint.physicsJoint.enableMotor();
  50347. joint.physicsJoint.setMotorSpeed(speed);
  50348. if (maxForce) {
  50349. this.setLimit(joint, maxForce);
  50350. }
  50351. }
  50352. };
  50353. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  50354. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  50355. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  50356. };
  50357. CannonJSPlugin.prototype.dispose = function () {
  50358. //nothing to do, actually.
  50359. };
  50360. return CannonJSPlugin;
  50361. })();
  50362. BABYLON.CannonJSPlugin = CannonJSPlugin;
  50363. })(BABYLON || (BABYLON = {}));
  50364. var BABYLON;
  50365. (function (BABYLON) {
  50366. var OimoJSPlugin = (function () {
  50367. function OimoJSPlugin(iterations) {
  50368. this.name = "OimoJSPlugin";
  50369. this._tmpImpostorsArray = [];
  50370. this._tmpPositionVector = BABYLON.Vector3.Zero();
  50371. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  50372. this.world.clear();
  50373. //making sure no stats are calculated
  50374. this.world.isNoStat = true;
  50375. }
  50376. OimoJSPlugin.prototype.setGravity = function (gravity) {
  50377. this.world.gravity.copy(gravity);
  50378. };
  50379. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  50380. this.world.timeStep = timeStep;
  50381. };
  50382. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  50383. var _this = this;
  50384. impostors.forEach(function (impostor) {
  50385. impostor.beforeStep();
  50386. });
  50387. this.world.step();
  50388. impostors.forEach(function (impostor) {
  50389. impostor.afterStep();
  50390. //update the ordered impostors array
  50391. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  50392. });
  50393. //check for collisions
  50394. var contact = this.world.contacts;
  50395. while (contact !== null) {
  50396. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  50397. contact = contact.next;
  50398. continue;
  50399. }
  50400. //is this body colliding with any other? get the impostor
  50401. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  50402. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  50403. if (!mainImpostor || !collidingImpostor) {
  50404. contact = contact.next;
  50405. continue;
  50406. }
  50407. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  50408. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  50409. contact = contact.next;
  50410. }
  50411. };
  50412. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  50413. var mass = impostor.physicsBody.massInfo.mass;
  50414. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  50415. };
  50416. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  50417. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  50418. this.applyImpulse(impostor, force, contactPoint);
  50419. };
  50420. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  50421. var _this = this;
  50422. //parent-child relationship. Does this impostor has a parent impostor?
  50423. if (impostor.parent) {
  50424. if (impostor.physicsBody) {
  50425. this.removePhysicsBody(impostor);
  50426. //TODO is that needed?
  50427. impostor.forceUpdate();
  50428. }
  50429. return;
  50430. }
  50431. if (impostor.isBodyInitRequired()) {
  50432. var bodyConfig = {
  50433. name: impostor.uniqueId,
  50434. //Oimo must have mass, also for static objects.
  50435. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  50436. size: [],
  50437. type: [],
  50438. pos: [],
  50439. rot: [],
  50440. move: impostor.getParam("mass") !== 0,
  50441. //Supporting older versions of Oimo
  50442. world: this.world
  50443. };
  50444. var impostors = [impostor];
  50445. function addToArray(parent) {
  50446. if (!parent.getChildMeshes)
  50447. return;
  50448. parent.getChildMeshes().forEach(function (m) {
  50449. if (m.physicsImpostor) {
  50450. impostors.push(m.physicsImpostor);
  50451. m.physicsImpostor._init();
  50452. }
  50453. });
  50454. }
  50455. addToArray(impostor.object);
  50456. function checkWithEpsilon(value) {
  50457. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  50458. }
  50459. impostors.forEach(function (i) {
  50460. //get the correct bounding box
  50461. var oldQuaternion = i.object.rotationQuaternion;
  50462. var rot = new OIMO.Euler().setFromQuaternion({
  50463. x: impostor.object.rotationQuaternion.x,
  50464. y: impostor.object.rotationQuaternion.y,
  50465. z: impostor.object.rotationQuaternion.z,
  50466. s: impostor.object.rotationQuaternion.w
  50467. });
  50468. var extendSize = i.getObjectExtendSize();
  50469. if (i === impostor) {
  50470. var center = impostor.getObjectCenter();
  50471. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  50472. //Can also use Array.prototype.push.apply
  50473. bodyConfig.pos.push(center.x);
  50474. bodyConfig.pos.push(center.y);
  50475. bodyConfig.pos.push(center.z);
  50476. //tmp solution
  50477. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  50478. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  50479. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  50480. }
  50481. else {
  50482. bodyConfig.pos.push(i.object.position.x);
  50483. bodyConfig.pos.push(i.object.position.y);
  50484. bodyConfig.pos.push(i.object.position.z);
  50485. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  50486. bodyConfig.rot.push(0);
  50487. bodyConfig.rot.push(0);
  50488. bodyConfig.rot.push(0);
  50489. }
  50490. // register mesh
  50491. switch (i.type) {
  50492. case BABYLON.PhysicsImpostor.ParticleImpostor:
  50493. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  50494. case BABYLON.PhysicsImpostor.SphereImpostor:
  50495. var radiusX = extendSize.x;
  50496. var radiusY = extendSize.y;
  50497. var radiusZ = extendSize.z;
  50498. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  50499. bodyConfig.type.push('sphere');
  50500. //due to the way oimo works with compounds, add 3 times
  50501. bodyConfig.size.push(size);
  50502. bodyConfig.size.push(size);
  50503. bodyConfig.size.push(size);
  50504. break;
  50505. case BABYLON.PhysicsImpostor.CylinderImpostor:
  50506. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  50507. var sizeY = checkWithEpsilon(extendSize.y);
  50508. bodyConfig.type.push('cylinder');
  50509. bodyConfig.size.push(sizeX);
  50510. bodyConfig.size.push(sizeY);
  50511. //due to the way oimo works with compounds, add one more value.
  50512. bodyConfig.size.push(sizeY);
  50513. break;
  50514. case BABYLON.PhysicsImpostor.PlaneImpostor:
  50515. case BABYLON.PhysicsImpostor.BoxImpostor:
  50516. default:
  50517. var sizeX = checkWithEpsilon(extendSize.x);
  50518. var sizeY = checkWithEpsilon(extendSize.y);
  50519. var sizeZ = checkWithEpsilon(extendSize.z);
  50520. bodyConfig.type.push('box');
  50521. bodyConfig.size.push(sizeX);
  50522. bodyConfig.size.push(sizeY);
  50523. bodyConfig.size.push(sizeZ);
  50524. break;
  50525. }
  50526. //actually not needed, but hey...
  50527. i.object.rotationQuaternion = oldQuaternion;
  50528. });
  50529. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  50530. }
  50531. else {
  50532. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  50533. }
  50534. impostor.setDeltaPosition(this._tmpPositionVector);
  50535. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  50536. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  50537. };
  50538. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  50539. //impostor.physicsBody.dispose();
  50540. //Same as : (older oimo versions)
  50541. this.world.removeRigidBody(impostor.physicsBody);
  50542. };
  50543. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  50544. var mainBody = impostorJoint.mainImpostor.physicsBody;
  50545. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  50546. if (!mainBody || !connectedBody) {
  50547. return;
  50548. }
  50549. var jointData = impostorJoint.joint.jointData;
  50550. var options = jointData.nativeParams || {};
  50551. var type;
  50552. var nativeJointData = {
  50553. body1: mainBody,
  50554. body2: connectedBody,
  50555. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  50556. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  50557. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  50558. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  50559. min: options.min,
  50560. max: options.max,
  50561. collision: options.collision || jointData.collision,
  50562. spring: options.spring,
  50563. //supporting older version of Oimo
  50564. world: this.world
  50565. };
  50566. switch (impostorJoint.joint.type) {
  50567. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  50568. type = "jointBall";
  50569. break;
  50570. case BABYLON.PhysicsJoint.SpringJoint:
  50571. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  50572. var springData = jointData;
  50573. nativeJointData.min = springData.length || nativeJointData.min;
  50574. //Max should also be set, just make sure it is at least min
  50575. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  50576. case BABYLON.PhysicsJoint.DistanceJoint:
  50577. type = "jointDistance";
  50578. nativeJointData.max = jointData.maxDistance;
  50579. break;
  50580. case BABYLON.PhysicsJoint.PrismaticJoint:
  50581. type = "jointPrisme";
  50582. break;
  50583. case BABYLON.PhysicsJoint.SliderJoint:
  50584. type = "jointSlide";
  50585. break;
  50586. case BABYLON.PhysicsJoint.WheelJoint:
  50587. type = "jointWheel";
  50588. break;
  50589. case BABYLON.PhysicsJoint.HingeJoint:
  50590. default:
  50591. type = "jointHinge";
  50592. break;
  50593. }
  50594. nativeJointData.type = type;
  50595. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  50596. };
  50597. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  50598. //Bug in Oimo prevents us from disposing a joint in the playground
  50599. //joint.joint.physicsJoint.dispose();
  50600. //So we will bruteforce it!
  50601. try {
  50602. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  50603. }
  50604. catch (e) {
  50605. BABYLON.Tools.Warn(e);
  50606. }
  50607. };
  50608. OimoJSPlugin.prototype.isSupported = function () {
  50609. return OIMO !== undefined;
  50610. };
  50611. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  50612. if (!impostor.physicsBody.sleeping) {
  50613. //TODO check that
  50614. if (impostor.physicsBody.shapes.next) {
  50615. var parentShape = this._getLastShape(impostor.physicsBody);
  50616. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  50617. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  50618. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  50619. }
  50620. else {
  50621. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  50622. }
  50623. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  50624. impostor.object.rotationQuaternion.normalize();
  50625. }
  50626. };
  50627. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  50628. var body = impostor.physicsBody;
  50629. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  50630. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  50631. body.syncShapes();
  50632. body.awake();
  50633. };
  50634. OimoJSPlugin.prototype._getLastShape = function (body) {
  50635. var lastShape = body.shapes;
  50636. while (lastShape.next) {
  50637. lastShape = lastShape.next;
  50638. }
  50639. return lastShape;
  50640. };
  50641. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  50642. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  50643. };
  50644. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  50645. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  50646. };
  50647. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  50648. var v = impostor.physicsBody.linearVelocity;
  50649. if (!v)
  50650. return null;
  50651. return new BABYLON.Vector3(v.x, v.y, v.z);
  50652. };
  50653. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  50654. var v = impostor.physicsBody.angularVelocity;
  50655. if (!v)
  50656. return null;
  50657. return new BABYLON.Vector3(v.x, v.y, v.z);
  50658. };
  50659. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  50660. var staticBody = mass === 0;
  50661. //this will actually set the body's density and not its mass.
  50662. //But this is how oimo treats the mass variable.
  50663. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  50664. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  50665. };
  50666. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  50667. impostor.physicsBody.sleep();
  50668. };
  50669. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  50670. impostor.physicsBody.awake();
  50671. };
  50672. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  50673. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  50674. if (minDistance !== void 0) {
  50675. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  50676. }
  50677. };
  50678. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  50679. //TODO separate rotational and transational motors.
  50680. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  50681. if (motor) {
  50682. motor.setMotor(speed, maxForce);
  50683. }
  50684. };
  50685. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  50686. //TODO separate rotational and transational motors.
  50687. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  50688. if (motor) {
  50689. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  50690. }
  50691. };
  50692. OimoJSPlugin.prototype.dispose = function () {
  50693. this.world.clear();
  50694. };
  50695. return OimoJSPlugin;
  50696. })();
  50697. BABYLON.OimoJSPlugin = OimoJSPlugin;
  50698. })(BABYLON || (BABYLON = {}));
  50699. var BABYLON;
  50700. (function (BABYLON) {
  50701. var DisplayPassPostProcess = (function (_super) {
  50702. __extends(DisplayPassPostProcess, _super);
  50703. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  50704. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  50705. }
  50706. return DisplayPassPostProcess;
  50707. })(BABYLON.PostProcess);
  50708. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  50709. })(BABYLON || (BABYLON = {}));
  50710. var BABYLON;
  50711. (function (BABYLON) {
  50712. var SimplificationSettings = (function () {
  50713. function SimplificationSettings(quality, distance, optimizeMesh) {
  50714. this.quality = quality;
  50715. this.distance = distance;
  50716. this.optimizeMesh = optimizeMesh;
  50717. }
  50718. return SimplificationSettings;
  50719. })();
  50720. BABYLON.SimplificationSettings = SimplificationSettings;
  50721. var SimplificationQueue = (function () {
  50722. function SimplificationQueue() {
  50723. this.running = false;
  50724. this._simplificationArray = [];
  50725. }
  50726. SimplificationQueue.prototype.addTask = function (task) {
  50727. this._simplificationArray.push(task);
  50728. };
  50729. SimplificationQueue.prototype.executeNext = function () {
  50730. var task = this._simplificationArray.pop();
  50731. if (task) {
  50732. this.running = true;
  50733. this.runSimplification(task);
  50734. }
  50735. else {
  50736. this.running = false;
  50737. }
  50738. };
  50739. SimplificationQueue.prototype.runSimplification = function (task) {
  50740. var _this = this;
  50741. if (task.parallelProcessing) {
  50742. //parallel simplifier
  50743. task.settings.forEach(function (setting) {
  50744. var simplifier = _this.getSimplifier(task);
  50745. simplifier.simplify(setting, function (newMesh) {
  50746. task.mesh.addLODLevel(setting.distance, newMesh);
  50747. newMesh.isVisible = true;
  50748. //check if it is the last
  50749. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  50750. //all done, run the success callback.
  50751. task.successCallback();
  50752. }
  50753. _this.executeNext();
  50754. });
  50755. });
  50756. }
  50757. else {
  50758. //single simplifier.
  50759. var simplifier = this.getSimplifier(task);
  50760. var runDecimation = function (setting, callback) {
  50761. simplifier.simplify(setting, function (newMesh) {
  50762. task.mesh.addLODLevel(setting.distance, newMesh);
  50763. newMesh.isVisible = true;
  50764. //run the next quality level
  50765. callback();
  50766. });
  50767. };
  50768. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  50769. runDecimation(task.settings[loop.index], function () {
  50770. loop.executeNext();
  50771. });
  50772. }, function () {
  50773. //execution ended, run the success callback.
  50774. if (task.successCallback) {
  50775. task.successCallback();
  50776. }
  50777. _this.executeNext();
  50778. });
  50779. }
  50780. };
  50781. SimplificationQueue.prototype.getSimplifier = function (task) {
  50782. switch (task.simplificationType) {
  50783. case SimplificationType.QUADRATIC:
  50784. default:
  50785. return new QuadraticErrorSimplification(task.mesh);
  50786. }
  50787. };
  50788. return SimplificationQueue;
  50789. })();
  50790. BABYLON.SimplificationQueue = SimplificationQueue;
  50791. /**
  50792. * The implemented types of simplification.
  50793. * At the moment only Quadratic Error Decimation is implemented.
  50794. */
  50795. (function (SimplificationType) {
  50796. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  50797. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  50798. var SimplificationType = BABYLON.SimplificationType;
  50799. var DecimationTriangle = (function () {
  50800. function DecimationTriangle(vertices) {
  50801. this.vertices = vertices;
  50802. this.error = new Array(4);
  50803. this.deleted = false;
  50804. this.isDirty = false;
  50805. this.deletePending = false;
  50806. this.borderFactor = 0;
  50807. }
  50808. return DecimationTriangle;
  50809. })();
  50810. BABYLON.DecimationTriangle = DecimationTriangle;
  50811. var DecimationVertex = (function () {
  50812. function DecimationVertex(position, id) {
  50813. this.position = position;
  50814. this.id = id;
  50815. this.isBorder = true;
  50816. this.q = new QuadraticMatrix();
  50817. this.triangleCount = 0;
  50818. this.triangleStart = 0;
  50819. this.originalOffsets = [];
  50820. }
  50821. DecimationVertex.prototype.updatePosition = function (newPosition) {
  50822. this.position.copyFrom(newPosition);
  50823. };
  50824. return DecimationVertex;
  50825. })();
  50826. BABYLON.DecimationVertex = DecimationVertex;
  50827. var QuadraticMatrix = (function () {
  50828. function QuadraticMatrix(data) {
  50829. this.data = new Array(10);
  50830. for (var i = 0; i < 10; ++i) {
  50831. if (data && data[i]) {
  50832. this.data[i] = data[i];
  50833. }
  50834. else {
  50835. this.data[i] = 0;
  50836. }
  50837. }
  50838. }
  50839. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  50840. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  50841. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  50842. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  50843. return det;
  50844. };
  50845. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  50846. for (var i = 0; i < 10; ++i) {
  50847. this.data[i] += matrix.data[i];
  50848. }
  50849. };
  50850. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  50851. for (var i = 0; i < 10; ++i) {
  50852. this.data[i] += data[i];
  50853. }
  50854. };
  50855. QuadraticMatrix.prototype.add = function (matrix) {
  50856. var m = new QuadraticMatrix();
  50857. for (var i = 0; i < 10; ++i) {
  50858. m.data[i] = this.data[i] + matrix.data[i];
  50859. }
  50860. return m;
  50861. };
  50862. QuadraticMatrix.FromData = function (a, b, c, d) {
  50863. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  50864. };
  50865. //returning an array to avoid garbage collection
  50866. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  50867. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  50868. };
  50869. return QuadraticMatrix;
  50870. })();
  50871. BABYLON.QuadraticMatrix = QuadraticMatrix;
  50872. var Reference = (function () {
  50873. function Reference(vertexId, triangleId) {
  50874. this.vertexId = vertexId;
  50875. this.triangleId = triangleId;
  50876. }
  50877. return Reference;
  50878. })();
  50879. BABYLON.Reference = Reference;
  50880. /**
  50881. * An implementation of the Quadratic Error simplification algorithm.
  50882. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  50883. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  50884. * @author RaananW
  50885. */
  50886. var QuadraticErrorSimplification = (function () {
  50887. function QuadraticErrorSimplification(_mesh) {
  50888. this._mesh = _mesh;
  50889. this.initialized = false;
  50890. this.syncIterations = 5000;
  50891. this.aggressiveness = 7;
  50892. this.decimationIterations = 100;
  50893. this.boundingBoxEpsilon = BABYLON.Epsilon;
  50894. }
  50895. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  50896. var _this = this;
  50897. this.initDecimatedMesh();
  50898. //iterating through the submeshes array, one after the other.
  50899. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  50900. _this.initWithMesh(loop.index, function () {
  50901. _this.runDecimation(settings, loop.index, function () {
  50902. loop.executeNext();
  50903. });
  50904. }, settings.optimizeMesh);
  50905. }, function () {
  50906. setTimeout(function () {
  50907. successCallback(_this._reconstructedMesh);
  50908. }, 0);
  50909. });
  50910. };
  50911. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  50912. var _this = this;
  50913. var gCount = 0;
  50914. triangle.vertices.forEach(function (vertex) {
  50915. var count = 0;
  50916. var vPos = vertex.position;
  50917. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  50918. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  50919. ++count;
  50920. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  50921. ++count;
  50922. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  50923. ++count;
  50924. if (count > 1) {
  50925. ++gCount;
  50926. }
  50927. ;
  50928. });
  50929. if (gCount > 1) {
  50930. console.log(triangle, gCount);
  50931. }
  50932. return gCount > 1;
  50933. };
  50934. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  50935. var _this = this;
  50936. var targetCount = ~~(this.triangles.length * settings.quality);
  50937. var deletedTriangles = 0;
  50938. var triangleCount = this.triangles.length;
  50939. var iterationFunction = function (iteration, callback) {
  50940. setTimeout(function () {
  50941. if (iteration % 5 === 0) {
  50942. _this.updateMesh(iteration === 0);
  50943. }
  50944. for (var i = 0; i < _this.triangles.length; ++i) {
  50945. _this.triangles[i].isDirty = false;
  50946. }
  50947. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  50948. var trianglesIterator = function (i) {
  50949. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  50950. var t = _this.triangles[tIdx];
  50951. if (!t)
  50952. return;
  50953. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  50954. return;
  50955. }
  50956. for (var j = 0; j < 3; ++j) {
  50957. if (t.error[j] < threshold) {
  50958. var deleted0 = [];
  50959. var deleted1 = [];
  50960. var v0 = t.vertices[j];
  50961. var v1 = t.vertices[(j + 1) % 3];
  50962. if (v0.isBorder || v1.isBorder)
  50963. continue;
  50964. var p = BABYLON.Vector3.Zero();
  50965. var n = BABYLON.Vector3.Zero();
  50966. var uv = BABYLON.Vector2.Zero();
  50967. var color = new BABYLON.Color4(0, 0, 0, 1);
  50968. _this.calculateError(v0, v1, p, n, uv, color);
  50969. var delTr = [];
  50970. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  50971. continue;
  50972. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  50973. continue;
  50974. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  50975. continue;
  50976. var uniqueArray = [];
  50977. delTr.forEach(function (deletedT) {
  50978. if (uniqueArray.indexOf(deletedT) === -1) {
  50979. deletedT.deletePending = true;
  50980. uniqueArray.push(deletedT);
  50981. }
  50982. });
  50983. if (uniqueArray.length % 2 !== 0) {
  50984. continue;
  50985. }
  50986. v0.q = v1.q.add(v0.q);
  50987. v0.updatePosition(p);
  50988. var tStart = _this.references.length;
  50989. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  50990. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  50991. var tCount = _this.references.length - tStart;
  50992. if (tCount <= v0.triangleCount) {
  50993. if (tCount) {
  50994. for (var c = 0; c < tCount; c++) {
  50995. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  50996. }
  50997. }
  50998. }
  50999. else {
  51000. v0.triangleStart = tStart;
  51001. }
  51002. v0.triangleCount = tCount;
  51003. break;
  51004. }
  51005. }
  51006. };
  51007. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  51008. }, 0);
  51009. };
  51010. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  51011. if (triangleCount - deletedTriangles <= targetCount)
  51012. loop.breakLoop();
  51013. else {
  51014. iterationFunction(loop.index, function () {
  51015. loop.executeNext();
  51016. });
  51017. }
  51018. }, function () {
  51019. setTimeout(function () {
  51020. //reconstruct this part of the mesh
  51021. _this.reconstructMesh(submeshIndex);
  51022. successCallback();
  51023. }, 0);
  51024. });
  51025. };
  51026. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  51027. var _this = this;
  51028. this.vertices = [];
  51029. this.triangles = [];
  51030. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51031. var indices = this._mesh.getIndices();
  51032. var submesh = this._mesh.subMeshes[submeshIndex];
  51033. var findInVertices = function (positionToSearch) {
  51034. if (optimizeMesh) {
  51035. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  51036. if (_this.vertices[ii].position.equals(positionToSearch)) {
  51037. return _this.vertices[ii];
  51038. }
  51039. }
  51040. }
  51041. return null;
  51042. };
  51043. var vertexReferences = [];
  51044. var vertexInit = function (i) {
  51045. var offset = i + submesh.verticesStart;
  51046. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  51047. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  51048. vertex.originalOffsets.push(offset);
  51049. if (vertex.id === _this.vertices.length) {
  51050. _this.vertices.push(vertex);
  51051. }
  51052. vertexReferences.push(vertex.id);
  51053. };
  51054. //var totalVertices = mesh.getTotalVertices();
  51055. var totalVertices = submesh.verticesCount;
  51056. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  51057. var indicesInit = function (i) {
  51058. var offset = (submesh.indexStart / 3) + i;
  51059. var pos = (offset * 3);
  51060. var i0 = indices[pos + 0];
  51061. var i1 = indices[pos + 1];
  51062. var i2 = indices[pos + 2];
  51063. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  51064. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  51065. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  51066. var triangle = new DecimationTriangle([v0, v1, v2]);
  51067. triangle.originalOffset = pos;
  51068. _this.triangles.push(triangle);
  51069. };
  51070. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  51071. _this.init(callback);
  51072. });
  51073. });
  51074. };
  51075. QuadraticErrorSimplification.prototype.init = function (callback) {
  51076. var _this = this;
  51077. var triangleInit1 = function (i) {
  51078. var t = _this.triangles[i];
  51079. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  51080. for (var j = 0; j < 3; j++) {
  51081. 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))));
  51082. }
  51083. };
  51084. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  51085. var triangleInit2 = function (i) {
  51086. var t = _this.triangles[i];
  51087. for (var j = 0; j < 3; ++j) {
  51088. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  51089. }
  51090. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  51091. };
  51092. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  51093. _this.initialized = true;
  51094. callback();
  51095. });
  51096. });
  51097. };
  51098. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  51099. var newTriangles = [];
  51100. var i;
  51101. for (i = 0; i < this.vertices.length; ++i) {
  51102. this.vertices[i].triangleCount = 0;
  51103. }
  51104. var t;
  51105. var j;
  51106. for (i = 0; i < this.triangles.length; ++i) {
  51107. if (!this.triangles[i].deleted) {
  51108. t = this.triangles[i];
  51109. for (j = 0; j < 3; ++j) {
  51110. t.vertices[j].triangleCount = 1;
  51111. }
  51112. newTriangles.push(t);
  51113. }
  51114. }
  51115. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  51116. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  51117. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  51118. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  51119. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51120. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51121. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51122. var vertexCount = 0;
  51123. for (i = 0; i < this.vertices.length; ++i) {
  51124. var vertex = this.vertices[i];
  51125. vertex.id = vertexCount;
  51126. if (vertex.triangleCount) {
  51127. vertex.originalOffsets.forEach(function (originalOffset) {
  51128. newPositionData.push(vertex.position.x);
  51129. newPositionData.push(vertex.position.y);
  51130. newPositionData.push(vertex.position.z);
  51131. newNormalData.push(normalData[originalOffset * 3]);
  51132. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  51133. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  51134. if (uvs && uvs.length) {
  51135. newUVsData.push(uvs[(originalOffset * 2)]);
  51136. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  51137. }
  51138. else if (colorsData && colorsData.length) {
  51139. newColorsData.push(colorsData[(originalOffset * 4)]);
  51140. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  51141. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  51142. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  51143. }
  51144. ++vertexCount;
  51145. });
  51146. }
  51147. }
  51148. var startingIndex = this._reconstructedMesh.getTotalIndices();
  51149. var startingVertex = this._reconstructedMesh.getTotalVertices();
  51150. var submeshesArray = this._reconstructedMesh.subMeshes;
  51151. this._reconstructedMesh.subMeshes = [];
  51152. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  51153. var originalIndices = this._mesh.getIndices();
  51154. for (i = 0; i < newTriangles.length; ++i) {
  51155. t = newTriangles[i]; //now get the new referencing point for each vertex
  51156. [0, 1, 2].forEach(function (idx) {
  51157. var id = originalIndices[t.originalOffset + idx];
  51158. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  51159. if (offset < 0)
  51160. offset = 0;
  51161. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  51162. });
  51163. }
  51164. //overwriting the old vertex buffers and indices.
  51165. this._reconstructedMesh.setIndices(newIndicesArray);
  51166. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  51167. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  51168. if (newUVsData.length > 0)
  51169. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  51170. if (newColorsData.length > 0)
  51171. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  51172. //create submesh
  51173. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  51174. if (submeshIndex > 0) {
  51175. this._reconstructedMesh.subMeshes = [];
  51176. submeshesArray.forEach(function (submesh) {
  51177. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  51178. });
  51179. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  51180. }
  51181. };
  51182. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  51183. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  51184. this._reconstructedMesh.material = this._mesh.material;
  51185. this._reconstructedMesh.parent = this._mesh.parent;
  51186. this._reconstructedMesh.isVisible = false;
  51187. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  51188. };
  51189. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  51190. for (var i = 0; i < vertex1.triangleCount; ++i) {
  51191. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  51192. if (t.deleted)
  51193. continue;
  51194. var s = this.references[vertex1.triangleStart + i].vertexId;
  51195. var v1 = t.vertices[(s + 1) % 3];
  51196. var v2 = t.vertices[(s + 2) % 3];
  51197. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  51198. deletedArray[i] = true;
  51199. delTr.push(t);
  51200. continue;
  51201. }
  51202. var d1 = v1.position.subtract(point);
  51203. d1 = d1.normalize();
  51204. var d2 = v2.position.subtract(point);
  51205. d2 = d2.normalize();
  51206. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  51207. return true;
  51208. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  51209. deletedArray[i] = false;
  51210. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  51211. return true;
  51212. }
  51213. return false;
  51214. };
  51215. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  51216. var newDeleted = deletedTriangles;
  51217. for (var i = 0; i < vertex.triangleCount; ++i) {
  51218. var ref = this.references[vertex.triangleStart + i];
  51219. var t = this.triangles[ref.triangleId];
  51220. if (t.deleted)
  51221. continue;
  51222. if (deletedArray[i] && t.deletePending) {
  51223. t.deleted = true;
  51224. newDeleted++;
  51225. continue;
  51226. }
  51227. t.vertices[ref.vertexId] = origVertex;
  51228. t.isDirty = true;
  51229. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  51230. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  51231. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  51232. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  51233. this.references.push(ref);
  51234. }
  51235. return newDeleted;
  51236. };
  51237. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  51238. for (var i = 0; i < this.vertices.length; ++i) {
  51239. var vCount = [];
  51240. var vId = [];
  51241. var v = this.vertices[i];
  51242. var j;
  51243. for (j = 0; j < v.triangleCount; ++j) {
  51244. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  51245. for (var ii = 0; ii < 3; ii++) {
  51246. var ofs = 0;
  51247. var vv = triangle.vertices[ii];
  51248. while (ofs < vCount.length) {
  51249. if (vId[ofs] === vv.id)
  51250. break;
  51251. ++ofs;
  51252. }
  51253. if (ofs === vCount.length) {
  51254. vCount.push(1);
  51255. vId.push(vv.id);
  51256. }
  51257. else {
  51258. vCount[ofs]++;
  51259. }
  51260. }
  51261. }
  51262. for (j = 0; j < vCount.length; ++j) {
  51263. if (vCount[j] === 1) {
  51264. this.vertices[vId[j]].isBorder = true;
  51265. }
  51266. else {
  51267. this.vertices[vId[j]].isBorder = false;
  51268. }
  51269. }
  51270. }
  51271. };
  51272. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  51273. if (identifyBorders === void 0) { identifyBorders = false; }
  51274. var i;
  51275. if (!identifyBorders) {
  51276. var newTrianglesVector = [];
  51277. for (i = 0; i < this.triangles.length; ++i) {
  51278. if (!this.triangles[i].deleted) {
  51279. newTrianglesVector.push(this.triangles[i]);
  51280. }
  51281. }
  51282. this.triangles = newTrianglesVector;
  51283. }
  51284. for (i = 0; i < this.vertices.length; ++i) {
  51285. this.vertices[i].triangleCount = 0;
  51286. this.vertices[i].triangleStart = 0;
  51287. }
  51288. var t;
  51289. var j;
  51290. var v;
  51291. for (i = 0; i < this.triangles.length; ++i) {
  51292. t = this.triangles[i];
  51293. for (j = 0; j < 3; ++j) {
  51294. v = t.vertices[j];
  51295. v.triangleCount++;
  51296. }
  51297. }
  51298. var tStart = 0;
  51299. for (i = 0; i < this.vertices.length; ++i) {
  51300. this.vertices[i].triangleStart = tStart;
  51301. tStart += this.vertices[i].triangleCount;
  51302. this.vertices[i].triangleCount = 0;
  51303. }
  51304. var newReferences = new Array(this.triangles.length * 3);
  51305. for (i = 0; i < this.triangles.length; ++i) {
  51306. t = this.triangles[i];
  51307. for (j = 0; j < 3; ++j) {
  51308. v = t.vertices[j];
  51309. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  51310. v.triangleCount++;
  51311. }
  51312. }
  51313. this.references = newReferences;
  51314. if (identifyBorders) {
  51315. this.identifyBorder();
  51316. }
  51317. };
  51318. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  51319. var x = point.x;
  51320. var y = point.y;
  51321. var z = point.z;
  51322. 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
  51323. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  51324. };
  51325. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  51326. var q = vertex1.q.add(vertex2.q);
  51327. var border = vertex1.isBorder && vertex2.isBorder;
  51328. var error = 0;
  51329. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  51330. if (qDet !== 0 && !border) {
  51331. if (!pointResult) {
  51332. pointResult = BABYLON.Vector3.Zero();
  51333. }
  51334. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  51335. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  51336. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  51337. error = this.vertexError(q, pointResult);
  51338. }
  51339. else {
  51340. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  51341. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  51342. var error1 = this.vertexError(q, vertex1.position);
  51343. var error2 = this.vertexError(q, vertex2.position);
  51344. var error3 = this.vertexError(q, p3);
  51345. error = Math.min(error1, error2, error3);
  51346. if (error === error1) {
  51347. if (pointResult) {
  51348. pointResult.copyFrom(vertex1.position);
  51349. }
  51350. }
  51351. else if (error === error2) {
  51352. if (pointResult) {
  51353. pointResult.copyFrom(vertex2.position);
  51354. }
  51355. }
  51356. else {
  51357. if (pointResult) {
  51358. pointResult.copyFrom(p3);
  51359. }
  51360. }
  51361. }
  51362. return error;
  51363. };
  51364. return QuadraticErrorSimplification;
  51365. })();
  51366. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  51367. })(BABYLON || (BABYLON = {}));
  51368. var BABYLON;
  51369. (function (BABYLON) {
  51370. var serializedGeometries = [];
  51371. var serializeGeometry = function (geometry, serializationGeometries) {
  51372. if (serializedGeometries[geometry.id]) {
  51373. return;
  51374. }
  51375. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  51376. serializationGeometries.boxes.push(geometry.serialize());
  51377. }
  51378. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  51379. serializationGeometries.spheres.push(geometry.serialize());
  51380. }
  51381. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  51382. serializationGeometries.cylinders.push(geometry.serialize());
  51383. }
  51384. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  51385. serializationGeometries.toruses.push(geometry.serialize());
  51386. }
  51387. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  51388. serializationGeometries.grounds.push(geometry.serialize());
  51389. }
  51390. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  51391. serializationGeometries.planes.push(geometry.serialize());
  51392. }
  51393. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  51394. serializationGeometries.torusKnots.push(geometry.serialize());
  51395. }
  51396. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  51397. throw new Error("Unknown primitive type");
  51398. }
  51399. else {
  51400. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  51401. }
  51402. serializedGeometries[geometry.id] = true;
  51403. };
  51404. var serializeMesh = function (mesh, serializationScene) {
  51405. var serializationObject = {};
  51406. serializationObject.name = mesh.name;
  51407. serializationObject.id = mesh.id;
  51408. if (BABYLON.Tags.HasTags(mesh)) {
  51409. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  51410. }
  51411. serializationObject.position = mesh.position.asArray();
  51412. if (mesh.rotationQuaternion) {
  51413. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  51414. }
  51415. else if (mesh.rotation) {
  51416. serializationObject.rotation = mesh.rotation.asArray();
  51417. }
  51418. serializationObject.scaling = mesh.scaling.asArray();
  51419. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  51420. serializationObject.isEnabled = mesh.isEnabled();
  51421. serializationObject.isVisible = mesh.isVisible;
  51422. serializationObject.infiniteDistance = mesh.infiniteDistance;
  51423. serializationObject.pickable = mesh.isPickable;
  51424. serializationObject.receiveShadows = mesh.receiveShadows;
  51425. serializationObject.billboardMode = mesh.billboardMode;
  51426. serializationObject.visibility = mesh.visibility;
  51427. serializationObject.checkCollisions = mesh.checkCollisions;
  51428. // Parent
  51429. if (mesh.parent) {
  51430. serializationObject.parentId = mesh.parent.id;
  51431. }
  51432. // Geometry
  51433. var geometry = mesh._geometry;
  51434. if (geometry) {
  51435. var geometryId = geometry.id;
  51436. serializationObject.geometryId = geometryId;
  51437. if (!mesh.getScene().getGeometryByID(geometryId)) {
  51438. // 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
  51439. serializeGeometry(geometry, serializationScene.geometries);
  51440. }
  51441. // SubMeshes
  51442. serializationObject.subMeshes = [];
  51443. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  51444. var subMesh = mesh.subMeshes[subIndex];
  51445. serializationObject.subMeshes.push({
  51446. materialIndex: subMesh.materialIndex,
  51447. verticesStart: subMesh.verticesStart,
  51448. verticesCount: subMesh.verticesCount,
  51449. indexStart: subMesh.indexStart,
  51450. indexCount: subMesh.indexCount
  51451. });
  51452. }
  51453. }
  51454. // Material
  51455. if (mesh.material) {
  51456. serializationObject.materialId = mesh.material.id;
  51457. }
  51458. else {
  51459. mesh.material = null;
  51460. }
  51461. // Skeleton
  51462. if (mesh.skeleton) {
  51463. serializationObject.skeletonId = mesh.skeleton.id;
  51464. }
  51465. // Physics
  51466. //TODO implement correct serialization for physics impostors.
  51467. if (mesh.getPhysicsImpostor()) {
  51468. serializationObject.physicsMass = mesh.getPhysicsMass();
  51469. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  51470. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  51471. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  51472. }
  51473. // Instances
  51474. serializationObject.instances = [];
  51475. for (var index = 0; index < mesh.instances.length; index++) {
  51476. var instance = mesh.instances[index];
  51477. var serializationInstance = {
  51478. name: instance.name,
  51479. position: instance.position.asArray(),
  51480. scaling: instance.scaling.asArray()
  51481. };
  51482. if (instance.rotationQuaternion) {
  51483. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  51484. }
  51485. else if (instance.rotation) {
  51486. serializationInstance.rotation = instance.rotation.asArray();
  51487. }
  51488. serializationObject.instances.push(serializationInstance);
  51489. // Animations
  51490. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  51491. serializationInstance.ranges = instance.serializeAnimationRanges();
  51492. }
  51493. // Animations
  51494. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  51495. serializationObject.ranges = mesh.serializeAnimationRanges();
  51496. // Layer mask
  51497. serializationObject.layerMask = mesh.layerMask;
  51498. // Action Manager
  51499. if (mesh.actionManager) {
  51500. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  51501. }
  51502. return serializationObject;
  51503. };
  51504. var finalizeSingleMesh = function (mesh, serializationObject) {
  51505. //only works if the mesh is already loaded
  51506. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  51507. //serialize material
  51508. if (mesh.material) {
  51509. if (mesh.material instanceof BABYLON.StandardMaterial) {
  51510. serializationObject.materials = serializationObject.materials || [];
  51511. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  51512. serializationObject.materials.push(mesh.material.serialize());
  51513. }
  51514. }
  51515. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  51516. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  51517. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  51518. serializationObject.multiMaterials.push(mesh.material.serialize());
  51519. }
  51520. }
  51521. }
  51522. //serialize geometry
  51523. var geometry = mesh._geometry;
  51524. if (geometry) {
  51525. if (!serializationObject.geometries) {
  51526. serializationObject.geometries = {};
  51527. serializationObject.geometries.boxes = [];
  51528. serializationObject.geometries.spheres = [];
  51529. serializationObject.geometries.cylinders = [];
  51530. serializationObject.geometries.toruses = [];
  51531. serializationObject.geometries.grounds = [];
  51532. serializationObject.geometries.planes = [];
  51533. serializationObject.geometries.torusKnots = [];
  51534. serializationObject.geometries.vertexData = [];
  51535. }
  51536. serializeGeometry(geometry, serializationObject.geometries);
  51537. }
  51538. // Skeletons
  51539. if (mesh.skeleton) {
  51540. serializationObject.skeletons = serializationObject.skeletons || [];
  51541. serializationObject.skeletons.push(mesh.skeleton.serialize());
  51542. }
  51543. //serialize the actual mesh
  51544. serializationObject.meshes = serializationObject.meshes || [];
  51545. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  51546. }
  51547. };
  51548. var SceneSerializer = (function () {
  51549. function SceneSerializer() {
  51550. }
  51551. SceneSerializer.ClearCache = function () {
  51552. serializedGeometries = [];
  51553. };
  51554. SceneSerializer.Serialize = function (scene) {
  51555. var serializationObject = {};
  51556. // Scene
  51557. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  51558. serializationObject.autoClear = scene.autoClear;
  51559. serializationObject.clearColor = scene.clearColor.asArray();
  51560. serializationObject.ambientColor = scene.ambientColor.asArray();
  51561. serializationObject.gravity = scene.gravity.asArray();
  51562. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  51563. serializationObject.workerCollisions = scene.workerCollisions;
  51564. // Fog
  51565. if (scene.fogMode && scene.fogMode !== 0) {
  51566. serializationObject.fogMode = scene.fogMode;
  51567. serializationObject.fogColor = scene.fogColor.asArray();
  51568. serializationObject.fogStart = scene.fogStart;
  51569. serializationObject.fogEnd = scene.fogEnd;
  51570. serializationObject.fogDensity = scene.fogDensity;
  51571. }
  51572. //Physics
  51573. if (scene.isPhysicsEnabled()) {
  51574. serializationObject.physicsEnabled = true;
  51575. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  51576. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  51577. }
  51578. // Lights
  51579. serializationObject.lights = [];
  51580. var index;
  51581. var light;
  51582. for (index = 0; index < scene.lights.length; index++) {
  51583. light = scene.lights[index];
  51584. serializationObject.lights.push(light.serialize());
  51585. }
  51586. // Cameras
  51587. serializationObject.cameras = [];
  51588. for (index = 0; index < scene.cameras.length; index++) {
  51589. var camera = scene.cameras[index];
  51590. serializationObject.cameras.push(camera.serialize());
  51591. }
  51592. if (scene.activeCamera) {
  51593. serializationObject.activeCameraID = scene.activeCamera.id;
  51594. }
  51595. // Animations
  51596. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  51597. // Materials
  51598. serializationObject.materials = [];
  51599. serializationObject.multiMaterials = [];
  51600. var material;
  51601. for (index = 0; index < scene.materials.length; index++) {
  51602. material = scene.materials[index];
  51603. serializationObject.materials.push(material.serialize());
  51604. }
  51605. // MultiMaterials
  51606. serializationObject.multiMaterials = [];
  51607. for (index = 0; index < scene.multiMaterials.length; index++) {
  51608. var multiMaterial = scene.multiMaterials[index];
  51609. serializationObject.multiMaterials.push(multiMaterial.serialize());
  51610. }
  51611. // Skeletons
  51612. serializationObject.skeletons = [];
  51613. for (index = 0; index < scene.skeletons.length; index++) {
  51614. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  51615. }
  51616. // Geometries
  51617. serializationObject.geometries = {};
  51618. serializationObject.geometries.boxes = [];
  51619. serializationObject.geometries.spheres = [];
  51620. serializationObject.geometries.cylinders = [];
  51621. serializationObject.geometries.toruses = [];
  51622. serializationObject.geometries.grounds = [];
  51623. serializationObject.geometries.planes = [];
  51624. serializationObject.geometries.torusKnots = [];
  51625. serializationObject.geometries.vertexData = [];
  51626. serializedGeometries = [];
  51627. var geometries = scene.getGeometries();
  51628. for (index = 0; index < geometries.length; index++) {
  51629. var geometry = geometries[index];
  51630. if (geometry.isReady()) {
  51631. serializeGeometry(geometry, serializationObject.geometries);
  51632. }
  51633. }
  51634. // Meshes
  51635. serializationObject.meshes = [];
  51636. for (index = 0; index < scene.meshes.length; index++) {
  51637. var abstractMesh = scene.meshes[index];
  51638. if (abstractMesh instanceof BABYLON.Mesh) {
  51639. var mesh = abstractMesh;
  51640. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  51641. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  51642. }
  51643. }
  51644. }
  51645. // Particles Systems
  51646. serializationObject.particleSystems = [];
  51647. for (index = 0; index < scene.particleSystems.length; index++) {
  51648. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  51649. }
  51650. // Lens flares
  51651. serializationObject.lensFlareSystems = [];
  51652. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  51653. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  51654. }
  51655. // Shadows
  51656. serializationObject.shadowGenerators = [];
  51657. for (index = 0; index < scene.lights.length; index++) {
  51658. light = scene.lights[index];
  51659. var shadowGenerator = light.getShadowGenerator();
  51660. // Only support serialization for official generator so far.
  51661. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  51662. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  51663. }
  51664. }
  51665. // Action Manager
  51666. if (scene.actionManager) {
  51667. serializationObject.actions = scene.actionManager.serialize("scene");
  51668. }
  51669. // Audio
  51670. serializationObject.sounds = [];
  51671. for (index = 0; index < scene.soundTracks.length; index++) {
  51672. var soundtrack = scene.soundTracks[index];
  51673. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  51674. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  51675. }
  51676. }
  51677. return serializationObject;
  51678. };
  51679. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  51680. if (withParents === void 0) { withParents = false; }
  51681. if (withChildren === void 0) { withChildren = false; }
  51682. var serializationObject = {};
  51683. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  51684. if (withParents || withChildren) {
  51685. //deliberate for loop! not for each, appended should be processed as well.
  51686. for (var i = 0; i < toSerialize.length; ++i) {
  51687. if (withChildren) {
  51688. toSerialize[i].getDescendants().forEach(function (node) {
  51689. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  51690. toSerialize.push(node);
  51691. }
  51692. });
  51693. }
  51694. //make sure the array doesn't contain the object already
  51695. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  51696. toSerialize.push(toSerialize[i].parent);
  51697. }
  51698. }
  51699. }
  51700. toSerialize.forEach(function (mesh) {
  51701. finalizeSingleMesh(mesh, serializationObject);
  51702. });
  51703. return serializationObject;
  51704. };
  51705. return SceneSerializer;
  51706. })();
  51707. BABYLON.SceneSerializer = SceneSerializer;
  51708. })(BABYLON || (BABYLON = {}));
  51709. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  51710. // Huge respect for a such great lib.
  51711. // Earcut license:
  51712. // Copyright (c) 2016, Mapbox
  51713. //
  51714. // Permission to use, copy, modify, and/or distribute this software for any purpose
  51715. // with or without fee is hereby granted, provided that the above copyright notice
  51716. // and this permission notice appear in all copies.
  51717. //
  51718. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  51719. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  51720. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  51721. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  51722. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  51723. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  51724. // THIS SOFTWARE.
  51725. var Earcut;
  51726. (function (Earcut) {
  51727. /**
  51728. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  51729. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  51730. * @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).
  51731. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  51732. */
  51733. function earcut(data, holeIndices, dim) {
  51734. dim = dim || 2;
  51735. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  51736. if (!outerNode)
  51737. return triangles;
  51738. var minX, minY, maxX, maxY, x, y, size;
  51739. if (hasHoles)
  51740. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  51741. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  51742. if (data.length > 80 * dim) {
  51743. minX = maxX = data[0];
  51744. minY = maxY = data[1];
  51745. for (var i = dim; i < outerLen; i += dim) {
  51746. x = data[i];
  51747. y = data[i + 1];
  51748. if (x < minX)
  51749. minX = x;
  51750. if (y < minY)
  51751. minY = y;
  51752. if (x > maxX)
  51753. maxX = x;
  51754. if (y > maxY)
  51755. maxY = y;
  51756. }
  51757. // minX, minY and size are later used to transform coords into integers for z-order calculation
  51758. size = Math.max(maxX - minX, maxY - minY);
  51759. }
  51760. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  51761. return triangles;
  51762. }
  51763. Earcut.earcut = earcut;
  51764. // create a circular doubly linked list from polygon points in the specified winding order
  51765. function linkedList(data, start, end, dim, clockwise) {
  51766. var i, last;
  51767. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  51768. for (i = start; i < end; i += dim)
  51769. last = insertNode(i, data[i], data[i + 1], last);
  51770. }
  51771. else {
  51772. for (i = end - dim; i >= start; i -= dim)
  51773. last = insertNode(i, data[i], data[i + 1], last);
  51774. }
  51775. if (last && equals(last, last.next)) {
  51776. removeNode(last);
  51777. last = last.next;
  51778. }
  51779. return last;
  51780. }
  51781. // eliminate colinear or duplicate points
  51782. function filterPoints(start, end) {
  51783. if (!start)
  51784. return start;
  51785. if (!end)
  51786. end = start;
  51787. var p = start, again;
  51788. do {
  51789. again = false;
  51790. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  51791. removeNode(p);
  51792. p = end = p.prev;
  51793. if (p === p.next)
  51794. return null;
  51795. again = true;
  51796. }
  51797. else {
  51798. p = p.next;
  51799. }
  51800. } while (again || p !== end);
  51801. return end;
  51802. }
  51803. // main ear slicing loop which triangulates a polygon (given as a linked list)
  51804. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  51805. if (!ear)
  51806. return;
  51807. // interlink polygon nodes in z-order
  51808. if (!pass && size)
  51809. indexCurve(ear, minX, minY, size);
  51810. var stop = ear, prev, next;
  51811. // iterate through ears, slicing them one by one
  51812. while (ear.prev !== ear.next) {
  51813. prev = ear.prev;
  51814. next = ear.next;
  51815. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  51816. // cut off the triangle
  51817. triangles.push(prev.i / dim);
  51818. triangles.push(ear.i / dim);
  51819. triangles.push(next.i / dim);
  51820. removeNode(ear);
  51821. // skipping the next vertice leads to less sliver triangles
  51822. ear = next.next;
  51823. stop = next.next;
  51824. continue;
  51825. }
  51826. ear = next;
  51827. // if we looped through the whole remaining polygon and can't find any more ears
  51828. if (ear === stop) {
  51829. // try filtering points and slicing again
  51830. if (!pass) {
  51831. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  51832. }
  51833. else if (pass === 1) {
  51834. ear = cureLocalIntersections(ear, triangles, dim);
  51835. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  51836. }
  51837. else if (pass === 2) {
  51838. splitEarcut(ear, triangles, dim, minX, minY, size);
  51839. }
  51840. break;
  51841. }
  51842. }
  51843. }
  51844. // check whether a polygon node forms a valid ear with adjacent nodes
  51845. function isEar(ear) {
  51846. var a = ear.prev, b = ear, c = ear.next;
  51847. if (area(a, b, c) >= 0)
  51848. return false; // reflex, can't be an ear
  51849. // now make sure we don't have other points inside the potential ear
  51850. var p = ear.next.next;
  51851. while (p !== ear.prev) {
  51852. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  51853. area(p.prev, p, p.next) >= 0)
  51854. return false;
  51855. p = p.next;
  51856. }
  51857. return true;
  51858. }
  51859. function isEarHashed(ear, minX, minY, size) {
  51860. var a = ear.prev, b = ear, c = ear.next;
  51861. if (area(a, b, c) >= 0)
  51862. return false; // reflex, can't be an ear
  51863. // triangle bbox; min & max are calculated like this for speed
  51864. 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);
  51865. // z-order range for the current triangle bbox;
  51866. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  51867. // first look for points inside the triangle in increasing z-order
  51868. var p = ear.nextZ;
  51869. while (p && p.z <= maxZ) {
  51870. if (p !== ear.prev &&
  51871. p !== ear.next &&
  51872. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  51873. area(p.prev, p, p.next) >= 0)
  51874. return false;
  51875. p = p.nextZ;
  51876. }
  51877. // then look for points in decreasing z-order
  51878. p = ear.prevZ;
  51879. while (p && p.z >= minZ) {
  51880. if (p !== ear.prev &&
  51881. p !== ear.next &&
  51882. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  51883. area(p.prev, p, p.next) >= 0)
  51884. return false;
  51885. p = p.prevZ;
  51886. }
  51887. return true;
  51888. }
  51889. // go through all polygon nodes and cure small local self-intersections
  51890. function cureLocalIntersections(start, triangles, dim) {
  51891. var p = start;
  51892. do {
  51893. var a = p.prev, b = p.next.next;
  51894. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  51895. triangles.push(a.i / dim);
  51896. triangles.push(p.i / dim);
  51897. triangles.push(b.i / dim);
  51898. // remove two nodes involved
  51899. removeNode(p);
  51900. removeNode(p.next);
  51901. p = start = b;
  51902. }
  51903. p = p.next;
  51904. } while (p !== start);
  51905. return p;
  51906. }
  51907. // try splitting polygon into two and triangulate them independently
  51908. function splitEarcut(start, triangles, dim, minX, minY, size) {
  51909. // look for a valid diagonal that divides the polygon into two
  51910. var a = start;
  51911. do {
  51912. var b = a.next.next;
  51913. while (b !== a.prev) {
  51914. if (a.i !== b.i && isValidDiagonal(a, b)) {
  51915. // split the polygon in two by the diagonal
  51916. var c = splitPolygon(a, b);
  51917. // filter colinear points around the cuts
  51918. a = filterPoints(a, a.next);
  51919. c = filterPoints(c, c.next);
  51920. // run earcut on each half
  51921. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  51922. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  51923. return;
  51924. }
  51925. b = b.next;
  51926. }
  51927. a = a.next;
  51928. } while (a !== start);
  51929. }
  51930. // link every hole into the outer loop, producing a single-ring polygon without holes
  51931. function eliminateHoles(data, holeIndices, outerNode, dim) {
  51932. var queue = [], i, len, start, end, list;
  51933. for (i = 0, len = holeIndices.length; i < len; i++) {
  51934. start = holeIndices[i] * dim;
  51935. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  51936. list = linkedList(data, start, end, dim, false);
  51937. if (list === list.next)
  51938. list.steiner = true;
  51939. queue.push(getLeftmost(list));
  51940. }
  51941. queue.sort(compareX);
  51942. // process holes from left to right
  51943. for (i = 0; i < queue.length; i++) {
  51944. eliminateHole(queue[i], outerNode);
  51945. outerNode = filterPoints(outerNode, outerNode.next);
  51946. }
  51947. return outerNode;
  51948. }
  51949. function compareX(a, b) {
  51950. return a.x - b.x;
  51951. }
  51952. // find a bridge between vertices that connects hole with an outer ring and and link it
  51953. function eliminateHole(hole, outerNode) {
  51954. outerNode = findHoleBridge(hole, outerNode);
  51955. if (outerNode) {
  51956. var b = splitPolygon(outerNode, hole);
  51957. filterPoints(b, b.next);
  51958. }
  51959. }
  51960. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  51961. function findHoleBridge(hole, outerNode) {
  51962. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  51963. // find a segment intersected by a ray from the hole's leftmost point to the left;
  51964. // segment's endpoint with lesser x will be potential connection point
  51965. do {
  51966. if (hy <= p.y && hy >= p.next.y) {
  51967. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  51968. if (x <= hx && x > qx) {
  51969. qx = x;
  51970. if (x === hx) {
  51971. if (hy === p.y)
  51972. return p;
  51973. if (hy === p.next.y)
  51974. return p.next;
  51975. }
  51976. m = p.x < p.next.x ? p : p.next;
  51977. }
  51978. }
  51979. p = p.next;
  51980. } while (p !== outerNode);
  51981. if (!m)
  51982. return null;
  51983. if (hx === qx)
  51984. return m.prev; // hole touches outer segment; pick lower endpoint
  51985. // look for points inside the triangle of hole point, segment intersection and endpoint;
  51986. // if there are no points found, we have a valid connection;
  51987. // otherwise choose the point of the minimum angle with the ray as connection point
  51988. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  51989. p = m.next;
  51990. while (p !== stop) {
  51991. if (hx >= p.x &&
  51992. p.x >= mx &&
  51993. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  51994. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  51995. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  51996. m = p;
  51997. tanMin = tan;
  51998. }
  51999. }
  52000. p = p.next;
  52001. }
  52002. return m;
  52003. }
  52004. // interlink polygon nodes in z-order
  52005. function indexCurve(start, minX, minY, size) {
  52006. var p = start;
  52007. do {
  52008. if (p.z === null)
  52009. p.z = zOrder(p.x, p.y, minX, minY, size);
  52010. p.prevZ = p.prev;
  52011. p.nextZ = p.next;
  52012. p = p.next;
  52013. } while (p !== start);
  52014. p.prevZ.nextZ = null;
  52015. p.prevZ = null;
  52016. sortLinked(p);
  52017. }
  52018. // Simon Tatham's linked list merge sort algorithm
  52019. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  52020. function sortLinked(list) {
  52021. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  52022. do {
  52023. p = list;
  52024. list = null;
  52025. tail = null;
  52026. numMerges = 0;
  52027. while (p) {
  52028. numMerges++;
  52029. q = p;
  52030. pSize = 0;
  52031. for (i = 0; i < inSize; i++) {
  52032. pSize++;
  52033. q = q.nextZ;
  52034. if (!q)
  52035. break;
  52036. }
  52037. qSize = inSize;
  52038. while (pSize > 0 || (qSize > 0 && q)) {
  52039. if (pSize === 0) {
  52040. e = q;
  52041. q = q.nextZ;
  52042. qSize--;
  52043. }
  52044. else if (qSize === 0 || !q) {
  52045. e = p;
  52046. p = p.nextZ;
  52047. pSize--;
  52048. }
  52049. else if (p.z <= q.z) {
  52050. e = p;
  52051. p = p.nextZ;
  52052. pSize--;
  52053. }
  52054. else {
  52055. e = q;
  52056. q = q.nextZ;
  52057. qSize--;
  52058. }
  52059. if (tail)
  52060. tail.nextZ = e;
  52061. else
  52062. list = e;
  52063. e.prevZ = tail;
  52064. tail = e;
  52065. }
  52066. p = q;
  52067. }
  52068. tail.nextZ = null;
  52069. inSize *= 2;
  52070. } while (numMerges > 1);
  52071. return list;
  52072. }
  52073. // z-order of a point given coords and size of the data bounding box
  52074. function zOrder(x, y, minX, minY, size) {
  52075. // coords are transformed into non-negative 15-bit integer range
  52076. x = 32767 * (x - minX) / size;
  52077. y = 32767 * (y - minY) / size;
  52078. x = (x | (x << 8)) & 0x00FF00FF;
  52079. x = (x | (x << 4)) & 0x0F0F0F0F;
  52080. x = (x | (x << 2)) & 0x33333333;
  52081. x = (x | (x << 1)) & 0x55555555;
  52082. y = (y | (y << 8)) & 0x00FF00FF;
  52083. y = (y | (y << 4)) & 0x0F0F0F0F;
  52084. y = (y | (y << 2)) & 0x33333333;
  52085. y = (y | (y << 1)) & 0x55555555;
  52086. return x | (y << 1);
  52087. }
  52088. // find the leftmost node of a polygon ring
  52089. function getLeftmost(start) {
  52090. var p = start, leftmost = start;
  52091. do {
  52092. if (p.x < leftmost.x)
  52093. leftmost = p;
  52094. p = p.next;
  52095. } while (p !== start);
  52096. return leftmost;
  52097. }
  52098. // check if a point lies within a convex triangle
  52099. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  52100. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  52101. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  52102. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  52103. }
  52104. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  52105. function isValidDiagonal(a, b) {
  52106. return a.next.i !== b.i &&
  52107. a.prev.i !== b.i &&
  52108. !intersectsPolygon(a, b) &&
  52109. locallyInside(a, b) &&
  52110. locallyInside(b, a) &&
  52111. middleInside(a, b);
  52112. }
  52113. // signed area of a triangle
  52114. function area(p, q, r) {
  52115. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  52116. }
  52117. // check if two points are equal
  52118. function equals(p1, p2) {
  52119. return p1.x === p2.x && p1.y === p2.y;
  52120. }
  52121. // check if two segments intersect
  52122. function intersects(p1, q1, p2, q2) {
  52123. if ((equals(p1, q1) && equals(p2, q2)) ||
  52124. (equals(p1, q2) && equals(p2, q1)))
  52125. return true;
  52126. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  52127. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  52128. }
  52129. // check if a polygon diagonal intersects any polygon segments
  52130. function intersectsPolygon(a, b) {
  52131. var p = a;
  52132. do {
  52133. if (p.i !== a.i &&
  52134. p.next.i !== a.i &&
  52135. p.i !== b.i &&
  52136. p.next.i !== b.i &&
  52137. intersects(p, p.next, a, b))
  52138. return true;
  52139. p = p.next;
  52140. } while (p !== a);
  52141. return false;
  52142. }
  52143. // check if a polygon diagonal is locally inside the polygon
  52144. function locallyInside(a, b) {
  52145. return area(a.prev, a, a.next) < 0
  52146. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  52147. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  52148. }
  52149. // check if the middle point of a polygon diagonal is inside the polygon
  52150. function middleInside(a, b) {
  52151. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  52152. do {
  52153. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  52154. inside = !inside;
  52155. p = p.next;
  52156. } while (p !== a);
  52157. return inside;
  52158. }
  52159. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  52160. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  52161. function splitPolygon(a, b) {
  52162. 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;
  52163. a.next = b;
  52164. b.prev = a;
  52165. a2.next = an;
  52166. an.prev = a2;
  52167. b2.next = a2;
  52168. a2.prev = b2;
  52169. bp.next = b2;
  52170. b2.prev = bp;
  52171. return b2;
  52172. }
  52173. // create a node and optionally link it with previous one (in a circular doubly linked list)
  52174. function insertNode(i, x, y, last) {
  52175. var p = new Node(i, x, y);
  52176. if (!last) {
  52177. p.prev = p;
  52178. p.next = p;
  52179. }
  52180. else {
  52181. p.next = last.next;
  52182. p.prev = last;
  52183. last.next.prev = p;
  52184. last.next = p;
  52185. }
  52186. return p;
  52187. }
  52188. function removeNode(p) {
  52189. p.next.prev = p.prev;
  52190. p.prev.next = p.next;
  52191. if (p.prevZ)
  52192. p.prevZ.nextZ = p.nextZ;
  52193. if (p.nextZ)
  52194. p.nextZ.prevZ = p.prevZ;
  52195. }
  52196. function Node(i, x, y) {
  52197. // vertice index in coordinates array
  52198. this.i = i;
  52199. // vertex coordinates
  52200. this.x = x;
  52201. this.y = y;
  52202. // previous and next vertice nodes in a polygon ring
  52203. this.prev = null;
  52204. this.next = null;
  52205. // z-order curve value
  52206. this.z = null;
  52207. // previous and next nodes in z-order
  52208. this.prevZ = null;
  52209. this.nextZ = null;
  52210. // indicates whether this is a steiner point
  52211. this.steiner = false;
  52212. }
  52213. /**
  52214. * return a percentage difference between the polygon area and its triangulation area;
  52215. * used to verify correctness of triangulation
  52216. */
  52217. function deviation(data, holeIndices, dim, triangles) {
  52218. var hasHoles = holeIndices && holeIndices.length;
  52219. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  52220. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  52221. if (hasHoles) {
  52222. for (var i = 0, len = holeIndices.length; i < len; i++) {
  52223. var start = holeIndices[i] * dim;
  52224. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  52225. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  52226. }
  52227. }
  52228. var trianglesArea = 0;
  52229. for (i = 0; i < triangles.length; i += 3) {
  52230. var a = triangles[i] * dim;
  52231. var b = triangles[i + 1] * dim;
  52232. var c = triangles[i + 2] * dim;
  52233. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  52234. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  52235. }
  52236. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  52237. }
  52238. Earcut.deviation = deviation;
  52239. ;
  52240. function signedArea(data, start, end, dim) {
  52241. var sum = 0;
  52242. for (var i = start, j = end - dim; i < end; i += dim) {
  52243. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  52244. j = i;
  52245. }
  52246. return sum;
  52247. }
  52248. /**
  52249. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  52250. */
  52251. function flatten(data) {
  52252. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  52253. for (var i = 0; i < data.length; i++) {
  52254. for (var j = 0; j < data[i].length; j++) {
  52255. for (var d = 0; d < dim; d++)
  52256. result.vertices.push(data[i][j][d]);
  52257. }
  52258. if (i > 0) {
  52259. holeIndex += data[i - 1].length;
  52260. result.holes.push(holeIndex);
  52261. }
  52262. }
  52263. return result;
  52264. }
  52265. Earcut.flatten = flatten;
  52266. ;
  52267. })(Earcut || (Earcut = {}));
  52268. var BABYLON;
  52269. (function (BABYLON) {
  52270. // Unique ID when we import meshes from Babylon to CSG
  52271. var currentCSGMeshId = 0;
  52272. // # class Vertex
  52273. // Represents a vertex of a polygon. Use your own vertex class instead of this
  52274. // one to provide additional features like texture coordinates and vertex
  52275. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  52276. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  52277. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  52278. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  52279. // is not used anywhere else.
  52280. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  52281. var Vertex = (function () {
  52282. function Vertex(pos, normal, uv) {
  52283. this.pos = pos;
  52284. this.normal = normal;
  52285. this.uv = uv;
  52286. }
  52287. Vertex.prototype.clone = function () {
  52288. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  52289. };
  52290. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  52291. // orientation of a polygon is flipped.
  52292. Vertex.prototype.flip = function () {
  52293. this.normal = this.normal.scale(-1);
  52294. };
  52295. // Create a new vertex between this vertex and `other` by linearly
  52296. // interpolating all properties using a parameter of `t`. Subclasses should
  52297. // override this to interpolate additional properties.
  52298. Vertex.prototype.interpolate = function (other, t) {
  52299. 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));
  52300. };
  52301. return Vertex;
  52302. })();
  52303. // # class Plane
  52304. // Represents a plane in 3D space.
  52305. var Plane = (function () {
  52306. function Plane(normal, w) {
  52307. this.normal = normal;
  52308. this.w = w;
  52309. }
  52310. Plane.FromPoints = function (a, b, c) {
  52311. var v0 = c.subtract(a);
  52312. var v1 = b.subtract(a);
  52313. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  52314. return null;
  52315. }
  52316. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  52317. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  52318. };
  52319. Plane.prototype.clone = function () {
  52320. return new Plane(this.normal.clone(), this.w);
  52321. };
  52322. Plane.prototype.flip = function () {
  52323. this.normal.scaleInPlace(-1);
  52324. this.w = -this.w;
  52325. };
  52326. // Split `polygon` by this plane if needed, then put the polygon or polygon
  52327. // fragments in the appropriate lists. Coplanar polygons go into either
  52328. // `coplanarFront` or `coplanarBack` depending on their orientation with
  52329. // respect to this plane. Polygons in front or in back of this plane go into
  52330. // either `front` or `back`.
  52331. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  52332. var COPLANAR = 0;
  52333. var FRONT = 1;
  52334. var BACK = 2;
  52335. var SPANNING = 3;
  52336. // Classify each point as well as the entire polygon into one of the above
  52337. // four classes.
  52338. var polygonType = 0;
  52339. var types = [];
  52340. var i;
  52341. var t;
  52342. for (i = 0; i < polygon.vertices.length; i++) {
  52343. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  52344. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  52345. polygonType |= type;
  52346. types.push(type);
  52347. }
  52348. // Put the polygon in the correct list, splitting it when necessary.
  52349. switch (polygonType) {
  52350. case COPLANAR:
  52351. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  52352. break;
  52353. case FRONT:
  52354. front.push(polygon);
  52355. break;
  52356. case BACK:
  52357. back.push(polygon);
  52358. break;
  52359. case SPANNING:
  52360. var f = [], b = [];
  52361. for (i = 0; i < polygon.vertices.length; i++) {
  52362. var j = (i + 1) % polygon.vertices.length;
  52363. var ti = types[i], tj = types[j];
  52364. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  52365. if (ti !== BACK)
  52366. f.push(vi);
  52367. if (ti !== FRONT)
  52368. b.push(ti !== BACK ? vi.clone() : vi);
  52369. if ((ti | tj) === SPANNING) {
  52370. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  52371. var v = vi.interpolate(vj, t);
  52372. f.push(v);
  52373. b.push(v.clone());
  52374. }
  52375. }
  52376. var poly;
  52377. if (f.length >= 3) {
  52378. poly = new Polygon(f, polygon.shared);
  52379. if (poly.plane)
  52380. front.push(poly);
  52381. }
  52382. if (b.length >= 3) {
  52383. poly = new Polygon(b, polygon.shared);
  52384. if (poly.plane)
  52385. back.push(poly);
  52386. }
  52387. break;
  52388. }
  52389. };
  52390. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  52391. // point is on the plane.
  52392. Plane.EPSILON = 1e-5;
  52393. return Plane;
  52394. })();
  52395. // # class Polygon
  52396. // Represents a convex polygon. The vertices used to initialize a polygon must
  52397. // be coplanar and form a convex loop.
  52398. //
  52399. // Each convex polygon has a `shared` property, which is shared between all
  52400. // polygons that are clones of each other or were split from the same polygon.
  52401. // This can be used to define per-polygon properties (such as surface color).
  52402. var Polygon = (function () {
  52403. function Polygon(vertices, shared) {
  52404. this.vertices = vertices;
  52405. this.shared = shared;
  52406. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  52407. }
  52408. Polygon.prototype.clone = function () {
  52409. var vertices = this.vertices.map(function (v) { return v.clone(); });
  52410. return new Polygon(vertices, this.shared);
  52411. };
  52412. Polygon.prototype.flip = function () {
  52413. this.vertices.reverse().map(function (v) { v.flip(); });
  52414. this.plane.flip();
  52415. };
  52416. return Polygon;
  52417. })();
  52418. // # class Node
  52419. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  52420. // by picking a polygon to split along. That polygon (and all other coplanar
  52421. // polygons) are added directly to that node and the other polygons are added to
  52422. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  52423. // no distinction between internal and leaf nodes.
  52424. var Node = (function () {
  52425. function Node(polygons) {
  52426. this.plane = null;
  52427. this.front = null;
  52428. this.back = null;
  52429. this.polygons = [];
  52430. if (polygons) {
  52431. this.build(polygons);
  52432. }
  52433. }
  52434. Node.prototype.clone = function () {
  52435. var node = new Node();
  52436. node.plane = this.plane && this.plane.clone();
  52437. node.front = this.front && this.front.clone();
  52438. node.back = this.back && this.back.clone();
  52439. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  52440. return node;
  52441. };
  52442. // Convert solid space to empty space and empty space to solid space.
  52443. Node.prototype.invert = function () {
  52444. for (var i = 0; i < this.polygons.length; i++) {
  52445. this.polygons[i].flip();
  52446. }
  52447. if (this.plane) {
  52448. this.plane.flip();
  52449. }
  52450. if (this.front) {
  52451. this.front.invert();
  52452. }
  52453. if (this.back) {
  52454. this.back.invert();
  52455. }
  52456. var temp = this.front;
  52457. this.front = this.back;
  52458. this.back = temp;
  52459. };
  52460. // Recursively remove all polygons in `polygons` that are inside this BSP
  52461. // tree.
  52462. Node.prototype.clipPolygons = function (polygons) {
  52463. if (!this.plane)
  52464. return polygons.slice();
  52465. var front = [], back = [];
  52466. for (var i = 0; i < polygons.length; i++) {
  52467. this.plane.splitPolygon(polygons[i], front, back, front, back);
  52468. }
  52469. if (this.front) {
  52470. front = this.front.clipPolygons(front);
  52471. }
  52472. if (this.back) {
  52473. back = this.back.clipPolygons(back);
  52474. }
  52475. else {
  52476. back = [];
  52477. }
  52478. return front.concat(back);
  52479. };
  52480. // Remove all polygons in this BSP tree that are inside the other BSP tree
  52481. // `bsp`.
  52482. Node.prototype.clipTo = function (bsp) {
  52483. this.polygons = bsp.clipPolygons(this.polygons);
  52484. if (this.front)
  52485. this.front.clipTo(bsp);
  52486. if (this.back)
  52487. this.back.clipTo(bsp);
  52488. };
  52489. // Return a list of all polygons in this BSP tree.
  52490. Node.prototype.allPolygons = function () {
  52491. var polygons = this.polygons.slice();
  52492. if (this.front)
  52493. polygons = polygons.concat(this.front.allPolygons());
  52494. if (this.back)
  52495. polygons = polygons.concat(this.back.allPolygons());
  52496. return polygons;
  52497. };
  52498. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  52499. // new polygons are filtered down to the bottom of the tree and become new
  52500. // nodes there. Each set of polygons is partitioned using the first polygon
  52501. // (no heuristic is used to pick a good split).
  52502. Node.prototype.build = function (polygons) {
  52503. if (!polygons.length)
  52504. return;
  52505. if (!this.plane)
  52506. this.plane = polygons[0].plane.clone();
  52507. var front = [], back = [];
  52508. for (var i = 0; i < polygons.length; i++) {
  52509. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  52510. }
  52511. if (front.length) {
  52512. if (!this.front)
  52513. this.front = new Node();
  52514. this.front.build(front);
  52515. }
  52516. if (back.length) {
  52517. if (!this.back)
  52518. this.back = new Node();
  52519. this.back.build(back);
  52520. }
  52521. };
  52522. return Node;
  52523. })();
  52524. var CSG = (function () {
  52525. function CSG() {
  52526. this.polygons = new Array();
  52527. }
  52528. // Convert BABYLON.Mesh to BABYLON.CSG
  52529. CSG.FromMesh = function (mesh) {
  52530. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  52531. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  52532. if (mesh instanceof BABYLON.Mesh) {
  52533. mesh.computeWorldMatrix(true);
  52534. matrix = mesh.getWorldMatrix();
  52535. meshPosition = mesh.position.clone();
  52536. meshRotation = mesh.rotation.clone();
  52537. if (mesh.rotationQuaternion) {
  52538. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  52539. }
  52540. meshScaling = mesh.scaling.clone();
  52541. }
  52542. else {
  52543. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  52544. }
  52545. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52546. var subMeshes = mesh.subMeshes;
  52547. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  52548. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  52549. vertices = [];
  52550. for (var j = 0; j < 3; j++) {
  52551. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  52552. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  52553. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  52554. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  52555. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  52556. vertex = new Vertex(position, normal, uv);
  52557. vertices.push(vertex);
  52558. }
  52559. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  52560. // To handle the case of degenerated triangle
  52561. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  52562. if (polygon.plane)
  52563. polygons.push(polygon);
  52564. }
  52565. }
  52566. var csg = CSG.FromPolygons(polygons);
  52567. csg.matrix = matrix;
  52568. csg.position = meshPosition;
  52569. csg.rotation = meshRotation;
  52570. csg.scaling = meshScaling;
  52571. csg.rotationQuaternion = meshRotationQuaternion;
  52572. currentCSGMeshId++;
  52573. return csg;
  52574. };
  52575. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  52576. CSG.FromPolygons = function (polygons) {
  52577. var csg = new CSG();
  52578. csg.polygons = polygons;
  52579. return csg;
  52580. };
  52581. CSG.prototype.clone = function () {
  52582. var csg = new CSG();
  52583. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  52584. csg.copyTransformAttributes(this);
  52585. return csg;
  52586. };
  52587. CSG.prototype.toPolygons = function () {
  52588. return this.polygons;
  52589. };
  52590. CSG.prototype.union = function (csg) {
  52591. var a = new Node(this.clone().polygons);
  52592. var b = new Node(csg.clone().polygons);
  52593. a.clipTo(b);
  52594. b.clipTo(a);
  52595. b.invert();
  52596. b.clipTo(a);
  52597. b.invert();
  52598. a.build(b.allPolygons());
  52599. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  52600. };
  52601. CSG.prototype.unionInPlace = function (csg) {
  52602. var a = new Node(this.polygons);
  52603. var b = new Node(csg.polygons);
  52604. a.clipTo(b);
  52605. b.clipTo(a);
  52606. b.invert();
  52607. b.clipTo(a);
  52608. b.invert();
  52609. a.build(b.allPolygons());
  52610. this.polygons = a.allPolygons();
  52611. };
  52612. CSG.prototype.subtract = function (csg) {
  52613. var a = new Node(this.clone().polygons);
  52614. var b = new Node(csg.clone().polygons);
  52615. a.invert();
  52616. a.clipTo(b);
  52617. b.clipTo(a);
  52618. b.invert();
  52619. b.clipTo(a);
  52620. b.invert();
  52621. a.build(b.allPolygons());
  52622. a.invert();
  52623. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  52624. };
  52625. CSG.prototype.subtractInPlace = function (csg) {
  52626. var a = new Node(this.polygons);
  52627. var b = new Node(csg.polygons);
  52628. a.invert();
  52629. a.clipTo(b);
  52630. b.clipTo(a);
  52631. b.invert();
  52632. b.clipTo(a);
  52633. b.invert();
  52634. a.build(b.allPolygons());
  52635. a.invert();
  52636. this.polygons = a.allPolygons();
  52637. };
  52638. CSG.prototype.intersect = function (csg) {
  52639. var a = new Node(this.clone().polygons);
  52640. var b = new Node(csg.clone().polygons);
  52641. a.invert();
  52642. b.clipTo(a);
  52643. b.invert();
  52644. a.clipTo(b);
  52645. b.clipTo(a);
  52646. a.build(b.allPolygons());
  52647. a.invert();
  52648. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  52649. };
  52650. CSG.prototype.intersectInPlace = function (csg) {
  52651. var a = new Node(this.polygons);
  52652. var b = new Node(csg.polygons);
  52653. a.invert();
  52654. b.clipTo(a);
  52655. b.invert();
  52656. a.clipTo(b);
  52657. b.clipTo(a);
  52658. a.build(b.allPolygons());
  52659. a.invert();
  52660. this.polygons = a.allPolygons();
  52661. };
  52662. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  52663. // not modified.
  52664. CSG.prototype.inverse = function () {
  52665. var csg = this.clone();
  52666. csg.inverseInPlace();
  52667. return csg;
  52668. };
  52669. CSG.prototype.inverseInPlace = function () {
  52670. this.polygons.map(function (p) { p.flip(); });
  52671. };
  52672. // This is used to keep meshes transformations so they can be restored
  52673. // when we build back a Babylon Mesh
  52674. // NB : All CSG operations are performed in world coordinates
  52675. CSG.prototype.copyTransformAttributes = function (csg) {
  52676. this.matrix = csg.matrix;
  52677. this.position = csg.position;
  52678. this.rotation = csg.rotation;
  52679. this.scaling = csg.scaling;
  52680. this.rotationQuaternion = csg.rotationQuaternion;
  52681. return this;
  52682. };
  52683. // Build Raw mesh from CSG
  52684. // Coordinates here are in world space
  52685. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  52686. var matrix = this.matrix.clone();
  52687. matrix.invert();
  52688. 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;
  52689. if (keepSubMeshes) {
  52690. // Sort Polygons, since subMeshes are indices range
  52691. polygons.sort(function (a, b) {
  52692. if (a.shared.meshId === b.shared.meshId) {
  52693. return a.shared.subMeshId - b.shared.subMeshId;
  52694. }
  52695. else {
  52696. return a.shared.meshId - b.shared.meshId;
  52697. }
  52698. });
  52699. }
  52700. for (var i = 0, il = polygons.length; i < il; i++) {
  52701. polygon = polygons[i];
  52702. // Building SubMeshes
  52703. if (!subMesh_dict[polygon.shared.meshId]) {
  52704. subMesh_dict[polygon.shared.meshId] = {};
  52705. }
  52706. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  52707. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  52708. indexStart: +Infinity,
  52709. indexEnd: -Infinity,
  52710. materialIndex: polygon.shared.materialIndex
  52711. };
  52712. }
  52713. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  52714. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  52715. polygonIndices[0] = 0;
  52716. polygonIndices[1] = j - 1;
  52717. polygonIndices[2] = j;
  52718. for (var k = 0; k < 3; k++) {
  52719. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  52720. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  52721. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  52722. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  52723. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  52724. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  52725. // Check if 2 points can be merged
  52726. if (!(typeof vertex_idx !== 'undefined' &&
  52727. normals[vertex_idx * 3] === localNormal.x &&
  52728. normals[vertex_idx * 3 + 1] === localNormal.y &&
  52729. normals[vertex_idx * 3 + 2] === localNormal.z &&
  52730. uvs[vertex_idx * 2] === uv.x &&
  52731. uvs[vertex_idx * 2 + 1] === uv.y)) {
  52732. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  52733. uvs.push(uv.x, uv.y);
  52734. normals.push(normal.x, normal.y, normal.z);
  52735. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  52736. }
  52737. indices.push(vertex_idx);
  52738. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  52739. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  52740. currentIndex++;
  52741. }
  52742. }
  52743. }
  52744. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  52745. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  52746. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  52747. mesh.setIndices(indices);
  52748. if (keepSubMeshes) {
  52749. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  52750. var materialIndexOffset = 0, materialMaxIndex;
  52751. mesh.subMeshes = new Array();
  52752. for (var m in subMesh_dict) {
  52753. materialMaxIndex = -1;
  52754. for (var sm in subMesh_dict[m]) {
  52755. subMesh_obj = subMesh_dict[m][sm];
  52756. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  52757. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  52758. }
  52759. materialIndexOffset += ++materialMaxIndex;
  52760. }
  52761. }
  52762. return mesh;
  52763. };
  52764. // Build Mesh from CSG taking material and transforms into account
  52765. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  52766. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  52767. mesh.material = material;
  52768. mesh.position.copyFrom(this.position);
  52769. mesh.rotation.copyFrom(this.rotation);
  52770. if (this.rotationQuaternion) {
  52771. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  52772. }
  52773. mesh.scaling.copyFrom(this.scaling);
  52774. mesh.computeWorldMatrix(true);
  52775. return mesh;
  52776. };
  52777. return CSG;
  52778. })();
  52779. BABYLON.CSG = CSG;
  52780. })(BABYLON || (BABYLON = {}));
  52781. var BABYLON;
  52782. (function (BABYLON) {
  52783. var VRDistortionCorrectionPostProcess = (function (_super) {
  52784. __extends(VRDistortionCorrectionPostProcess, _super);
  52785. //ANY
  52786. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  52787. var _this = this;
  52788. _super.call(this, name, "vrDistortionCorrection", [
  52789. 'LensCenter',
  52790. 'Scale',
  52791. 'ScaleIn',
  52792. 'HmdWarpParam'
  52793. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  52794. this._isRightEye = isRightEye;
  52795. this._distortionFactors = vrMetrics.distortionK;
  52796. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  52797. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  52798. this.onSizeChangedObservable.add(function () {
  52799. _this.aspectRatio = _this.width * .5 / _this.height;
  52800. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  52801. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  52802. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  52803. });
  52804. this.onApplyObservable.add(function (effect) {
  52805. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  52806. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  52807. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  52808. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  52809. });
  52810. }
  52811. return VRDistortionCorrectionPostProcess;
  52812. })(BABYLON.PostProcess);
  52813. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  52814. })(BABYLON || (BABYLON = {}));
  52815. // Mainly based on these 2 articles :
  52816. // 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
  52817. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  52818. var BABYLON;
  52819. (function (BABYLON) {
  52820. (function (JoystickAxis) {
  52821. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  52822. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  52823. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  52824. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  52825. var JoystickAxis = BABYLON.JoystickAxis;
  52826. var VirtualJoystick = (function () {
  52827. function VirtualJoystick(leftJoystick) {
  52828. var _this = this;
  52829. if (leftJoystick) {
  52830. this._leftJoystick = true;
  52831. }
  52832. else {
  52833. this._leftJoystick = false;
  52834. }
  52835. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  52836. VirtualJoystick._globalJoystickIndex++;
  52837. // By default left & right arrow keys are moving the X
  52838. // and up & down keys are moving the Y
  52839. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  52840. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  52841. this.reverseLeftRight = false;
  52842. this.reverseUpDown = false;
  52843. // collections of pointers
  52844. this._touches = new BABYLON.StringDictionary();
  52845. this.deltaPosition = BABYLON.Vector3.Zero();
  52846. this._joystickSensibility = 25;
  52847. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  52848. this._rotationSpeed = 25;
  52849. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  52850. this._rotateOnAxisRelativeToMesh = false;
  52851. this._onResize = function (evt) {
  52852. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  52853. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  52854. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  52855. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  52856. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  52857. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  52858. };
  52859. // injecting a canvas element on top of the canvas 3D game
  52860. if (!VirtualJoystick.vjCanvas) {
  52861. window.addEventListener("resize", this._onResize, false);
  52862. VirtualJoystick.vjCanvas = document.createElement("canvas");
  52863. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  52864. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  52865. VirtualJoystick.vjCanvas.width = window.innerWidth;
  52866. VirtualJoystick.vjCanvas.height = window.innerHeight;
  52867. VirtualJoystick.vjCanvas.style.width = "100%";
  52868. VirtualJoystick.vjCanvas.style.height = "100%";
  52869. VirtualJoystick.vjCanvas.style.position = "absolute";
  52870. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  52871. VirtualJoystick.vjCanvas.style.top = "0px";
  52872. VirtualJoystick.vjCanvas.style.left = "0px";
  52873. VirtualJoystick.vjCanvas.style.zIndex = "5";
  52874. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  52875. // Support for jQuery PEP polyfill
  52876. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  52877. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  52878. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  52879. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  52880. document.body.appendChild(VirtualJoystick.vjCanvas);
  52881. }
  52882. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  52883. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  52884. this.pressed = false;
  52885. // default joystick color
  52886. this._joystickColor = "cyan";
  52887. this._joystickPointerID = -1;
  52888. // current joystick position
  52889. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  52890. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  52891. // origin joystick position
  52892. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  52893. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  52894. this._onPointerDownHandlerRef = function (evt) {
  52895. _this._onPointerDown(evt);
  52896. };
  52897. this._onPointerMoveHandlerRef = function (evt) {
  52898. _this._onPointerMove(evt);
  52899. };
  52900. this._onPointerOutHandlerRef = function (evt) {
  52901. _this._onPointerUp(evt);
  52902. };
  52903. this._onPointerUpHandlerRef = function (evt) {
  52904. _this._onPointerUp(evt);
  52905. };
  52906. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  52907. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  52908. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  52909. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  52910. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  52911. evt.preventDefault(); // Disables system menu
  52912. }, false);
  52913. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  52914. }
  52915. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  52916. this._joystickSensibility = newJoystickSensibility;
  52917. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  52918. };
  52919. VirtualJoystick.prototype._onPointerDown = function (e) {
  52920. var positionOnScreenCondition;
  52921. e.preventDefault();
  52922. if (this._leftJoystick === true) {
  52923. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  52924. }
  52925. else {
  52926. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  52927. }
  52928. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  52929. // First contact will be dedicated to the virtual joystick
  52930. this._joystickPointerID = e.pointerId;
  52931. this._joystickPointerStartPos.x = e.clientX;
  52932. this._joystickPointerStartPos.y = e.clientY;
  52933. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  52934. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  52935. this._deltaJoystickVector.x = 0;
  52936. this._deltaJoystickVector.y = 0;
  52937. this.pressed = true;
  52938. this._touches.add(e.pointerId.toString(), e);
  52939. }
  52940. else {
  52941. // You can only trigger the action buttons with a joystick declared
  52942. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  52943. this._action();
  52944. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  52945. }
  52946. }
  52947. };
  52948. VirtualJoystick.prototype._onPointerMove = function (e) {
  52949. // If the current pointer is the one associated to the joystick (first touch contact)
  52950. if (this._joystickPointerID == e.pointerId) {
  52951. this._joystickPointerPos.x = e.clientX;
  52952. this._joystickPointerPos.y = e.clientY;
  52953. this._deltaJoystickVector = this._joystickPointerPos.clone();
  52954. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  52955. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  52956. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  52957. switch (this._axisTargetedByLeftAndRight) {
  52958. case JoystickAxis.X:
  52959. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  52960. break;
  52961. case JoystickAxis.Y:
  52962. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  52963. break;
  52964. case JoystickAxis.Z:
  52965. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  52966. break;
  52967. }
  52968. var directionUpDown = this.reverseUpDown ? 1 : -1;
  52969. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  52970. switch (this._axisTargetedByUpAndDown) {
  52971. case JoystickAxis.X:
  52972. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  52973. break;
  52974. case JoystickAxis.Y:
  52975. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  52976. break;
  52977. case JoystickAxis.Z:
  52978. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  52979. break;
  52980. }
  52981. }
  52982. else {
  52983. var data = this._touches.get(e.pointerId.toString());
  52984. if (data) {
  52985. data.x = e.clientX;
  52986. data.y = e.clientY;
  52987. }
  52988. }
  52989. };
  52990. VirtualJoystick.prototype._onPointerUp = function (e) {
  52991. if (this._joystickPointerID == e.pointerId) {
  52992. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  52993. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  52994. this._joystickPointerID = -1;
  52995. this.pressed = false;
  52996. }
  52997. else {
  52998. var touch = this._touches.get(e.pointerId.toString());
  52999. if (touch) {
  53000. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  53001. }
  53002. }
  53003. this._deltaJoystickVector.x = 0;
  53004. this._deltaJoystickVector.y = 0;
  53005. this._touches.remove(e.pointerId.toString());
  53006. };
  53007. /**
  53008. * Change the color of the virtual joystick
  53009. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  53010. */
  53011. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  53012. this._joystickColor = newColor;
  53013. };
  53014. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  53015. this._action = action;
  53016. };
  53017. // Define which axis you'd like to control for left & right
  53018. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  53019. switch (axis) {
  53020. case JoystickAxis.X:
  53021. case JoystickAxis.Y:
  53022. case JoystickAxis.Z:
  53023. this._axisTargetedByLeftAndRight = axis;
  53024. break;
  53025. default:
  53026. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  53027. break;
  53028. }
  53029. };
  53030. // Define which axis you'd like to control for up & down
  53031. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  53032. switch (axis) {
  53033. case JoystickAxis.X:
  53034. case JoystickAxis.Y:
  53035. case JoystickAxis.Z:
  53036. this._axisTargetedByUpAndDown = axis;
  53037. break;
  53038. default:
  53039. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  53040. break;
  53041. }
  53042. };
  53043. VirtualJoystick.prototype._clearCanvas = function () {
  53044. if (this._leftJoystick) {
  53045. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  53046. }
  53047. else {
  53048. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  53049. }
  53050. };
  53051. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  53052. var _this = this;
  53053. if (this.pressed) {
  53054. this._touches.forEach(function (touch) {
  53055. if (touch.pointerId === _this._joystickPointerID) {
  53056. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  53057. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  53058. VirtualJoystick.vjCanvasContext.beginPath();
  53059. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  53060. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  53061. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  53062. VirtualJoystick.vjCanvasContext.stroke();
  53063. VirtualJoystick.vjCanvasContext.closePath();
  53064. VirtualJoystick.vjCanvasContext.beginPath();
  53065. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  53066. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  53067. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  53068. VirtualJoystick.vjCanvasContext.stroke();
  53069. VirtualJoystick.vjCanvasContext.closePath();
  53070. VirtualJoystick.vjCanvasContext.beginPath();
  53071. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  53072. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  53073. VirtualJoystick.vjCanvasContext.stroke();
  53074. VirtualJoystick.vjCanvasContext.closePath();
  53075. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  53076. }
  53077. else {
  53078. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  53079. VirtualJoystick.vjCanvasContext.beginPath();
  53080. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  53081. VirtualJoystick.vjCanvasContext.beginPath();
  53082. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  53083. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  53084. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  53085. VirtualJoystick.vjCanvasContext.stroke();
  53086. VirtualJoystick.vjCanvasContext.closePath();
  53087. touch.prevX = touch.x;
  53088. touch.prevY = touch.y;
  53089. }
  53090. ;
  53091. });
  53092. }
  53093. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  53094. };
  53095. VirtualJoystick.prototype.releaseCanvas = function () {
  53096. if (VirtualJoystick.vjCanvas) {
  53097. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  53098. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  53099. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  53100. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  53101. window.removeEventListener("resize", this._onResize);
  53102. document.body.removeChild(VirtualJoystick.vjCanvas);
  53103. VirtualJoystick.vjCanvas = null;
  53104. }
  53105. };
  53106. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  53107. VirtualJoystick._globalJoystickIndex = 0;
  53108. return VirtualJoystick;
  53109. })();
  53110. BABYLON.VirtualJoystick = VirtualJoystick;
  53111. })(BABYLON || (BABYLON = {}));
  53112. var BABYLON;
  53113. (function (BABYLON) {
  53114. // We're mainly based on the logic defined into the FreeCamera code
  53115. var VirtualJoysticksCamera = (function (_super) {
  53116. __extends(VirtualJoysticksCamera, _super);
  53117. function VirtualJoysticksCamera(name, position, scene) {
  53118. _super.call(this, name, position, scene);
  53119. this.inputs.addVirtualJoystick();
  53120. }
  53121. return VirtualJoysticksCamera;
  53122. })(BABYLON.FreeCamera);
  53123. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  53124. })(BABYLON || (BABYLON = {}));
  53125. var BABYLON;
  53126. (function (BABYLON) {
  53127. var FreeCameraVirtualJoystickInput = (function () {
  53128. function FreeCameraVirtualJoystickInput() {
  53129. }
  53130. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  53131. return this._leftjoystick;
  53132. };
  53133. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  53134. return this._rightjoystick;
  53135. };
  53136. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  53137. if (this._leftjoystick) {
  53138. var camera = this.camera;
  53139. var speed = camera._computeLocalCameraSpeed() * 50;
  53140. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  53141. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  53142. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  53143. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  53144. if (!this._leftjoystick.pressed) {
  53145. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  53146. }
  53147. if (!this._rightjoystick.pressed) {
  53148. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  53149. }
  53150. }
  53151. };
  53152. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  53153. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  53154. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  53155. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  53156. this._leftjoystick.setJoystickSensibility(0.15);
  53157. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  53158. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  53159. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  53160. this._rightjoystick.reverseUpDown = true;
  53161. this._rightjoystick.setJoystickSensibility(0.05);
  53162. this._rightjoystick.setJoystickColor("yellow");
  53163. };
  53164. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  53165. this._leftjoystick.releaseCanvas();
  53166. this._rightjoystick.releaseCanvas();
  53167. };
  53168. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  53169. return "FreeCameraVirtualJoystickInput";
  53170. };
  53171. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  53172. return "virtualJoystick";
  53173. };
  53174. return FreeCameraVirtualJoystickInput;
  53175. })();
  53176. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  53177. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  53178. })(BABYLON || (BABYLON = {}));
  53179. var BABYLON;
  53180. (function (BABYLON) {
  53181. var AnaglyphPostProcess = (function (_super) {
  53182. __extends(AnaglyphPostProcess, _super);
  53183. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  53184. var _this = this;
  53185. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  53186. this._passedProcess = rigCameras[0]._rigPostProcess;
  53187. this.onApplyObservable.add(function (effect) {
  53188. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  53189. });
  53190. }
  53191. return AnaglyphPostProcess;
  53192. })(BABYLON.PostProcess);
  53193. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  53194. })(BABYLON || (BABYLON = {}));
  53195. var BABYLON;
  53196. (function (BABYLON) {
  53197. var OutlineRenderer = (function () {
  53198. function OutlineRenderer(scene) {
  53199. this._scene = scene;
  53200. }
  53201. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  53202. var _this = this;
  53203. if (useOverlay === void 0) { useOverlay = false; }
  53204. var scene = this._scene;
  53205. var engine = this._scene.getEngine();
  53206. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  53207. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  53208. return;
  53209. }
  53210. var mesh = subMesh.getRenderingMesh();
  53211. var material = subMesh.getMaterial();
  53212. engine.enableEffect(this._effect);
  53213. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  53214. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  53215. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  53216. // Bones
  53217. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53218. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  53219. }
  53220. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  53221. // Alpha test
  53222. if (material && material.needAlphaTesting()) {
  53223. var alphaTexture = material.getAlphaTestTexture();
  53224. this._effect.setTexture("diffuseSampler", alphaTexture);
  53225. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  53226. }
  53227. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  53228. };
  53229. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  53230. var defines = [];
  53231. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  53232. var mesh = subMesh.getMesh();
  53233. var material = subMesh.getMaterial();
  53234. // Alpha test
  53235. if (material && material.needAlphaTesting()) {
  53236. defines.push("#define ALPHATEST");
  53237. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53238. attribs.push(BABYLON.VertexBuffer.UVKind);
  53239. defines.push("#define UV1");
  53240. }
  53241. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53242. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53243. defines.push("#define UV2");
  53244. }
  53245. }
  53246. // Bones
  53247. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53248. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53249. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53250. if (mesh.numBoneInfluencers > 4) {
  53251. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53252. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53253. }
  53254. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53255. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53256. }
  53257. else {
  53258. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53259. }
  53260. // Instances
  53261. if (useInstances) {
  53262. defines.push("#define INSTANCES");
  53263. attribs.push("world0");
  53264. attribs.push("world1");
  53265. attribs.push("world2");
  53266. attribs.push("world3");
  53267. }
  53268. // Get correct effect
  53269. var join = defines.join("\n");
  53270. if (this._cachedDefines !== join) {
  53271. this._cachedDefines = join;
  53272. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  53273. }
  53274. return this._effect.isReady();
  53275. };
  53276. return OutlineRenderer;
  53277. })();
  53278. BABYLON.OutlineRenderer = OutlineRenderer;
  53279. })(BABYLON || (BABYLON = {}));
  53280. var BABYLON;
  53281. (function (BABYLON) {
  53282. var MeshAssetTask = (function () {
  53283. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  53284. this.name = name;
  53285. this.meshesNames = meshesNames;
  53286. this.rootUrl = rootUrl;
  53287. this.sceneFilename = sceneFilename;
  53288. this.isCompleted = false;
  53289. }
  53290. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  53291. var _this = this;
  53292. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  53293. _this.loadedMeshes = meshes;
  53294. _this.loadedParticleSystems = particleSystems;
  53295. _this.loadedSkeletons = skeletons;
  53296. _this.isCompleted = true;
  53297. if (_this.onSuccess) {
  53298. _this.onSuccess(_this);
  53299. }
  53300. onSuccess();
  53301. }, null, function () {
  53302. if (_this.onError) {
  53303. _this.onError(_this);
  53304. }
  53305. onError();
  53306. });
  53307. };
  53308. return MeshAssetTask;
  53309. })();
  53310. BABYLON.MeshAssetTask = MeshAssetTask;
  53311. var TextFileAssetTask = (function () {
  53312. function TextFileAssetTask(name, url) {
  53313. this.name = name;
  53314. this.url = url;
  53315. this.isCompleted = false;
  53316. }
  53317. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  53318. var _this = this;
  53319. BABYLON.Tools.LoadFile(this.url, function (data) {
  53320. _this.text = data;
  53321. _this.isCompleted = true;
  53322. if (_this.onSuccess) {
  53323. _this.onSuccess(_this);
  53324. }
  53325. onSuccess();
  53326. }, null, scene.database, false, function () {
  53327. if (_this.onError) {
  53328. _this.onError(_this);
  53329. }
  53330. onError();
  53331. });
  53332. };
  53333. return TextFileAssetTask;
  53334. })();
  53335. BABYLON.TextFileAssetTask = TextFileAssetTask;
  53336. var BinaryFileAssetTask = (function () {
  53337. function BinaryFileAssetTask(name, url) {
  53338. this.name = name;
  53339. this.url = url;
  53340. this.isCompleted = false;
  53341. }
  53342. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  53343. var _this = this;
  53344. BABYLON.Tools.LoadFile(this.url, function (data) {
  53345. _this.data = data;
  53346. _this.isCompleted = true;
  53347. if (_this.onSuccess) {
  53348. _this.onSuccess(_this);
  53349. }
  53350. onSuccess();
  53351. }, null, scene.database, true, function () {
  53352. if (_this.onError) {
  53353. _this.onError(_this);
  53354. }
  53355. onError();
  53356. });
  53357. };
  53358. return BinaryFileAssetTask;
  53359. })();
  53360. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  53361. var ImageAssetTask = (function () {
  53362. function ImageAssetTask(name, url) {
  53363. this.name = name;
  53364. this.url = url;
  53365. this.isCompleted = false;
  53366. }
  53367. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  53368. var _this = this;
  53369. var img = new Image();
  53370. BABYLON.Tools.SetCorsBehavior(this.url, img);
  53371. img.onload = function () {
  53372. _this.image = img;
  53373. _this.isCompleted = true;
  53374. if (_this.onSuccess) {
  53375. _this.onSuccess(_this);
  53376. }
  53377. onSuccess();
  53378. };
  53379. img.onerror = function () {
  53380. if (_this.onError) {
  53381. _this.onError(_this);
  53382. }
  53383. onError();
  53384. };
  53385. img.src = this.url;
  53386. };
  53387. return ImageAssetTask;
  53388. })();
  53389. BABYLON.ImageAssetTask = ImageAssetTask;
  53390. var TextureAssetTask = (function () {
  53391. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  53392. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53393. this.name = name;
  53394. this.url = url;
  53395. this.noMipmap = noMipmap;
  53396. this.invertY = invertY;
  53397. this.samplingMode = samplingMode;
  53398. this.isCompleted = false;
  53399. }
  53400. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  53401. var _this = this;
  53402. var onload = function () {
  53403. _this.isCompleted = true;
  53404. if (_this.onSuccess) {
  53405. _this.onSuccess(_this);
  53406. }
  53407. onSuccess();
  53408. };
  53409. var onerror = function () {
  53410. if (_this.onError) {
  53411. _this.onError(_this);
  53412. }
  53413. onError();
  53414. };
  53415. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  53416. };
  53417. return TextureAssetTask;
  53418. })();
  53419. BABYLON.TextureAssetTask = TextureAssetTask;
  53420. var AssetsManager = (function () {
  53421. function AssetsManager(scene) {
  53422. this._tasks = new Array();
  53423. this._waitingTasksCount = 0;
  53424. this.useDefaultLoadingScreen = true;
  53425. this._scene = scene;
  53426. }
  53427. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  53428. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  53429. this._tasks.push(task);
  53430. return task;
  53431. };
  53432. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  53433. var task = new TextFileAssetTask(taskName, url);
  53434. this._tasks.push(task);
  53435. return task;
  53436. };
  53437. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  53438. var task = new BinaryFileAssetTask(taskName, url);
  53439. this._tasks.push(task);
  53440. return task;
  53441. };
  53442. AssetsManager.prototype.addImageTask = function (taskName, url) {
  53443. var task = new ImageAssetTask(taskName, url);
  53444. this._tasks.push(task);
  53445. return task;
  53446. };
  53447. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  53448. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53449. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  53450. this._tasks.push(task);
  53451. return task;
  53452. };
  53453. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  53454. this._waitingTasksCount--;
  53455. if (this._waitingTasksCount === 0) {
  53456. if (this.onFinish) {
  53457. this.onFinish(this._tasks);
  53458. }
  53459. this._scene.getEngine().hideLoadingUI();
  53460. }
  53461. };
  53462. AssetsManager.prototype._runTask = function (task) {
  53463. var _this = this;
  53464. task.run(this._scene, function () {
  53465. if (_this.onTaskSuccess) {
  53466. _this.onTaskSuccess(task);
  53467. }
  53468. _this._decreaseWaitingTasksCount();
  53469. }, function () {
  53470. if (_this.onTaskError) {
  53471. _this.onTaskError(task);
  53472. }
  53473. _this._decreaseWaitingTasksCount();
  53474. });
  53475. };
  53476. AssetsManager.prototype.reset = function () {
  53477. this._tasks = new Array();
  53478. return this;
  53479. };
  53480. AssetsManager.prototype.load = function () {
  53481. this._waitingTasksCount = this._tasks.length;
  53482. if (this._waitingTasksCount === 0) {
  53483. if (this.onFinish) {
  53484. this.onFinish(this._tasks);
  53485. }
  53486. return this;
  53487. }
  53488. if (this.useDefaultLoadingScreen) {
  53489. this._scene.getEngine().displayLoadingUI();
  53490. }
  53491. for (var index = 0; index < this._tasks.length; index++) {
  53492. var task = this._tasks[index];
  53493. this._runTask(task);
  53494. }
  53495. return this;
  53496. };
  53497. return AssetsManager;
  53498. })();
  53499. BABYLON.AssetsManager = AssetsManager;
  53500. })(BABYLON || (BABYLON = {}));
  53501. var BABYLON;
  53502. (function (BABYLON) {
  53503. var VRCameraMetrics = (function () {
  53504. function VRCameraMetrics() {
  53505. this.compensateDistortion = true;
  53506. }
  53507. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  53508. get: function () {
  53509. return this.hResolution / (2 * this.vResolution);
  53510. },
  53511. enumerable: true,
  53512. configurable: true
  53513. });
  53514. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  53515. get: function () {
  53516. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  53517. },
  53518. enumerable: true,
  53519. configurable: true
  53520. });
  53521. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  53522. get: function () {
  53523. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  53524. var h = (4 * meters) / this.hScreenSize;
  53525. return BABYLON.Matrix.Translation(h, 0, 0);
  53526. },
  53527. enumerable: true,
  53528. configurable: true
  53529. });
  53530. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  53531. get: function () {
  53532. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  53533. var h = (4 * meters) / this.hScreenSize;
  53534. return BABYLON.Matrix.Translation(-h, 0, 0);
  53535. },
  53536. enumerable: true,
  53537. configurable: true
  53538. });
  53539. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  53540. get: function () {
  53541. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  53542. },
  53543. enumerable: true,
  53544. configurable: true
  53545. });
  53546. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  53547. get: function () {
  53548. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  53549. },
  53550. enumerable: true,
  53551. configurable: true
  53552. });
  53553. VRCameraMetrics.GetDefault = function () {
  53554. var result = new VRCameraMetrics();
  53555. result.hResolution = 1280;
  53556. result.vResolution = 800;
  53557. result.hScreenSize = 0.149759993;
  53558. result.vScreenSize = 0.0935999975;
  53559. result.vScreenCenter = 0.0467999987,
  53560. result.eyeToScreenDistance = 0.0410000011;
  53561. result.lensSeparationDistance = 0.0635000020;
  53562. result.interpupillaryDistance = 0.0640000030;
  53563. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  53564. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  53565. result.postProcessScaleFactor = 1.714605507808412;
  53566. result.lensCenterOffset = 0.151976421;
  53567. return result;
  53568. };
  53569. return VRCameraMetrics;
  53570. })();
  53571. BABYLON.VRCameraMetrics = VRCameraMetrics;
  53572. })(BABYLON || (BABYLON = {}));
  53573. var BABYLON;
  53574. (function (BABYLON) {
  53575. var WebVRFreeCamera = (function (_super) {
  53576. __extends(WebVRFreeCamera, _super);
  53577. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  53578. var _this = this;
  53579. if (compensateDistortion === void 0) { compensateDistortion = false; }
  53580. if (webVROptions === void 0) { webVROptions = {}; }
  53581. _super.call(this, name, position, scene);
  53582. this.webVROptions = webVROptions;
  53583. this._vrDevice = null;
  53584. this._cacheState = null;
  53585. this._vrEnabled = false;
  53586. //enable VR
  53587. this.getEngine().initWebVR();
  53588. if (!this.getEngine().vrDisplaysPromise) {
  53589. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  53590. }
  53591. else {
  53592. //TODO get the metrics updated using the device's eye parameters!
  53593. //TODO also check that the device has the right capabilities!
  53594. this.getEngine().vrDisplaysPromise.then(function (devices) {
  53595. if (devices.length > 0) {
  53596. _this._vrEnabled = true;
  53597. if (_this.webVROptions.displayName) {
  53598. var found = devices.some(function (device) {
  53599. if (device.displayName === _this.webVROptions.displayName) {
  53600. _this._vrDevice = device;
  53601. return true;
  53602. }
  53603. else {
  53604. return false;
  53605. }
  53606. });
  53607. if (!found) {
  53608. _this._vrDevice = devices[0];
  53609. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  53610. }
  53611. }
  53612. else {
  53613. //choose the first one
  53614. _this._vrDevice = devices[0];
  53615. }
  53616. //reset the rig parameters.
  53617. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice });
  53618. }
  53619. else {
  53620. BABYLON.Tools.Error("No WebVR devices found!");
  53621. }
  53622. });
  53623. }
  53624. this.rotationQuaternion = new BABYLON.Quaternion();
  53625. this._quaternionCache = new BABYLON.Quaternion();
  53626. }
  53627. WebVRFreeCamera.prototype._checkInputs = function () {
  53628. if (this._vrEnabled) {
  53629. var currentPost = this._vrDevice.getPose();
  53630. //make sure we have data
  53631. if (currentPost && currentPost.orientation) {
  53632. this._cacheState = currentPost;
  53633. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], this._cacheState.orientation[2], this._cacheState.orientation[3]);
  53634. if (this.webVROptions.trackPosition && this._cacheState.position) {
  53635. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  53636. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  53637. }
  53638. //Flip in XY plane
  53639. this.rotationQuaternion.z *= -1;
  53640. this.rotationQuaternion.w *= -1;
  53641. }
  53642. }
  53643. _super.prototype._checkInputs.call(this);
  53644. };
  53645. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  53646. _super.prototype.attachControl.call(this, element, noPreventDefault);
  53647. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  53648. if (this._vrEnabled) {
  53649. this.getEngine().enableVR(this._vrDevice);
  53650. }
  53651. };
  53652. WebVRFreeCamera.prototype.detachControl = function (element) {
  53653. _super.prototype.detachControl.call(this, element);
  53654. this._vrEnabled = false;
  53655. this.getEngine().disableVR();
  53656. };
  53657. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  53658. //Backwards comp.
  53659. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  53660. //this.getEngine().switchFullscreen(requestPointerlock);
  53661. };
  53662. WebVRFreeCamera.prototype.getTypeName = function () {
  53663. return "WebVRFreeCamera";
  53664. };
  53665. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  53666. //uses the vrDisplay's "resetPose()".
  53667. //pitch and roll won't be affected.
  53668. this._vrDevice.resetPose();
  53669. };
  53670. return WebVRFreeCamera;
  53671. })(BABYLON.FreeCamera);
  53672. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  53673. })(BABYLON || (BABYLON = {}));
  53674. var BABYLON;
  53675. (function (BABYLON) {
  53676. // Standard optimizations
  53677. var SceneOptimization = (function () {
  53678. function SceneOptimization(priority) {
  53679. if (priority === void 0) { priority = 0; }
  53680. this.priority = priority;
  53681. this.apply = function (scene) {
  53682. return true; // Return true if everything that can be done was applied
  53683. };
  53684. }
  53685. return SceneOptimization;
  53686. })();
  53687. BABYLON.SceneOptimization = SceneOptimization;
  53688. var TextureOptimization = (function (_super) {
  53689. __extends(TextureOptimization, _super);
  53690. function TextureOptimization(priority, maximumSize) {
  53691. var _this = this;
  53692. if (priority === void 0) { priority = 0; }
  53693. if (maximumSize === void 0) { maximumSize = 1024; }
  53694. _super.call(this, priority);
  53695. this.priority = priority;
  53696. this.maximumSize = maximumSize;
  53697. this.apply = function (scene) {
  53698. var allDone = true;
  53699. for (var index = 0; index < scene.textures.length; index++) {
  53700. var texture = scene.textures[index];
  53701. if (!texture.canRescale) {
  53702. continue;
  53703. }
  53704. var currentSize = texture.getSize();
  53705. var maxDimension = Math.max(currentSize.width, currentSize.height);
  53706. if (maxDimension > _this.maximumSize) {
  53707. texture.scale(0.5);
  53708. allDone = false;
  53709. }
  53710. }
  53711. return allDone;
  53712. };
  53713. }
  53714. return TextureOptimization;
  53715. })(SceneOptimization);
  53716. BABYLON.TextureOptimization = TextureOptimization;
  53717. var HardwareScalingOptimization = (function (_super) {
  53718. __extends(HardwareScalingOptimization, _super);
  53719. function HardwareScalingOptimization(priority, maximumScale) {
  53720. var _this = this;
  53721. if (priority === void 0) { priority = 0; }
  53722. if (maximumScale === void 0) { maximumScale = 2; }
  53723. _super.call(this, priority);
  53724. this.priority = priority;
  53725. this.maximumScale = maximumScale;
  53726. this._currentScale = 1;
  53727. this.apply = function (scene) {
  53728. _this._currentScale++;
  53729. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  53730. return _this._currentScale >= _this.maximumScale;
  53731. };
  53732. }
  53733. return HardwareScalingOptimization;
  53734. })(SceneOptimization);
  53735. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  53736. var ShadowsOptimization = (function (_super) {
  53737. __extends(ShadowsOptimization, _super);
  53738. function ShadowsOptimization() {
  53739. _super.apply(this, arguments);
  53740. this.apply = function (scene) {
  53741. scene.shadowsEnabled = false;
  53742. return true;
  53743. };
  53744. }
  53745. return ShadowsOptimization;
  53746. })(SceneOptimization);
  53747. BABYLON.ShadowsOptimization = ShadowsOptimization;
  53748. var PostProcessesOptimization = (function (_super) {
  53749. __extends(PostProcessesOptimization, _super);
  53750. function PostProcessesOptimization() {
  53751. _super.apply(this, arguments);
  53752. this.apply = function (scene) {
  53753. scene.postProcessesEnabled = false;
  53754. return true;
  53755. };
  53756. }
  53757. return PostProcessesOptimization;
  53758. })(SceneOptimization);
  53759. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  53760. var LensFlaresOptimization = (function (_super) {
  53761. __extends(LensFlaresOptimization, _super);
  53762. function LensFlaresOptimization() {
  53763. _super.apply(this, arguments);
  53764. this.apply = function (scene) {
  53765. scene.lensFlaresEnabled = false;
  53766. return true;
  53767. };
  53768. }
  53769. return LensFlaresOptimization;
  53770. })(SceneOptimization);
  53771. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  53772. var ParticlesOptimization = (function (_super) {
  53773. __extends(ParticlesOptimization, _super);
  53774. function ParticlesOptimization() {
  53775. _super.apply(this, arguments);
  53776. this.apply = function (scene) {
  53777. scene.particlesEnabled = false;
  53778. return true;
  53779. };
  53780. }
  53781. return ParticlesOptimization;
  53782. })(SceneOptimization);
  53783. BABYLON.ParticlesOptimization = ParticlesOptimization;
  53784. var RenderTargetsOptimization = (function (_super) {
  53785. __extends(RenderTargetsOptimization, _super);
  53786. function RenderTargetsOptimization() {
  53787. _super.apply(this, arguments);
  53788. this.apply = function (scene) {
  53789. scene.renderTargetsEnabled = false;
  53790. return true;
  53791. };
  53792. }
  53793. return RenderTargetsOptimization;
  53794. })(SceneOptimization);
  53795. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  53796. var MergeMeshesOptimization = (function (_super) {
  53797. __extends(MergeMeshesOptimization, _super);
  53798. function MergeMeshesOptimization() {
  53799. var _this = this;
  53800. _super.apply(this, arguments);
  53801. this._canBeMerged = function (abstractMesh) {
  53802. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  53803. return false;
  53804. }
  53805. var mesh = abstractMesh;
  53806. if (!mesh.isVisible || !mesh.isEnabled()) {
  53807. return false;
  53808. }
  53809. if (mesh.instances.length > 0) {
  53810. return false;
  53811. }
  53812. if (mesh.skeleton || mesh.hasLODLevels) {
  53813. return false;
  53814. }
  53815. if (mesh.parent) {
  53816. return false;
  53817. }
  53818. return true;
  53819. };
  53820. this.apply = function (scene, updateSelectionTree) {
  53821. var globalPool = scene.meshes.slice(0);
  53822. var globalLength = globalPool.length;
  53823. for (var index = 0; index < globalLength; index++) {
  53824. var currentPool = new Array();
  53825. var current = globalPool[index];
  53826. // Checks
  53827. if (!_this._canBeMerged(current)) {
  53828. continue;
  53829. }
  53830. currentPool.push(current);
  53831. // Find compatible meshes
  53832. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  53833. var otherMesh = globalPool[subIndex];
  53834. if (!_this._canBeMerged(otherMesh)) {
  53835. continue;
  53836. }
  53837. if (otherMesh.material !== current.material) {
  53838. continue;
  53839. }
  53840. if (otherMesh.checkCollisions !== current.checkCollisions) {
  53841. continue;
  53842. }
  53843. currentPool.push(otherMesh);
  53844. globalLength--;
  53845. globalPool.splice(subIndex, 1);
  53846. subIndex--;
  53847. }
  53848. if (currentPool.length < 2) {
  53849. continue;
  53850. }
  53851. // Merge meshes
  53852. BABYLON.Mesh.MergeMeshes(currentPool);
  53853. }
  53854. if (updateSelectionTree != undefined) {
  53855. if (updateSelectionTree) {
  53856. scene.createOrUpdateSelectionOctree();
  53857. }
  53858. }
  53859. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  53860. scene.createOrUpdateSelectionOctree();
  53861. }
  53862. return true;
  53863. };
  53864. }
  53865. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  53866. get: function () {
  53867. return MergeMeshesOptimization._UpdateSelectionTree;
  53868. },
  53869. set: function (value) {
  53870. MergeMeshesOptimization._UpdateSelectionTree = value;
  53871. },
  53872. enumerable: true,
  53873. configurable: true
  53874. });
  53875. MergeMeshesOptimization._UpdateSelectionTree = false;
  53876. return MergeMeshesOptimization;
  53877. })(SceneOptimization);
  53878. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  53879. // Options
  53880. var SceneOptimizerOptions = (function () {
  53881. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  53882. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  53883. if (trackerDuration === void 0) { trackerDuration = 2000; }
  53884. this.targetFrameRate = targetFrameRate;
  53885. this.trackerDuration = trackerDuration;
  53886. this.optimizations = new Array();
  53887. }
  53888. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  53889. var result = new SceneOptimizerOptions(targetFrameRate);
  53890. var priority = 0;
  53891. result.optimizations.push(new MergeMeshesOptimization(priority));
  53892. result.optimizations.push(new ShadowsOptimization(priority));
  53893. result.optimizations.push(new LensFlaresOptimization(priority));
  53894. // Next priority
  53895. priority++;
  53896. result.optimizations.push(new PostProcessesOptimization(priority));
  53897. result.optimizations.push(new ParticlesOptimization(priority));
  53898. // Next priority
  53899. priority++;
  53900. result.optimizations.push(new TextureOptimization(priority, 1024));
  53901. return result;
  53902. };
  53903. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  53904. var result = new SceneOptimizerOptions(targetFrameRate);
  53905. var priority = 0;
  53906. result.optimizations.push(new MergeMeshesOptimization(priority));
  53907. result.optimizations.push(new ShadowsOptimization(priority));
  53908. result.optimizations.push(new LensFlaresOptimization(priority));
  53909. // Next priority
  53910. priority++;
  53911. result.optimizations.push(new PostProcessesOptimization(priority));
  53912. result.optimizations.push(new ParticlesOptimization(priority));
  53913. // Next priority
  53914. priority++;
  53915. result.optimizations.push(new TextureOptimization(priority, 512));
  53916. // Next priority
  53917. priority++;
  53918. result.optimizations.push(new RenderTargetsOptimization(priority));
  53919. // Next priority
  53920. priority++;
  53921. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  53922. return result;
  53923. };
  53924. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  53925. var result = new SceneOptimizerOptions(targetFrameRate);
  53926. var priority = 0;
  53927. result.optimizations.push(new MergeMeshesOptimization(priority));
  53928. result.optimizations.push(new ShadowsOptimization(priority));
  53929. result.optimizations.push(new LensFlaresOptimization(priority));
  53930. // Next priority
  53931. priority++;
  53932. result.optimizations.push(new PostProcessesOptimization(priority));
  53933. result.optimizations.push(new ParticlesOptimization(priority));
  53934. // Next priority
  53935. priority++;
  53936. result.optimizations.push(new TextureOptimization(priority, 256));
  53937. // Next priority
  53938. priority++;
  53939. result.optimizations.push(new RenderTargetsOptimization(priority));
  53940. // Next priority
  53941. priority++;
  53942. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  53943. return result;
  53944. };
  53945. return SceneOptimizerOptions;
  53946. })();
  53947. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  53948. // Scene optimizer tool
  53949. var SceneOptimizer = (function () {
  53950. function SceneOptimizer() {
  53951. }
  53952. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  53953. // TODO: add an epsilon
  53954. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  53955. if (onSuccess) {
  53956. onSuccess();
  53957. }
  53958. return;
  53959. }
  53960. // Apply current level of optimizations
  53961. var allDone = true;
  53962. var noOptimizationApplied = true;
  53963. for (var index = 0; index < options.optimizations.length; index++) {
  53964. var optimization = options.optimizations[index];
  53965. if (optimization.priority === currentPriorityLevel) {
  53966. noOptimizationApplied = false;
  53967. allDone = allDone && optimization.apply(scene);
  53968. }
  53969. }
  53970. // If no optimization was applied, this is a failure :(
  53971. if (noOptimizationApplied) {
  53972. if (onFailure) {
  53973. onFailure();
  53974. }
  53975. return;
  53976. }
  53977. // If all optimizations were done, move to next level
  53978. if (allDone) {
  53979. currentPriorityLevel++;
  53980. }
  53981. // Let's the system running for a specific amount of time before checking FPS
  53982. scene.executeWhenReady(function () {
  53983. setTimeout(function () {
  53984. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  53985. }, options.trackerDuration);
  53986. });
  53987. };
  53988. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  53989. if (!options) {
  53990. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  53991. }
  53992. // Let's the system running for a specific amount of time before checking FPS
  53993. scene.executeWhenReady(function () {
  53994. setTimeout(function () {
  53995. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  53996. }, options.trackerDuration);
  53997. });
  53998. };
  53999. return SceneOptimizer;
  54000. })();
  54001. BABYLON.SceneOptimizer = SceneOptimizer;
  54002. })(BABYLON || (BABYLON = {}));
  54003. var BABYLON;
  54004. (function (BABYLON) {
  54005. var Internals;
  54006. (function (Internals) {
  54007. var MeshLODLevel = (function () {
  54008. function MeshLODLevel(distance, mesh) {
  54009. this.distance = distance;
  54010. this.mesh = mesh;
  54011. }
  54012. return MeshLODLevel;
  54013. })();
  54014. Internals.MeshLODLevel = MeshLODLevel;
  54015. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54016. })(BABYLON || (BABYLON = {}));
  54017. var BABYLON;
  54018. (function (BABYLON) {
  54019. var RawTexture = (function (_super) {
  54020. __extends(RawTexture, _super);
  54021. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  54022. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54023. if (invertY === void 0) { invertY = false; }
  54024. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54025. _super.call(this, null, scene, !generateMipMaps, invertY);
  54026. this.format = format;
  54027. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  54028. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54029. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54030. }
  54031. RawTexture.prototype.update = function (data) {
  54032. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  54033. };
  54034. // Statics
  54035. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54036. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54037. if (invertY === void 0) { invertY = false; }
  54038. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54039. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  54040. };
  54041. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54042. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54043. if (invertY === void 0) { invertY = false; }
  54044. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54045. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  54046. };
  54047. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54048. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54049. if (invertY === void 0) { invertY = false; }
  54050. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54051. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  54052. };
  54053. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54054. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54055. if (invertY === void 0) { invertY = false; }
  54056. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54057. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  54058. };
  54059. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54060. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54061. if (invertY === void 0) { invertY = false; }
  54062. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54063. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  54064. };
  54065. return RawTexture;
  54066. })(BABYLON.Texture);
  54067. BABYLON.RawTexture = RawTexture;
  54068. })(BABYLON || (BABYLON = {}));
  54069. var BABYLON;
  54070. (function (BABYLON) {
  54071. var IndexedVector2 = (function (_super) {
  54072. __extends(IndexedVector2, _super);
  54073. function IndexedVector2(original, index) {
  54074. _super.call(this, original.x, original.y);
  54075. this.index = index;
  54076. }
  54077. return IndexedVector2;
  54078. })(BABYLON.Vector2);
  54079. var PolygonPoints = (function () {
  54080. function PolygonPoints() {
  54081. this.elements = new Array();
  54082. }
  54083. PolygonPoints.prototype.add = function (originalPoints) {
  54084. var _this = this;
  54085. var result = new Array();
  54086. originalPoints.forEach(function (point) {
  54087. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  54088. var newPoint = new IndexedVector2(point, _this.elements.length);
  54089. result.push(newPoint);
  54090. _this.elements.push(newPoint);
  54091. }
  54092. });
  54093. return result;
  54094. };
  54095. PolygonPoints.prototype.computeBounds = function () {
  54096. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  54097. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  54098. this.elements.forEach(function (point) {
  54099. // x
  54100. if (point.x < lmin.x) {
  54101. lmin.x = point.x;
  54102. }
  54103. else if (point.x > lmax.x) {
  54104. lmax.x = point.x;
  54105. }
  54106. // y
  54107. if (point.y < lmin.y) {
  54108. lmin.y = point.y;
  54109. }
  54110. else if (point.y > lmax.y) {
  54111. lmax.y = point.y;
  54112. }
  54113. });
  54114. return {
  54115. min: lmin,
  54116. max: lmax,
  54117. width: lmax.x - lmin.x,
  54118. height: lmax.y - lmin.y
  54119. };
  54120. };
  54121. return PolygonPoints;
  54122. })();
  54123. var Polygon = (function () {
  54124. function Polygon() {
  54125. }
  54126. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  54127. return [
  54128. new BABYLON.Vector2(xmin, ymin),
  54129. new BABYLON.Vector2(xmax, ymin),
  54130. new BABYLON.Vector2(xmax, ymax),
  54131. new BABYLON.Vector2(xmin, ymax)
  54132. ];
  54133. };
  54134. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  54135. if (cx === void 0) { cx = 0; }
  54136. if (cy === void 0) { cy = 0; }
  54137. if (numberOfSides === void 0) { numberOfSides = 32; }
  54138. var result = new Array();
  54139. var angle = 0;
  54140. var increment = (Math.PI * 2) / numberOfSides;
  54141. for (var i = 0; i < numberOfSides; i++) {
  54142. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  54143. angle -= increment;
  54144. }
  54145. return result;
  54146. };
  54147. Polygon.Parse = function (input) {
  54148. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  54149. var i, result = [];
  54150. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  54151. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  54152. }
  54153. return result;
  54154. };
  54155. Polygon.StartingAt = function (x, y) {
  54156. return BABYLON.Path2.StartingAt(x, y);
  54157. };
  54158. return Polygon;
  54159. })();
  54160. BABYLON.Polygon = Polygon;
  54161. var PolygonMeshBuilder = (function () {
  54162. function PolygonMeshBuilder(name, contours, scene) {
  54163. this._points = new PolygonPoints();
  54164. this._outlinepoints = new PolygonPoints();
  54165. this._holes = [];
  54166. this._epoints = new Array();
  54167. this._eholes = new Array();
  54168. this._name = name;
  54169. this._scene = scene;
  54170. var points;
  54171. if (contours instanceof BABYLON.Path2) {
  54172. points = contours.getPoints();
  54173. }
  54174. else {
  54175. points = contours;
  54176. }
  54177. this._addToepoint(points);
  54178. this._points.add(points);
  54179. this._outlinepoints.add(points);
  54180. }
  54181. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  54182. for (var _i = 0; _i < points.length; _i++) {
  54183. var p = points[_i];
  54184. this._epoints.push(p.x, p.y);
  54185. }
  54186. };
  54187. PolygonMeshBuilder.prototype.addHole = function (hole) {
  54188. this._points.add(hole);
  54189. var holepoints = new PolygonPoints();
  54190. holepoints.add(hole);
  54191. this._holes.push(holepoints);
  54192. this._eholes.push(this._epoints.length / 2);
  54193. this._addToepoint(hole);
  54194. return this;
  54195. };
  54196. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  54197. var _this = this;
  54198. if (updatable === void 0) { updatable = false; }
  54199. var result = new BABYLON.Mesh(this._name, this._scene);
  54200. var normals = [];
  54201. var positions = [];
  54202. var uvs = [];
  54203. var bounds = this._points.computeBounds();
  54204. this._points.elements.forEach(function (p) {
  54205. normals.push(0, 1.0, 0);
  54206. positions.push(p.x, 0, p.y);
  54207. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  54208. });
  54209. var indices = [];
  54210. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  54211. for (var i = 0; i < res.length; i++) {
  54212. indices.push(res[i]);
  54213. }
  54214. if (depth > 0) {
  54215. var positionscount = (positions.length / 3); //get the current pointcount
  54216. this._points.elements.forEach(function (p) {
  54217. normals.push(0, -1.0, 0);
  54218. positions.push(p.x, -depth, p.y);
  54219. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  54220. });
  54221. var totalCount = indices.length;
  54222. for (var i = 0; i < totalCount; i += 3) {
  54223. var i0 = indices[i + 0];
  54224. var i1 = indices[i + 1];
  54225. var i2 = indices[i + 2];
  54226. indices.push(i2 + positionscount);
  54227. indices.push(i1 + positionscount);
  54228. indices.push(i0 + positionscount);
  54229. }
  54230. //Add the sides
  54231. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  54232. this._holes.forEach(function (hole) {
  54233. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  54234. });
  54235. }
  54236. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  54237. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  54238. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  54239. result.setIndices(indices);
  54240. return result;
  54241. };
  54242. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  54243. var StartIndex = positions.length / 3;
  54244. var ulength = 0;
  54245. for (var i = 0; i < points.elements.length; i++) {
  54246. var p = points.elements[i];
  54247. var p1;
  54248. if ((i + 1) > points.elements.length - 1) {
  54249. p1 = points.elements[0];
  54250. }
  54251. else {
  54252. p1 = points.elements[i + 1];
  54253. }
  54254. positions.push(p.x, 0, p.y);
  54255. positions.push(p.x, -depth, p.y);
  54256. positions.push(p1.x, 0, p1.y);
  54257. positions.push(p1.x, -depth, p1.y);
  54258. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  54259. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  54260. var v3 = v2.subtract(v1);
  54261. var v4 = new BABYLON.Vector3(0, 1, 0);
  54262. var vn = BABYLON.Vector3.Cross(v3, v4);
  54263. vn = vn.normalize();
  54264. uvs.push(ulength / bounds.width, 0);
  54265. uvs.push(ulength / bounds.width, 1);
  54266. ulength += v3.length();
  54267. uvs.push((ulength / bounds.width), 0);
  54268. uvs.push((ulength / bounds.width), 1);
  54269. if (!flip) {
  54270. normals.push(-vn.x, -vn.y, -vn.z);
  54271. normals.push(-vn.x, -vn.y, -vn.z);
  54272. normals.push(-vn.x, -vn.y, -vn.z);
  54273. normals.push(-vn.x, -vn.y, -vn.z);
  54274. indices.push(StartIndex);
  54275. indices.push(StartIndex + 1);
  54276. indices.push(StartIndex + 2);
  54277. indices.push(StartIndex + 1);
  54278. indices.push(StartIndex + 3);
  54279. indices.push(StartIndex + 2);
  54280. }
  54281. else {
  54282. normals.push(vn.x, vn.y, vn.z);
  54283. normals.push(vn.x, vn.y, vn.z);
  54284. normals.push(vn.x, vn.y, vn.z);
  54285. normals.push(vn.x, vn.y, vn.z);
  54286. indices.push(StartIndex);
  54287. indices.push(StartIndex + 2);
  54288. indices.push(StartIndex + 1);
  54289. indices.push(StartIndex + 1);
  54290. indices.push(StartIndex + 2);
  54291. indices.push(StartIndex + 3);
  54292. }
  54293. StartIndex += 4;
  54294. }
  54295. ;
  54296. };
  54297. return PolygonMeshBuilder;
  54298. })();
  54299. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  54300. })(BABYLON || (BABYLON = {}));
  54301. var BABYLON;
  54302. (function (BABYLON) {
  54303. var Octree = (function () {
  54304. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  54305. if (maxDepth === void 0) { maxDepth = 2; }
  54306. this.maxDepth = maxDepth;
  54307. this.dynamicContent = new Array();
  54308. this._maxBlockCapacity = maxBlockCapacity || 64;
  54309. this._selectionContent = new BABYLON.SmartArray(1024);
  54310. this._creationFunc = creationFunc;
  54311. }
  54312. // Methods
  54313. Octree.prototype.update = function (worldMin, worldMax, entries) {
  54314. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  54315. };
  54316. Octree.prototype.addMesh = function (entry) {
  54317. for (var index = 0; index < this.blocks.length; index++) {
  54318. var block = this.blocks[index];
  54319. block.addEntry(entry);
  54320. }
  54321. };
  54322. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  54323. this._selectionContent.reset();
  54324. for (var index = 0; index < this.blocks.length; index++) {
  54325. var block = this.blocks[index];
  54326. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  54327. }
  54328. if (allowDuplicate) {
  54329. this._selectionContent.concat(this.dynamicContent);
  54330. }
  54331. else {
  54332. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  54333. }
  54334. return this._selectionContent;
  54335. };
  54336. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  54337. this._selectionContent.reset();
  54338. for (var index = 0; index < this.blocks.length; index++) {
  54339. var block = this.blocks[index];
  54340. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  54341. }
  54342. if (allowDuplicate) {
  54343. this._selectionContent.concat(this.dynamicContent);
  54344. }
  54345. else {
  54346. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  54347. }
  54348. return this._selectionContent;
  54349. };
  54350. Octree.prototype.intersectsRay = function (ray) {
  54351. this._selectionContent.reset();
  54352. for (var index = 0; index < this.blocks.length; index++) {
  54353. var block = this.blocks[index];
  54354. block.intersectsRay(ray, this._selectionContent);
  54355. }
  54356. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  54357. return this._selectionContent;
  54358. };
  54359. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  54360. target.blocks = new Array();
  54361. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  54362. // Segmenting space
  54363. for (var x = 0; x < 2; x++) {
  54364. for (var y = 0; y < 2; y++) {
  54365. for (var z = 0; z < 2; z++) {
  54366. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  54367. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  54368. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  54369. block.addEntries(entries);
  54370. target.blocks.push(block);
  54371. }
  54372. }
  54373. }
  54374. };
  54375. Octree.CreationFuncForMeshes = function (entry, block) {
  54376. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  54377. block.entries.push(entry);
  54378. }
  54379. };
  54380. Octree.CreationFuncForSubMeshes = function (entry, block) {
  54381. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  54382. block.entries.push(entry);
  54383. }
  54384. };
  54385. return Octree;
  54386. })();
  54387. BABYLON.Octree = Octree;
  54388. })(BABYLON || (BABYLON = {}));
  54389. var BABYLON;
  54390. (function (BABYLON) {
  54391. var OctreeBlock = (function () {
  54392. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  54393. this.entries = new Array();
  54394. this._boundingVectors = new Array();
  54395. this._capacity = capacity;
  54396. this._depth = depth;
  54397. this._maxDepth = maxDepth;
  54398. this._creationFunc = creationFunc;
  54399. this._minPoint = minPoint;
  54400. this._maxPoint = maxPoint;
  54401. this._boundingVectors.push(minPoint.clone());
  54402. this._boundingVectors.push(maxPoint.clone());
  54403. this._boundingVectors.push(minPoint.clone());
  54404. this._boundingVectors[2].x = maxPoint.x;
  54405. this._boundingVectors.push(minPoint.clone());
  54406. this._boundingVectors[3].y = maxPoint.y;
  54407. this._boundingVectors.push(minPoint.clone());
  54408. this._boundingVectors[4].z = maxPoint.z;
  54409. this._boundingVectors.push(maxPoint.clone());
  54410. this._boundingVectors[5].z = minPoint.z;
  54411. this._boundingVectors.push(maxPoint.clone());
  54412. this._boundingVectors[6].x = minPoint.x;
  54413. this._boundingVectors.push(maxPoint.clone());
  54414. this._boundingVectors[7].y = minPoint.y;
  54415. }
  54416. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  54417. // Property
  54418. get: function () {
  54419. return this._capacity;
  54420. },
  54421. enumerable: true,
  54422. configurable: true
  54423. });
  54424. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  54425. get: function () {
  54426. return this._minPoint;
  54427. },
  54428. enumerable: true,
  54429. configurable: true
  54430. });
  54431. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  54432. get: function () {
  54433. return this._maxPoint;
  54434. },
  54435. enumerable: true,
  54436. configurable: true
  54437. });
  54438. // Methods
  54439. OctreeBlock.prototype.addEntry = function (entry) {
  54440. if (this.blocks) {
  54441. for (var index = 0; index < this.blocks.length; index++) {
  54442. var block = this.blocks[index];
  54443. block.addEntry(entry);
  54444. }
  54445. return;
  54446. }
  54447. this._creationFunc(entry, this);
  54448. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  54449. this.createInnerBlocks();
  54450. }
  54451. };
  54452. OctreeBlock.prototype.addEntries = function (entries) {
  54453. for (var index = 0; index < entries.length; index++) {
  54454. var mesh = entries[index];
  54455. this.addEntry(mesh);
  54456. }
  54457. };
  54458. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  54459. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  54460. if (this.blocks) {
  54461. for (var index = 0; index < this.blocks.length; index++) {
  54462. var block = this.blocks[index];
  54463. block.select(frustumPlanes, selection, allowDuplicate);
  54464. }
  54465. return;
  54466. }
  54467. if (allowDuplicate) {
  54468. selection.concat(this.entries);
  54469. }
  54470. else {
  54471. selection.concatWithNoDuplicate(this.entries);
  54472. }
  54473. }
  54474. };
  54475. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  54476. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  54477. if (this.blocks) {
  54478. for (var index = 0; index < this.blocks.length; index++) {
  54479. var block = this.blocks[index];
  54480. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  54481. }
  54482. return;
  54483. }
  54484. if (allowDuplicate) {
  54485. selection.concat(this.entries);
  54486. }
  54487. else {
  54488. selection.concatWithNoDuplicate(this.entries);
  54489. }
  54490. }
  54491. };
  54492. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  54493. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  54494. if (this.blocks) {
  54495. for (var index = 0; index < this.blocks.length; index++) {
  54496. var block = this.blocks[index];
  54497. block.intersectsRay(ray, selection);
  54498. }
  54499. return;
  54500. }
  54501. selection.concatWithNoDuplicate(this.entries);
  54502. }
  54503. };
  54504. OctreeBlock.prototype.createInnerBlocks = function () {
  54505. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  54506. };
  54507. return OctreeBlock;
  54508. })();
  54509. BABYLON.OctreeBlock = OctreeBlock;
  54510. })(BABYLON || (BABYLON = {}));
  54511. var BABYLON;
  54512. (function (BABYLON) {
  54513. var BlurPostProcess = (function (_super) {
  54514. __extends(BlurPostProcess, _super);
  54515. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  54516. var _this = this;
  54517. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  54518. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  54519. this.direction = direction;
  54520. this.blurWidth = blurWidth;
  54521. this.onApplyObservable.add(function (effect) {
  54522. effect.setFloat2("screenSize", _this.width, _this.height);
  54523. effect.setVector2("direction", _this.direction);
  54524. effect.setFloat("blurWidth", _this.blurWidth);
  54525. });
  54526. }
  54527. return BlurPostProcess;
  54528. })(BABYLON.PostProcess);
  54529. BABYLON.BlurPostProcess = BlurPostProcess;
  54530. })(BABYLON || (BABYLON = {}));
  54531. var BABYLON;
  54532. (function (BABYLON) {
  54533. var RefractionPostProcess = (function (_super) {
  54534. __extends(RefractionPostProcess, _super);
  54535. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  54536. var _this = this;
  54537. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  54538. this.color = color;
  54539. this.depth = depth;
  54540. this.colorLevel = colorLevel;
  54541. this.onActivateObservable.add(function (cam) {
  54542. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  54543. });
  54544. this.onApplyObservable.add(function (effect) {
  54545. effect.setColor3("baseColor", _this.color);
  54546. effect.setFloat("depth", _this.depth);
  54547. effect.setFloat("colorLevel", _this.colorLevel);
  54548. effect.setTexture("refractionSampler", _this._refRexture);
  54549. });
  54550. }
  54551. // Methods
  54552. RefractionPostProcess.prototype.dispose = function (camera) {
  54553. if (this._refRexture) {
  54554. this._refRexture.dispose();
  54555. }
  54556. _super.prototype.dispose.call(this, camera);
  54557. };
  54558. return RefractionPostProcess;
  54559. })(BABYLON.PostProcess);
  54560. BABYLON.RefractionPostProcess = RefractionPostProcess;
  54561. })(BABYLON || (BABYLON = {}));
  54562. var BABYLON;
  54563. (function (BABYLON) {
  54564. var BlackAndWhitePostProcess = (function (_super) {
  54565. __extends(BlackAndWhitePostProcess, _super);
  54566. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  54567. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  54568. }
  54569. return BlackAndWhitePostProcess;
  54570. })(BABYLON.PostProcess);
  54571. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  54572. })(BABYLON || (BABYLON = {}));
  54573. var BABYLON;
  54574. (function (BABYLON) {
  54575. var ConvolutionPostProcess = (function (_super) {
  54576. __extends(ConvolutionPostProcess, _super);
  54577. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  54578. var _this = this;
  54579. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  54580. this.kernel = kernel;
  54581. this.onApply = function (effect) {
  54582. effect.setFloat2("screenSize", _this.width, _this.height);
  54583. effect.setArray("kernel", _this.kernel);
  54584. };
  54585. }
  54586. // Statics
  54587. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  54588. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  54589. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  54590. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  54591. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  54592. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  54593. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  54594. return ConvolutionPostProcess;
  54595. })(BABYLON.PostProcess);
  54596. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  54597. })(BABYLON || (BABYLON = {}));
  54598. var BABYLON;
  54599. (function (BABYLON) {
  54600. var FilterPostProcess = (function (_super) {
  54601. __extends(FilterPostProcess, _super);
  54602. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  54603. var _this = this;
  54604. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  54605. this.kernelMatrix = kernelMatrix;
  54606. this.onApply = function (effect) {
  54607. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  54608. };
  54609. }
  54610. return FilterPostProcess;
  54611. })(BABYLON.PostProcess);
  54612. BABYLON.FilterPostProcess = FilterPostProcess;
  54613. })(BABYLON || (BABYLON = {}));
  54614. var BABYLON;
  54615. (function (BABYLON) {
  54616. var FxaaPostProcess = (function (_super) {
  54617. __extends(FxaaPostProcess, _super);
  54618. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  54619. var _this = this;
  54620. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  54621. this.onSizeChangedObservable.add(function () {
  54622. _this.texelWidth = 1.0 / _this.width;
  54623. _this.texelHeight = 1.0 / _this.height;
  54624. });
  54625. this.onApplyObservable.add(function (effect) {
  54626. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  54627. });
  54628. }
  54629. return FxaaPostProcess;
  54630. })(BABYLON.PostProcess);
  54631. BABYLON.FxaaPostProcess = FxaaPostProcess;
  54632. })(BABYLON || (BABYLON = {}));
  54633. var BABYLON;
  54634. (function (BABYLON) {
  54635. var StereoscopicInterlacePostProcess = (function (_super) {
  54636. __extends(StereoscopicInterlacePostProcess, _super);
  54637. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  54638. var _this = this;
  54639. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  54640. this._passedProcess = rigCameras[0]._rigPostProcess;
  54641. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  54642. this.onSizeChangedObservable.add(function () {
  54643. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  54644. });
  54645. this.onApplyObservable.add(function (effect) {
  54646. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  54647. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  54648. });
  54649. }
  54650. return StereoscopicInterlacePostProcess;
  54651. })(BABYLON.PostProcess);
  54652. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  54653. })(BABYLON || (BABYLON = {}));
  54654. var BABYLON;
  54655. (function (BABYLON) {
  54656. var LensFlare = (function () {
  54657. function LensFlare(size, position, color, imgUrl, system) {
  54658. this.size = size;
  54659. this.position = position;
  54660. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  54661. this.dispose = function () {
  54662. if (this.texture) {
  54663. this.texture.dispose();
  54664. }
  54665. // Remove from scene
  54666. var index = this._system.lensFlares.indexOf(this);
  54667. this._system.lensFlares.splice(index, 1);
  54668. };
  54669. this.color = color || new BABYLON.Color3(1, 1, 1);
  54670. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  54671. this._system = system;
  54672. system.lensFlares.push(this);
  54673. }
  54674. return LensFlare;
  54675. })();
  54676. BABYLON.LensFlare = LensFlare;
  54677. })(BABYLON || (BABYLON = {}));
  54678. var BABYLON;
  54679. (function (BABYLON) {
  54680. var LensFlareSystem = (function () {
  54681. function LensFlareSystem(name, emitter, scene) {
  54682. this.name = name;
  54683. this.lensFlares = new Array();
  54684. this.borderLimit = 300;
  54685. this.viewportBorder = 0;
  54686. this.layerMask = 0x0FFFFFFF;
  54687. this._vertexBuffers = {};
  54688. this._isEnabled = true;
  54689. this._scene = scene;
  54690. this._emitter = emitter;
  54691. this.id = name;
  54692. scene.lensFlareSystems.push(this);
  54693. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  54694. var engine = scene.getEngine();
  54695. // VBO
  54696. var vertices = [];
  54697. vertices.push(1, 1);
  54698. vertices.push(-1, 1);
  54699. vertices.push(-1, -1);
  54700. vertices.push(1, -1);
  54701. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  54702. // Indices
  54703. var indices = [];
  54704. indices.push(0);
  54705. indices.push(1);
  54706. indices.push(2);
  54707. indices.push(0);
  54708. indices.push(2);
  54709. indices.push(3);
  54710. this._indexBuffer = engine.createIndexBuffer(indices);
  54711. // Effects
  54712. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  54713. }
  54714. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  54715. get: function () {
  54716. return this._isEnabled;
  54717. },
  54718. set: function (value) {
  54719. this._isEnabled = value;
  54720. },
  54721. enumerable: true,
  54722. configurable: true
  54723. });
  54724. LensFlareSystem.prototype.getScene = function () {
  54725. return this._scene;
  54726. };
  54727. LensFlareSystem.prototype.getEmitter = function () {
  54728. return this._emitter;
  54729. };
  54730. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  54731. this._emitter = newEmitter;
  54732. };
  54733. LensFlareSystem.prototype.getEmitterPosition = function () {
  54734. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  54735. };
  54736. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  54737. var position = this.getEmitterPosition();
  54738. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  54739. this._positionX = position.x;
  54740. this._positionY = position.y;
  54741. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  54742. if (this.viewportBorder > 0) {
  54743. globalViewport.x -= this.viewportBorder;
  54744. globalViewport.y -= this.viewportBorder;
  54745. globalViewport.width += this.viewportBorder * 2;
  54746. globalViewport.height += this.viewportBorder * 2;
  54747. position.x += this.viewportBorder;
  54748. position.y += this.viewportBorder;
  54749. this._positionX += this.viewportBorder;
  54750. this._positionY += this.viewportBorder;
  54751. }
  54752. if (position.z > 0) {
  54753. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  54754. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  54755. return true;
  54756. }
  54757. return true;
  54758. }
  54759. return false;
  54760. };
  54761. LensFlareSystem.prototype._isVisible = function () {
  54762. if (!this._isEnabled) {
  54763. return false;
  54764. }
  54765. var emitterPosition = this.getEmitterPosition();
  54766. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  54767. var distance = direction.length();
  54768. direction.normalize();
  54769. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  54770. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  54771. return !pickInfo.hit || pickInfo.distance > distance;
  54772. };
  54773. LensFlareSystem.prototype.render = function () {
  54774. if (!this._effect.isReady())
  54775. return false;
  54776. var engine = this._scene.getEngine();
  54777. var viewport = this._scene.activeCamera.viewport;
  54778. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  54779. // Position
  54780. if (!this.computeEffectivePosition(globalViewport)) {
  54781. return false;
  54782. }
  54783. // Visibility
  54784. if (!this._isVisible()) {
  54785. return false;
  54786. }
  54787. // Intensity
  54788. var awayX;
  54789. var awayY;
  54790. if (this._positionX < this.borderLimit + globalViewport.x) {
  54791. awayX = this.borderLimit + globalViewport.x - this._positionX;
  54792. }
  54793. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  54794. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  54795. }
  54796. else {
  54797. awayX = 0;
  54798. }
  54799. if (this._positionY < this.borderLimit + globalViewport.y) {
  54800. awayY = this.borderLimit + globalViewport.y - this._positionY;
  54801. }
  54802. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  54803. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  54804. }
  54805. else {
  54806. awayY = 0;
  54807. }
  54808. var away = (awayX > awayY) ? awayX : awayY;
  54809. away -= this.viewportBorder;
  54810. if (away > this.borderLimit) {
  54811. away = this.borderLimit;
  54812. }
  54813. var intensity = 1.0 - (away / this.borderLimit);
  54814. if (intensity < 0) {
  54815. return false;
  54816. }
  54817. if (intensity > 1.0) {
  54818. intensity = 1.0;
  54819. }
  54820. if (this.viewportBorder > 0) {
  54821. globalViewport.x += this.viewportBorder;
  54822. globalViewport.y += this.viewportBorder;
  54823. globalViewport.width -= this.viewportBorder * 2;
  54824. globalViewport.height -= this.viewportBorder * 2;
  54825. this._positionX -= this.viewportBorder;
  54826. this._positionY -= this.viewportBorder;
  54827. }
  54828. // Position
  54829. var centerX = globalViewport.x + globalViewport.width / 2;
  54830. var centerY = globalViewport.y + globalViewport.height / 2;
  54831. var distX = centerX - this._positionX;
  54832. var distY = centerY - this._positionY;
  54833. // Effects
  54834. engine.enableEffect(this._effect);
  54835. engine.setState(false);
  54836. engine.setDepthBuffer(false);
  54837. // VBOs
  54838. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54839. // Flares
  54840. for (var index = 0; index < this.lensFlares.length; index++) {
  54841. var flare = this.lensFlares[index];
  54842. engine.setAlphaMode(flare.alphaMode);
  54843. var x = centerX - (distX * flare.position);
  54844. var y = centerY - (distY * flare.position);
  54845. var cw = flare.size;
  54846. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  54847. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  54848. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  54849. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  54850. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  54851. // Texture
  54852. this._effect.setTexture("textureSampler", flare.texture);
  54853. // Color
  54854. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  54855. // Draw order
  54856. engine.draw(true, 0, 6);
  54857. }
  54858. engine.setDepthBuffer(true);
  54859. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54860. return true;
  54861. };
  54862. LensFlareSystem.prototype.dispose = function () {
  54863. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54864. if (vertexBuffer) {
  54865. vertexBuffer.dispose();
  54866. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  54867. }
  54868. if (this._indexBuffer) {
  54869. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54870. this._indexBuffer = null;
  54871. }
  54872. while (this.lensFlares.length) {
  54873. this.lensFlares[0].dispose();
  54874. }
  54875. // Remove from scene
  54876. var index = this._scene.lensFlareSystems.indexOf(this);
  54877. this._scene.lensFlareSystems.splice(index, 1);
  54878. };
  54879. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  54880. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  54881. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  54882. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  54883. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  54884. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  54885. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  54886. var parsedFlare = parsedLensFlareSystem.flares[index];
  54887. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  54888. }
  54889. return lensFlareSystem;
  54890. };
  54891. LensFlareSystem.prototype.serialize = function () {
  54892. var serializationObject = {};
  54893. serializationObject.id = this.id;
  54894. serializationObject.name = this.name;
  54895. serializationObject.emitterId = this.getEmitter().id;
  54896. serializationObject.borderLimit = this.borderLimit;
  54897. serializationObject.flares = [];
  54898. for (var index = 0; index < this.lensFlares.length; index++) {
  54899. var flare = this.lensFlares[index];
  54900. serializationObject.flares.push({
  54901. size: flare.size,
  54902. position: flare.position,
  54903. color: flare.color.asArray(),
  54904. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  54905. });
  54906. }
  54907. return serializationObject;
  54908. };
  54909. return LensFlareSystem;
  54910. })();
  54911. BABYLON.LensFlareSystem = LensFlareSystem;
  54912. })(BABYLON || (BABYLON = {}));
  54913. var BABYLON;
  54914. (function (BABYLON) {
  54915. // We're mainly based on the logic defined into the FreeCamera code
  54916. var DeviceOrientationCamera = (function (_super) {
  54917. __extends(DeviceOrientationCamera, _super);
  54918. function DeviceOrientationCamera(name, position, scene) {
  54919. _super.call(this, name, position, scene);
  54920. this._quaternionCache = new BABYLON.Quaternion();
  54921. this.inputs.addDeviceOrientation();
  54922. }
  54923. DeviceOrientationCamera.prototype.getTypeName = function () {
  54924. return "DeviceOrientationCamera";
  54925. };
  54926. DeviceOrientationCamera.prototype._checkInputs = function () {
  54927. _super.prototype._checkInputs.call(this);
  54928. this._quaternionCache.copyFrom(this.rotationQuaternion);
  54929. if (this._initialQuaternion) {
  54930. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  54931. }
  54932. };
  54933. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  54934. var _this = this;
  54935. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  54936. //can only work if this camera has a rotation quaternion already.
  54937. if (!this.rotationQuaternion)
  54938. return;
  54939. if (!this._initialQuaternion) {
  54940. this._initialQuaternion = new BABYLON.Quaternion();
  54941. }
  54942. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  54943. ['x', 'y', 'z'].forEach(function (axisName) {
  54944. if (!axis[axisName]) {
  54945. _this._initialQuaternion[axisName] = 0;
  54946. }
  54947. else {
  54948. _this._initialQuaternion[axisName] *= -1;
  54949. }
  54950. });
  54951. this._initialQuaternion.normalize();
  54952. //force rotation update
  54953. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  54954. };
  54955. return DeviceOrientationCamera;
  54956. })(BABYLON.FreeCamera);
  54957. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  54958. })(BABYLON || (BABYLON = {}));
  54959. var BABYLON;
  54960. (function (BABYLON) {
  54961. var VRDeviceOrientationFreeCamera = (function (_super) {
  54962. __extends(VRDeviceOrientationFreeCamera, _super);
  54963. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  54964. if (compensateDistortion === void 0) { compensateDistortion = true; }
  54965. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  54966. _super.call(this, name, position, scene);
  54967. vrCameraMetrics.compensateDistortion = compensateDistortion;
  54968. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  54969. }
  54970. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  54971. return "VRDeviceOrientationFreeCamera";
  54972. };
  54973. return VRDeviceOrientationFreeCamera;
  54974. })(BABYLON.DeviceOrientationCamera);
  54975. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  54976. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  54977. __extends(VRDeviceOrientationArcRotateCamera, _super);
  54978. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  54979. if (compensateDistortion === void 0) { compensateDistortion = true; }
  54980. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  54981. _super.call(this, name, alpha, beta, radius, target, scene);
  54982. vrCameraMetrics.compensateDistortion = compensateDistortion;
  54983. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  54984. this.inputs.addVRDeviceOrientation();
  54985. }
  54986. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  54987. return "VRDeviceOrientationArcRotateCamera";
  54988. };
  54989. return VRDeviceOrientationArcRotateCamera;
  54990. })(BABYLON.ArcRotateCamera);
  54991. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  54992. })(BABYLON || (BABYLON = {}));
  54993. var BABYLON;
  54994. (function (BABYLON) {
  54995. // We're mainly based on the logic defined into the FreeCamera code
  54996. var UniversalCamera = (function (_super) {
  54997. __extends(UniversalCamera, _super);
  54998. //-- end properties for backward compatibility for inputs
  54999. function UniversalCamera(name, position, scene) {
  55000. _super.call(this, name, position, scene);
  55001. this.inputs.addGamepad();
  55002. }
  55003. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  55004. //-- Begin properties for backward compatibility for inputs
  55005. get: function () {
  55006. var gamepad = this.inputs.attached["gamepad"];
  55007. if (gamepad)
  55008. return gamepad.gamepadAngularSensibility;
  55009. },
  55010. set: function (value) {
  55011. var gamepad = this.inputs.attached["gamepad"];
  55012. if (gamepad)
  55013. gamepad.gamepadAngularSensibility = value;
  55014. },
  55015. enumerable: true,
  55016. configurable: true
  55017. });
  55018. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  55019. get: function () {
  55020. var gamepad = this.inputs.attached["gamepad"];
  55021. if (gamepad)
  55022. return gamepad.gamepadMoveSensibility;
  55023. },
  55024. set: function (value) {
  55025. var gamepad = this.inputs.attached["gamepad"];
  55026. if (gamepad)
  55027. gamepad.gamepadMoveSensibility = value;
  55028. },
  55029. enumerable: true,
  55030. configurable: true
  55031. });
  55032. UniversalCamera.prototype.getTypeName = function () {
  55033. return "UniversalCamera";
  55034. };
  55035. return UniversalCamera;
  55036. })(BABYLON.TouchCamera);
  55037. BABYLON.UniversalCamera = UniversalCamera;
  55038. })(BABYLON || (BABYLON = {}));
  55039. var BABYLON;
  55040. (function (BABYLON) {
  55041. var Gamepads = (function () {
  55042. function Gamepads(ongamedpadconnected) {
  55043. var _this = this;
  55044. this.babylonGamepads = [];
  55045. this.oneGamepadConnected = false;
  55046. this.isMonitoring = false;
  55047. this.gamepadEventSupported = 'GamepadEvent' in window;
  55048. this.gamepadSupportAvailable = (navigator.getGamepads ||
  55049. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  55050. this._callbackGamepadConnected = ongamedpadconnected;
  55051. if (this.gamepadSupportAvailable) {
  55052. // Checking if the gamepad connected event is supported (like in Firefox)
  55053. if (this.gamepadEventSupported) {
  55054. this._onGamepadConnectedEvent = function (evt) {
  55055. _this._onGamepadConnected(evt);
  55056. };
  55057. this._onGamepadDisonnectedEvent = function (evt) {
  55058. _this._onGamepadDisconnected(evt);
  55059. };
  55060. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  55061. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  55062. }
  55063. else {
  55064. this._startMonitoringGamepads();
  55065. }
  55066. }
  55067. }
  55068. Gamepads.prototype.dispose = function () {
  55069. if (Gamepads.gamepadDOMInfo) {
  55070. document.body.removeChild(Gamepads.gamepadDOMInfo);
  55071. }
  55072. if (this._onGamepadConnectedEvent) {
  55073. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  55074. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  55075. this._onGamepadConnectedEvent = null;
  55076. this._onGamepadDisonnectedEvent = null;
  55077. }
  55078. };
  55079. Gamepads.prototype._onGamepadConnected = function (evt) {
  55080. var newGamepad = this._addNewGamepad(evt.gamepad);
  55081. if (this._callbackGamepadConnected)
  55082. this._callbackGamepadConnected(newGamepad);
  55083. this._startMonitoringGamepads();
  55084. };
  55085. Gamepads.prototype._addNewGamepad = function (gamepad) {
  55086. if (!this.oneGamepadConnected) {
  55087. this.oneGamepadConnected = true;
  55088. if (Gamepads.gamepadDOMInfo) {
  55089. document.body.removeChild(Gamepads.gamepadDOMInfo);
  55090. Gamepads.gamepadDOMInfo = null;
  55091. }
  55092. }
  55093. var newGamepad;
  55094. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  55095. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  55096. }
  55097. else {
  55098. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  55099. }
  55100. this.babylonGamepads.push(newGamepad);
  55101. return newGamepad;
  55102. };
  55103. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  55104. // Remove the gamepad from the list of gamepads to monitor.
  55105. for (var i in this.babylonGamepads) {
  55106. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  55107. this.babylonGamepads.splice(+i, 1);
  55108. break;
  55109. }
  55110. }
  55111. // If no gamepads are left, stop the polling loop.
  55112. if (this.babylonGamepads.length == 0) {
  55113. this._stopMonitoringGamepads();
  55114. }
  55115. };
  55116. Gamepads.prototype._startMonitoringGamepads = function () {
  55117. if (!this.isMonitoring) {
  55118. this.isMonitoring = true;
  55119. this._checkGamepadsStatus();
  55120. }
  55121. };
  55122. Gamepads.prototype._stopMonitoringGamepads = function () {
  55123. this.isMonitoring = false;
  55124. };
  55125. Gamepads.prototype._checkGamepadsStatus = function () {
  55126. var _this = this;
  55127. // updating gamepad objects
  55128. this._updateGamepadObjects();
  55129. for (var i in this.babylonGamepads) {
  55130. this.babylonGamepads[i].update();
  55131. }
  55132. if (this.isMonitoring) {
  55133. if (window.requestAnimationFrame) {
  55134. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  55135. }
  55136. else if (window.mozRequestAnimationFrame) {
  55137. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  55138. }
  55139. else if (window.webkitRequestAnimationFrame) {
  55140. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  55141. }
  55142. }
  55143. };
  55144. // This function is called only on Chrome, which does not yet support
  55145. // connection/disconnection events, but requires you to monitor
  55146. // an array for changes.
  55147. Gamepads.prototype._updateGamepadObjects = function () {
  55148. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  55149. for (var i = 0; i < gamepads.length; i++) {
  55150. if (gamepads[i]) {
  55151. if (!(gamepads[i].index in this.babylonGamepads)) {
  55152. var newGamepad = this._addNewGamepad(gamepads[i]);
  55153. if (this._callbackGamepadConnected) {
  55154. this._callbackGamepadConnected(newGamepad);
  55155. }
  55156. }
  55157. else {
  55158. this.babylonGamepads[i].browserGamepad = gamepads[i];
  55159. }
  55160. }
  55161. }
  55162. };
  55163. return Gamepads;
  55164. })();
  55165. BABYLON.Gamepads = Gamepads;
  55166. var StickValues = (function () {
  55167. function StickValues(x, y) {
  55168. this.x = x;
  55169. this.y = y;
  55170. }
  55171. return StickValues;
  55172. })();
  55173. BABYLON.StickValues = StickValues;
  55174. var Gamepad = (function () {
  55175. function Gamepad(id, index, browserGamepad) {
  55176. this.id = id;
  55177. this.index = index;
  55178. this.browserGamepad = browserGamepad;
  55179. if (this.browserGamepad.axes.length >= 2) {
  55180. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  55181. }
  55182. if (this.browserGamepad.axes.length >= 4) {
  55183. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  55184. }
  55185. }
  55186. Gamepad.prototype.onleftstickchanged = function (callback) {
  55187. this._onleftstickchanged = callback;
  55188. };
  55189. Gamepad.prototype.onrightstickchanged = function (callback) {
  55190. this._onrightstickchanged = callback;
  55191. };
  55192. Object.defineProperty(Gamepad.prototype, "leftStick", {
  55193. get: function () {
  55194. return this._leftStick;
  55195. },
  55196. set: function (newValues) {
  55197. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  55198. this._onleftstickchanged(newValues);
  55199. }
  55200. this._leftStick = newValues;
  55201. },
  55202. enumerable: true,
  55203. configurable: true
  55204. });
  55205. Object.defineProperty(Gamepad.prototype, "rightStick", {
  55206. get: function () {
  55207. return this._rightStick;
  55208. },
  55209. set: function (newValues) {
  55210. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  55211. this._onrightstickchanged(newValues);
  55212. }
  55213. this._rightStick = newValues;
  55214. },
  55215. enumerable: true,
  55216. configurable: true
  55217. });
  55218. Gamepad.prototype.update = function () {
  55219. if (this._leftStick) {
  55220. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  55221. }
  55222. if (this._rightStick) {
  55223. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  55224. }
  55225. };
  55226. return Gamepad;
  55227. })();
  55228. BABYLON.Gamepad = Gamepad;
  55229. var GenericPad = (function (_super) {
  55230. __extends(GenericPad, _super);
  55231. function GenericPad(id, index, gamepad) {
  55232. _super.call(this, id, index, gamepad);
  55233. this.id = id;
  55234. this.index = index;
  55235. this.gamepad = gamepad;
  55236. this._buttons = new Array(gamepad.buttons.length);
  55237. }
  55238. GenericPad.prototype.onbuttondown = function (callback) {
  55239. this._onbuttondown = callback;
  55240. };
  55241. GenericPad.prototype.onbuttonup = function (callback) {
  55242. this._onbuttonup = callback;
  55243. };
  55244. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  55245. if (newValue !== currentValue) {
  55246. if (this._onbuttondown && newValue === 1) {
  55247. this._onbuttondown(buttonIndex);
  55248. }
  55249. if (this._onbuttonup && newValue === 0) {
  55250. this._onbuttonup(buttonIndex);
  55251. }
  55252. }
  55253. return newValue;
  55254. };
  55255. GenericPad.prototype.update = function () {
  55256. _super.prototype.update.call(this);
  55257. for (var index = 0; index < this._buttons.length; index++) {
  55258. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  55259. }
  55260. };
  55261. return GenericPad;
  55262. })(Gamepad);
  55263. BABYLON.GenericPad = GenericPad;
  55264. (function (Xbox360Button) {
  55265. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  55266. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  55267. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  55268. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  55269. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  55270. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  55271. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  55272. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  55273. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  55274. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  55275. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  55276. var Xbox360Button = BABYLON.Xbox360Button;
  55277. (function (Xbox360Dpad) {
  55278. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  55279. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  55280. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  55281. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  55282. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  55283. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  55284. var Xbox360Pad = (function (_super) {
  55285. __extends(Xbox360Pad, _super);
  55286. function Xbox360Pad() {
  55287. _super.apply(this, arguments);
  55288. this._leftTrigger = 0;
  55289. this._rightTrigger = 0;
  55290. this._buttonA = 0;
  55291. this._buttonB = 0;
  55292. this._buttonX = 0;
  55293. this._buttonY = 0;
  55294. this._buttonBack = 0;
  55295. this._buttonStart = 0;
  55296. this._buttonLB = 0;
  55297. this._buttonRB = 0;
  55298. this._buttonLeftStick = 0;
  55299. this._buttonRightStick = 0;
  55300. this._dPadUp = 0;
  55301. this._dPadDown = 0;
  55302. this._dPadLeft = 0;
  55303. this._dPadRight = 0;
  55304. }
  55305. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  55306. this._onlefttriggerchanged = callback;
  55307. };
  55308. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  55309. this._onrighttriggerchanged = callback;
  55310. };
  55311. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  55312. get: function () {
  55313. return this._leftTrigger;
  55314. },
  55315. set: function (newValue) {
  55316. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  55317. this._onlefttriggerchanged(newValue);
  55318. }
  55319. this._leftTrigger = newValue;
  55320. },
  55321. enumerable: true,
  55322. configurable: true
  55323. });
  55324. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  55325. get: function () {
  55326. return this._rightTrigger;
  55327. },
  55328. set: function (newValue) {
  55329. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  55330. this._onrighttriggerchanged(newValue);
  55331. }
  55332. this._rightTrigger = newValue;
  55333. },
  55334. enumerable: true,
  55335. configurable: true
  55336. });
  55337. Xbox360Pad.prototype.onbuttondown = function (callback) {
  55338. this._onbuttondown = callback;
  55339. };
  55340. Xbox360Pad.prototype.onbuttonup = function (callback) {
  55341. this._onbuttonup = callback;
  55342. };
  55343. Xbox360Pad.prototype.ondpaddown = function (callback) {
  55344. this._ondpaddown = callback;
  55345. };
  55346. Xbox360Pad.prototype.ondpadup = function (callback) {
  55347. this._ondpadup = callback;
  55348. };
  55349. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  55350. if (newValue !== currentValue) {
  55351. if (this._onbuttondown && newValue === 1) {
  55352. this._onbuttondown(buttonType);
  55353. }
  55354. if (this._onbuttonup && newValue === 0) {
  55355. this._onbuttonup(buttonType);
  55356. }
  55357. }
  55358. return newValue;
  55359. };
  55360. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  55361. if (newValue !== currentValue) {
  55362. if (this._ondpaddown && newValue === 1) {
  55363. this._ondpaddown(buttonType);
  55364. }
  55365. if (this._ondpadup && newValue === 0) {
  55366. this._ondpadup(buttonType);
  55367. }
  55368. }
  55369. return newValue;
  55370. };
  55371. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  55372. get: function () {
  55373. return this._buttonA;
  55374. },
  55375. set: function (value) {
  55376. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  55377. },
  55378. enumerable: true,
  55379. configurable: true
  55380. });
  55381. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  55382. get: function () {
  55383. return this._buttonB;
  55384. },
  55385. set: function (value) {
  55386. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  55387. },
  55388. enumerable: true,
  55389. configurable: true
  55390. });
  55391. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  55392. get: function () {
  55393. return this._buttonX;
  55394. },
  55395. set: function (value) {
  55396. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  55397. },
  55398. enumerable: true,
  55399. configurable: true
  55400. });
  55401. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  55402. get: function () {
  55403. return this._buttonY;
  55404. },
  55405. set: function (value) {
  55406. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  55407. },
  55408. enumerable: true,
  55409. configurable: true
  55410. });
  55411. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  55412. get: function () {
  55413. return this._buttonStart;
  55414. },
  55415. set: function (value) {
  55416. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  55417. },
  55418. enumerable: true,
  55419. configurable: true
  55420. });
  55421. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  55422. get: function () {
  55423. return this._buttonBack;
  55424. },
  55425. set: function (value) {
  55426. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  55427. },
  55428. enumerable: true,
  55429. configurable: true
  55430. });
  55431. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  55432. get: function () {
  55433. return this._buttonLB;
  55434. },
  55435. set: function (value) {
  55436. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  55437. },
  55438. enumerable: true,
  55439. configurable: true
  55440. });
  55441. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  55442. get: function () {
  55443. return this._buttonRB;
  55444. },
  55445. set: function (value) {
  55446. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  55447. },
  55448. enumerable: true,
  55449. configurable: true
  55450. });
  55451. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  55452. get: function () {
  55453. return this._buttonLeftStick;
  55454. },
  55455. set: function (value) {
  55456. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  55457. },
  55458. enumerable: true,
  55459. configurable: true
  55460. });
  55461. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  55462. get: function () {
  55463. return this._buttonRightStick;
  55464. },
  55465. set: function (value) {
  55466. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  55467. },
  55468. enumerable: true,
  55469. configurable: true
  55470. });
  55471. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  55472. get: function () {
  55473. return this._dPadUp;
  55474. },
  55475. set: function (value) {
  55476. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  55477. },
  55478. enumerable: true,
  55479. configurable: true
  55480. });
  55481. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  55482. get: function () {
  55483. return this._dPadDown;
  55484. },
  55485. set: function (value) {
  55486. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  55487. },
  55488. enumerable: true,
  55489. configurable: true
  55490. });
  55491. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  55492. get: function () {
  55493. return this._dPadLeft;
  55494. },
  55495. set: function (value) {
  55496. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  55497. },
  55498. enumerable: true,
  55499. configurable: true
  55500. });
  55501. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  55502. get: function () {
  55503. return this._dPadRight;
  55504. },
  55505. set: function (value) {
  55506. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  55507. },
  55508. enumerable: true,
  55509. configurable: true
  55510. });
  55511. Xbox360Pad.prototype.update = function () {
  55512. _super.prototype.update.call(this);
  55513. this.buttonA = this.browserGamepad.buttons[0].value;
  55514. this.buttonB = this.browserGamepad.buttons[1].value;
  55515. this.buttonX = this.browserGamepad.buttons[2].value;
  55516. this.buttonY = this.browserGamepad.buttons[3].value;
  55517. this.buttonLB = this.browserGamepad.buttons[4].value;
  55518. this.buttonRB = this.browserGamepad.buttons[5].value;
  55519. this.leftTrigger = this.browserGamepad.buttons[6].value;
  55520. this.rightTrigger = this.browserGamepad.buttons[7].value;
  55521. this.buttonBack = this.browserGamepad.buttons[8].value;
  55522. this.buttonStart = this.browserGamepad.buttons[9].value;
  55523. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  55524. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  55525. this.dPadUp = this.browserGamepad.buttons[12].value;
  55526. this.dPadDown = this.browserGamepad.buttons[13].value;
  55527. this.dPadLeft = this.browserGamepad.buttons[14].value;
  55528. this.dPadRight = this.browserGamepad.buttons[15].value;
  55529. };
  55530. return Xbox360Pad;
  55531. })(Gamepad);
  55532. BABYLON.Xbox360Pad = Xbox360Pad;
  55533. })(BABYLON || (BABYLON = {}));
  55534. var BABYLON;
  55535. (function (BABYLON) {
  55536. // We're mainly based on the logic defined into the FreeCamera code
  55537. var GamepadCamera = (function (_super) {
  55538. __extends(GamepadCamera, _super);
  55539. //-- end properties for backward compatibility for inputs
  55540. function GamepadCamera(name, position, scene) {
  55541. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  55542. _super.call(this, name, position, scene);
  55543. }
  55544. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  55545. //-- Begin properties for backward compatibility for inputs
  55546. get: function () {
  55547. var gamepad = this.inputs.attached["gamepad"];
  55548. if (gamepad)
  55549. return gamepad.gamepadAngularSensibility;
  55550. },
  55551. set: function (value) {
  55552. var gamepad = this.inputs.attached["gamepad"];
  55553. if (gamepad)
  55554. gamepad.gamepadAngularSensibility = value;
  55555. },
  55556. enumerable: true,
  55557. configurable: true
  55558. });
  55559. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  55560. get: function () {
  55561. var gamepad = this.inputs.attached["gamepad"];
  55562. if (gamepad)
  55563. return gamepad.gamepadMoveSensibility;
  55564. },
  55565. set: function (value) {
  55566. var gamepad = this.inputs.attached["gamepad"];
  55567. if (gamepad)
  55568. gamepad.gamepadMoveSensibility = value;
  55569. },
  55570. enumerable: true,
  55571. configurable: true
  55572. });
  55573. GamepadCamera.prototype.getTypeName = function () {
  55574. return "GamepadCamera";
  55575. };
  55576. return GamepadCamera;
  55577. })(BABYLON.UniversalCamera);
  55578. BABYLON.GamepadCamera = GamepadCamera;
  55579. })(BABYLON || (BABYLON = {}));
  55580. var BABYLON;
  55581. (function (BABYLON) {
  55582. var Analyser = (function () {
  55583. function Analyser(scene) {
  55584. this.SMOOTHING = 0.75;
  55585. this.FFT_SIZE = 512;
  55586. this.BARGRAPHAMPLITUDE = 256;
  55587. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  55588. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  55589. this._scene = scene;
  55590. this._audioEngine = BABYLON.Engine.audioEngine;
  55591. if (this._audioEngine.canUseWebAudio) {
  55592. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  55593. this._webAudioAnalyser.minDecibels = -140;
  55594. this._webAudioAnalyser.maxDecibels = 0;
  55595. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  55596. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  55597. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  55598. }
  55599. }
  55600. Analyser.prototype.getFrequencyBinCount = function () {
  55601. if (this._audioEngine.canUseWebAudio) {
  55602. return this._webAudioAnalyser.frequencyBinCount;
  55603. }
  55604. else {
  55605. return 0;
  55606. }
  55607. };
  55608. Analyser.prototype.getByteFrequencyData = function () {
  55609. if (this._audioEngine.canUseWebAudio) {
  55610. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55611. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55612. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  55613. }
  55614. return this._byteFreqs;
  55615. };
  55616. Analyser.prototype.getByteTimeDomainData = function () {
  55617. if (this._audioEngine.canUseWebAudio) {
  55618. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55619. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55620. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  55621. }
  55622. return this._byteTime;
  55623. };
  55624. Analyser.prototype.getFloatFrequencyData = function () {
  55625. if (this._audioEngine.canUseWebAudio) {
  55626. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55627. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55628. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  55629. }
  55630. return this._floatFreqs;
  55631. };
  55632. Analyser.prototype.drawDebugCanvas = function () {
  55633. var _this = this;
  55634. if (this._audioEngine.canUseWebAudio) {
  55635. if (!this._debugCanvas) {
  55636. this._debugCanvas = document.createElement("canvas");
  55637. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  55638. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  55639. this._debugCanvas.style.position = "absolute";
  55640. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  55641. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  55642. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  55643. document.body.appendChild(this._debugCanvas);
  55644. this._registerFunc = function () {
  55645. _this.drawDebugCanvas();
  55646. };
  55647. this._scene.registerBeforeRender(this._registerFunc);
  55648. }
  55649. if (this._registerFunc) {
  55650. var workingArray = this.getByteFrequencyData();
  55651. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  55652. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  55653. // Draw the frequency domain chart.
  55654. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  55655. var value = workingArray[i];
  55656. var percent = value / this.BARGRAPHAMPLITUDE;
  55657. var height = this.DEBUGCANVASSIZE.height * percent;
  55658. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  55659. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  55660. var hue = i / this.getFrequencyBinCount() * 360;
  55661. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  55662. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  55663. }
  55664. }
  55665. }
  55666. };
  55667. Analyser.prototype.stopDebugCanvas = function () {
  55668. if (this._debugCanvas) {
  55669. this._scene.unregisterBeforeRender(this._registerFunc);
  55670. this._registerFunc = null;
  55671. document.body.removeChild(this._debugCanvas);
  55672. this._debugCanvas = null;
  55673. this._debugCanvasContext = null;
  55674. }
  55675. };
  55676. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  55677. if (this._audioEngine.canUseWebAudio) {
  55678. inputAudioNode.connect(this._webAudioAnalyser);
  55679. this._webAudioAnalyser.connect(outputAudioNode);
  55680. }
  55681. };
  55682. Analyser.prototype.dispose = function () {
  55683. if (this._audioEngine.canUseWebAudio) {
  55684. this._webAudioAnalyser.disconnect();
  55685. }
  55686. };
  55687. return Analyser;
  55688. })();
  55689. BABYLON.Analyser = Analyser;
  55690. })(BABYLON || (BABYLON = {}));
  55691. var BABYLON;
  55692. (function (BABYLON) {
  55693. var DepthRenderer = (function () {
  55694. function DepthRenderer(scene, type) {
  55695. var _this = this;
  55696. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  55697. this._viewMatrix = BABYLON.Matrix.Zero();
  55698. this._projectionMatrix = BABYLON.Matrix.Zero();
  55699. this._transformMatrix = BABYLON.Matrix.Zero();
  55700. this._worldViewProjection = BABYLON.Matrix.Zero();
  55701. this._scene = scene;
  55702. var engine = scene.getEngine();
  55703. // Render target
  55704. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  55705. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55706. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55707. this._depthMap.refreshRate = 1;
  55708. this._depthMap.renderParticles = false;
  55709. this._depthMap.renderList = null;
  55710. // set default depth value to 1.0 (far away)
  55711. this._depthMap.onClearObservable.add(function (engine) {
  55712. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  55713. });
  55714. // Custom render function
  55715. var renderSubMesh = function (subMesh) {
  55716. var mesh = subMesh.getRenderingMesh();
  55717. var scene = _this._scene;
  55718. var engine = scene.getEngine();
  55719. // Culling
  55720. engine.setState(subMesh.getMaterial().backFaceCulling);
  55721. // Managing instances
  55722. var batch = mesh._getInstancesRenderList(subMesh._id);
  55723. if (batch.mustReturn) {
  55724. return;
  55725. }
  55726. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  55727. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  55728. engine.enableEffect(_this._effect);
  55729. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  55730. var material = subMesh.getMaterial();
  55731. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  55732. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  55733. // Alpha test
  55734. if (material && material.needAlphaTesting()) {
  55735. var alphaTexture = material.getAlphaTestTexture();
  55736. _this._effect.setTexture("diffuseSampler", alphaTexture);
  55737. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  55738. }
  55739. // Bones
  55740. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55741. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  55742. }
  55743. // Draw
  55744. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  55745. }
  55746. };
  55747. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  55748. var index;
  55749. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55750. renderSubMesh(opaqueSubMeshes.data[index]);
  55751. }
  55752. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55753. renderSubMesh(alphaTestSubMeshes.data[index]);
  55754. }
  55755. };
  55756. }
  55757. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  55758. var material = subMesh.getMaterial();
  55759. if (material.disableDepthWrite) {
  55760. return false;
  55761. }
  55762. var defines = [];
  55763. var attribs = [BABYLON.VertexBuffer.PositionKind];
  55764. var mesh = subMesh.getMesh();
  55765. var scene = mesh.getScene();
  55766. // Alpha test
  55767. if (material && material.needAlphaTesting()) {
  55768. defines.push("#define ALPHATEST");
  55769. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55770. attribs.push(BABYLON.VertexBuffer.UVKind);
  55771. defines.push("#define UV1");
  55772. }
  55773. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55774. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55775. defines.push("#define UV2");
  55776. }
  55777. }
  55778. // Bones
  55779. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55780. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55781. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55782. if (mesh.numBoneInfluencers > 4) {
  55783. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55784. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55785. }
  55786. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55787. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55788. }
  55789. else {
  55790. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55791. }
  55792. // Instances
  55793. if (useInstances) {
  55794. defines.push("#define INSTANCES");
  55795. attribs.push("world0");
  55796. attribs.push("world1");
  55797. attribs.push("world2");
  55798. attribs.push("world3");
  55799. }
  55800. // Get correct effect
  55801. var join = defines.join("\n");
  55802. if (this._cachedDefines !== join) {
  55803. this._cachedDefines = join;
  55804. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  55805. }
  55806. return this._effect.isReady();
  55807. };
  55808. DepthRenderer.prototype.getDepthMap = function () {
  55809. return this._depthMap;
  55810. };
  55811. // Methods
  55812. DepthRenderer.prototype.dispose = function () {
  55813. this._depthMap.dispose();
  55814. };
  55815. return DepthRenderer;
  55816. })();
  55817. BABYLON.DepthRenderer = DepthRenderer;
  55818. })(BABYLON || (BABYLON = {}));
  55819. var BABYLON;
  55820. (function (BABYLON) {
  55821. var SSAORenderingPipeline = (function (_super) {
  55822. __extends(SSAORenderingPipeline, _super);
  55823. /**
  55824. * @constructor
  55825. * @param {string} name - The rendering pipeline name
  55826. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  55827. * @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 }
  55828. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55829. */
  55830. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  55831. var _this = this;
  55832. _super.call(this, scene.getEngine(), name);
  55833. // Members
  55834. /**
  55835. * The PassPostProcess id in the pipeline that contains the original scene color
  55836. * @type {string}
  55837. */
  55838. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  55839. /**
  55840. * The SSAO PostProcess id in the pipeline
  55841. * @type {string}
  55842. */
  55843. this.SSAORenderEffect = "SSAORenderEffect";
  55844. /**
  55845. * The horizontal blur PostProcess id in the pipeline
  55846. * @type {string}
  55847. */
  55848. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  55849. /**
  55850. * The vertical blur PostProcess id in the pipeline
  55851. * @type {string}
  55852. */
  55853. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  55854. /**
  55855. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  55856. * @type {string}
  55857. */
  55858. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  55859. /**
  55860. * The output strength of the SSAO post-process. Default value is 1.0.
  55861. * @type {number}
  55862. */
  55863. this.totalStrength = 1.0;
  55864. /**
  55865. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  55866. * @type {number}
  55867. */
  55868. this.radius = 0.0001;
  55869. /**
  55870. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  55871. * Must not be equal to fallOff and superior to fallOff.
  55872. * Default value is 0.975
  55873. * @type {number}
  55874. */
  55875. this.area = 0.0075;
  55876. /**
  55877. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  55878. * Must not be equal to area and inferior to area.
  55879. * Default value is 0.0
  55880. * @type {number}
  55881. */
  55882. this.fallOff = 0.000001;
  55883. /**
  55884. * The base color of the SSAO post-process
  55885. * The final result is "base + ssao" between [0, 1]
  55886. * @type {number}
  55887. */
  55888. this.base = 0.5;
  55889. this._firstUpdate = true;
  55890. this._scene = scene;
  55891. // Set up assets
  55892. this._createRandomTexture();
  55893. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  55894. var ssaoRatio = ratio.ssaoRatio || ratio;
  55895. var combineRatio = ratio.combineRatio || ratio;
  55896. this._ratio = {
  55897. ssaoRatio: ssaoRatio,
  55898. combineRatio: combineRatio
  55899. };
  55900. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  55901. this._createSSAOPostProcess(ssaoRatio);
  55902. this._createBlurPostProcess(ssaoRatio);
  55903. this._createSSAOCombinePostProcess(combineRatio);
  55904. // Set up pipeline
  55905. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  55906. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  55907. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  55908. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  55909. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  55910. // Finish
  55911. scene.postProcessRenderPipelineManager.addPipeline(this);
  55912. if (cameras)
  55913. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  55914. }
  55915. // Public Methods
  55916. /**
  55917. * Returns the horizontal blur PostProcess
  55918. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  55919. */
  55920. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  55921. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  55922. return null;
  55923. };
  55924. /**
  55925. * Returns the vertical blur PostProcess
  55926. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  55927. */
  55928. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  55929. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  55930. return null;
  55931. };
  55932. /**
  55933. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  55934. */
  55935. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  55936. if (disableDepthRender === void 0) { disableDepthRender = false; }
  55937. for (var i = 0; i < this._scene.cameras.length; i++) {
  55938. var camera = this._scene.cameras[i];
  55939. this._originalColorPostProcess.dispose(camera);
  55940. this._ssaoPostProcess.dispose(camera);
  55941. this._blurHPostProcess.dispose(camera);
  55942. this._blurVPostProcess.dispose(camera);
  55943. this._ssaoCombinePostProcess.dispose(camera);
  55944. }
  55945. this._randomTexture.dispose();
  55946. if (disableDepthRender)
  55947. this._scene.disableDepthRenderer();
  55948. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  55949. };
  55950. // Private Methods
  55951. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  55952. var _this = this;
  55953. /*
  55954. var samplerOffsets = [
  55955. -8.0, -6.0, -4.0, -2.0,
  55956. 0.0,
  55957. 2.0, 4.0, 6.0, 8.0
  55958. ];
  55959. */
  55960. var samples = 16;
  55961. var samplerOffsets = [];
  55962. for (var i = -8; i < 8; i++) {
  55963. samplerOffsets.push(i * 2);
  55964. }
  55965. 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");
  55966. this._blurHPostProcess.onApply = function (effect) {
  55967. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  55968. effect.setTexture("depthSampler", _this._depthTexture);
  55969. if (_this._firstUpdate) {
  55970. effect.setArray("samplerOffsets", samplerOffsets);
  55971. }
  55972. };
  55973. 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");
  55974. this._blurVPostProcess.onApply = function (effect) {
  55975. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  55976. effect.setTexture("depthSampler", _this._depthTexture);
  55977. if (_this._firstUpdate) {
  55978. effect.setArray("samplerOffsets", samplerOffsets);
  55979. _this._firstUpdate = false;
  55980. }
  55981. };
  55982. };
  55983. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  55984. var _this = this;
  55985. var numSamples = 16;
  55986. var sampleSphere = [
  55987. 0.5381, 0.1856, -0.4319,
  55988. 0.1379, 0.2486, 0.4430,
  55989. 0.3371, 0.5679, -0.0057,
  55990. -0.6999, -0.0451, -0.0019,
  55991. 0.0689, -0.1598, -0.8547,
  55992. 0.0560, 0.0069, -0.1843,
  55993. -0.0146, 0.1402, 0.0762,
  55994. 0.0100, -0.1924, -0.0344,
  55995. -0.3577, -0.5301, -0.4358,
  55996. -0.3169, 0.1063, 0.0158,
  55997. 0.0103, -0.5869, 0.0046,
  55998. -0.0897, -0.4940, 0.3287,
  55999. 0.7119, -0.0154, -0.0918,
  56000. -0.0533, 0.0596, -0.5411,
  56001. 0.0352, -0.0631, 0.5460,
  56002. -0.4776, 0.2847, -0.0271
  56003. ];
  56004. var samplesFactor = 1.0 / numSamples;
  56005. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  56006. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  56007. "area", "fallOff", "base", "range", "viewport"
  56008. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  56009. var viewport = new BABYLON.Vector2(0, 0);
  56010. this._ssaoPostProcess.onApply = function (effect) {
  56011. if (_this._firstUpdate) {
  56012. effect.setArray3("sampleSphere", sampleSphere);
  56013. effect.setFloat("samplesFactor", samplesFactor);
  56014. effect.setFloat("randTextureTiles", 4.0);
  56015. }
  56016. effect.setFloat("totalStrength", _this.totalStrength);
  56017. effect.setFloat("radius", _this.radius);
  56018. effect.setFloat("area", _this.area);
  56019. effect.setFloat("fallOff", _this.fallOff);
  56020. effect.setFloat("base", _this.base);
  56021. effect.setTexture("textureSampler", _this._depthTexture);
  56022. effect.setTexture("randomSampler", _this._randomTexture);
  56023. };
  56024. };
  56025. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  56026. var _this = this;
  56027. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  56028. this._ssaoCombinePostProcess.onApply = function (effect) {
  56029. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  56030. };
  56031. };
  56032. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  56033. var size = 512;
  56034. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  56035. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56036. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56037. var context = this._randomTexture.getContext();
  56038. var rand = function (min, max) {
  56039. return Math.random() * (max - min) + min;
  56040. };
  56041. var randVector = BABYLON.Vector3.Zero();
  56042. for (var x = 0; x < size; x++) {
  56043. for (var y = 0; y < size; y++) {
  56044. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  56045. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  56046. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  56047. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  56048. context.fillRect(x, y, 1, 1);
  56049. }
  56050. }
  56051. this._randomTexture.update(false);
  56052. };
  56053. __decorate([
  56054. BABYLON.serialize()
  56055. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  56056. __decorate([
  56057. BABYLON.serialize()
  56058. ], SSAORenderingPipeline.prototype, "radius", void 0);
  56059. __decorate([
  56060. BABYLON.serialize()
  56061. ], SSAORenderingPipeline.prototype, "area", void 0);
  56062. __decorate([
  56063. BABYLON.serialize()
  56064. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  56065. __decorate([
  56066. BABYLON.serialize()
  56067. ], SSAORenderingPipeline.prototype, "base", void 0);
  56068. __decorate([
  56069. BABYLON.serialize()
  56070. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  56071. return SSAORenderingPipeline;
  56072. })(BABYLON.PostProcessRenderPipeline);
  56073. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  56074. })(BABYLON || (BABYLON = {}));
  56075. var BABYLON;
  56076. (function (BABYLON) {
  56077. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  56078. var VolumetricLightScatteringPostProcess = (function (_super) {
  56079. __extends(VolumetricLightScatteringPostProcess, _super);
  56080. /**
  56081. * @constructor
  56082. * @param {string} name - The post-process name
  56083. * @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)
  56084. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  56085. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  56086. * @param {number} samples - The post-process quality, default 100
  56087. * @param {number} samplingMode - The post-process filtering mode
  56088. * @param {BABYLON.Engine} engine - The babylon engine
  56089. * @param {boolean} reusable - If the post-process is reusable
  56090. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  56091. */
  56092. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  56093. var _this = this;
  56094. if (samples === void 0) { samples = 100; }
  56095. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  56096. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  56097. this._screenCoordinates = BABYLON.Vector2.Zero();
  56098. /**
  56099. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  56100. * @type {Vector3}
  56101. */
  56102. this.customMeshPosition = BABYLON.Vector3.Zero();
  56103. /**
  56104. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  56105. * @type {boolean}
  56106. */
  56107. this.useCustomMeshPosition = false;
  56108. /**
  56109. * If the post-process should inverse the light scattering direction
  56110. * @type {boolean}
  56111. */
  56112. this.invert = true;
  56113. /**
  56114. * Array containing the excluded meshes not rendered in the internal pass
  56115. */
  56116. this.excludedMeshes = new Array();
  56117. /**
  56118. * Controls the overall intensity of the post-process
  56119. * @type {number}
  56120. */
  56121. this.exposure = 0.3;
  56122. /**
  56123. * Dissipates each sample's contribution in range [0, 1]
  56124. * @type {number}
  56125. */
  56126. this.decay = 0.96815;
  56127. /**
  56128. * Controls the overall intensity of each sample
  56129. * @type {number}
  56130. */
  56131. this.weight = 0.58767;
  56132. /**
  56133. * Controls the density of each sample
  56134. * @type {number}
  56135. */
  56136. this.density = 0.926;
  56137. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  56138. var engine = scene.getEngine();
  56139. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  56140. // Configure mesh
  56141. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  56142. // Configure
  56143. this._createPass(scene, ratio.passRatio || ratio);
  56144. this.onActivate = function (camera) {
  56145. if (!_this.isSupported) {
  56146. _this.dispose(camera);
  56147. }
  56148. _this.onActivate = null;
  56149. };
  56150. this.onApplyObservable.add(function (effect) {
  56151. _this._updateMeshScreenCoordinates(scene);
  56152. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  56153. effect.setFloat("exposure", _this.exposure);
  56154. effect.setFloat("decay", _this.decay);
  56155. effect.setFloat("weight", _this.weight);
  56156. effect.setFloat("density", _this.density);
  56157. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  56158. });
  56159. }
  56160. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  56161. get: function () {
  56162. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  56163. return false;
  56164. },
  56165. set: function (useDiffuseColor) {
  56166. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  56167. },
  56168. enumerable: true,
  56169. configurable: true
  56170. });
  56171. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  56172. var mesh = subMesh.getMesh();
  56173. // Render this.mesh as default
  56174. if (mesh === this.mesh) {
  56175. return mesh.material.isReady(mesh);
  56176. }
  56177. var defines = [];
  56178. var attribs = [BABYLON.VertexBuffer.PositionKind];
  56179. var material = subMesh.getMaterial();
  56180. var needUV = false;
  56181. // Alpha test
  56182. if (material) {
  56183. if (material.needAlphaTesting()) {
  56184. defines.push("#define ALPHATEST");
  56185. }
  56186. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56187. attribs.push(BABYLON.VertexBuffer.UVKind);
  56188. defines.push("#define UV1");
  56189. }
  56190. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  56191. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  56192. defines.push("#define UV2");
  56193. }
  56194. }
  56195. // Bones
  56196. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56197. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  56198. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  56199. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  56200. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  56201. }
  56202. else {
  56203. defines.push("#define NUM_BONE_INFLUENCERS 0");
  56204. }
  56205. // Instances
  56206. if (useInstances) {
  56207. defines.push("#define INSTANCES");
  56208. attribs.push("world0");
  56209. attribs.push("world1");
  56210. attribs.push("world2");
  56211. attribs.push("world3");
  56212. }
  56213. // Get correct effect
  56214. var join = defines.join("\n");
  56215. if (this._cachedDefines !== join) {
  56216. this._cachedDefines = join;
  56217. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  56218. }
  56219. return this._volumetricLightScatteringPass.isReady();
  56220. };
  56221. /**
  56222. * Sets the new light position for light scattering effect
  56223. * @param {BABYLON.Vector3} The new custom light position
  56224. */
  56225. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  56226. this.customMeshPosition = position;
  56227. };
  56228. /**
  56229. * Returns the light position for light scattering effect
  56230. * @return {BABYLON.Vector3} The custom light position
  56231. */
  56232. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  56233. return this.customMeshPosition;
  56234. };
  56235. /**
  56236. * Disposes the internal assets and detaches the post-process from the camera
  56237. */
  56238. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  56239. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  56240. if (rttIndex !== -1) {
  56241. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  56242. }
  56243. this._volumetricLightScatteringRTT.dispose();
  56244. _super.prototype.dispose.call(this, camera);
  56245. };
  56246. /**
  56247. * Returns the render target texture used by the post-process
  56248. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  56249. */
  56250. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  56251. return this._volumetricLightScatteringRTT;
  56252. };
  56253. // Private methods
  56254. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  56255. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  56256. return true;
  56257. }
  56258. return false;
  56259. };
  56260. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  56261. var _this = this;
  56262. var engine = scene.getEngine();
  56263. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  56264. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56265. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56266. this._volumetricLightScatteringRTT.renderList = null;
  56267. this._volumetricLightScatteringRTT.renderParticles = false;
  56268. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  56269. // Custom render function for submeshes
  56270. var renderSubMesh = function (subMesh) {
  56271. var mesh = subMesh.getRenderingMesh();
  56272. if (_this._meshExcluded(mesh)) {
  56273. return;
  56274. }
  56275. var scene = mesh.getScene();
  56276. var engine = scene.getEngine();
  56277. // Culling
  56278. engine.setState(subMesh.getMaterial().backFaceCulling);
  56279. // Managing instances
  56280. var batch = mesh._getInstancesRenderList(subMesh._id);
  56281. if (batch.mustReturn) {
  56282. return;
  56283. }
  56284. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  56285. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  56286. var effect = _this._volumetricLightScatteringPass;
  56287. if (mesh === _this.mesh) {
  56288. effect = subMesh.getMaterial().getEffect();
  56289. }
  56290. engine.enableEffect(effect);
  56291. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  56292. if (mesh === _this.mesh) {
  56293. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  56294. }
  56295. else {
  56296. var material = subMesh.getMaterial();
  56297. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  56298. // Alpha test
  56299. if (material && material.needAlphaTesting()) {
  56300. var alphaTexture = material.getAlphaTestTexture();
  56301. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  56302. if (alphaTexture) {
  56303. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  56304. }
  56305. }
  56306. // Bones
  56307. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56308. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  56309. }
  56310. }
  56311. // Draw
  56312. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  56313. }
  56314. };
  56315. // Render target texture callbacks
  56316. var savedSceneClearColor;
  56317. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  56318. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  56319. savedSceneClearColor = scene.clearColor;
  56320. scene.clearColor = sceneClearColor;
  56321. });
  56322. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  56323. scene.clearColor = savedSceneClearColor;
  56324. });
  56325. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  56326. var engine = scene.getEngine();
  56327. var index;
  56328. for (index = 0; index < opaqueSubMeshes.length; index++) {
  56329. renderSubMesh(opaqueSubMeshes.data[index]);
  56330. }
  56331. engine.setAlphaTesting(true);
  56332. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  56333. renderSubMesh(alphaTestSubMeshes.data[index]);
  56334. }
  56335. engine.setAlphaTesting(false);
  56336. if (transparentSubMeshes.length) {
  56337. // Sort sub meshes
  56338. for (index = 0; index < transparentSubMeshes.length; index++) {
  56339. var submesh = transparentSubMeshes.data[index];
  56340. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  56341. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  56342. }
  56343. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  56344. sortedArray.sort(function (a, b) {
  56345. // Alpha index first
  56346. if (a._alphaIndex > b._alphaIndex) {
  56347. return 1;
  56348. }
  56349. if (a._alphaIndex < b._alphaIndex) {
  56350. return -1;
  56351. }
  56352. // Then distance to camera
  56353. if (a._distanceToCamera < b._distanceToCamera) {
  56354. return 1;
  56355. }
  56356. if (a._distanceToCamera > b._distanceToCamera) {
  56357. return -1;
  56358. }
  56359. return 0;
  56360. });
  56361. // Render sub meshes
  56362. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56363. for (index = 0; index < sortedArray.length; index++) {
  56364. renderSubMesh(sortedArray[index]);
  56365. }
  56366. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56367. }
  56368. };
  56369. };
  56370. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  56371. var transform = scene.getTransformMatrix();
  56372. var meshPosition;
  56373. if (this.useCustomMeshPosition) {
  56374. meshPosition = this.customMeshPosition;
  56375. }
  56376. else if (this.attachedNode) {
  56377. meshPosition = this.attachedNode.position;
  56378. }
  56379. else {
  56380. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  56381. }
  56382. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  56383. this._screenCoordinates.x = pos.x / this._viewPort.width;
  56384. this._screenCoordinates.y = pos.y / this._viewPort.height;
  56385. if (this.invert)
  56386. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  56387. };
  56388. // Static methods
  56389. /**
  56390. * Creates a default mesh for the Volumeric Light Scattering post-process
  56391. * @param {string} The mesh name
  56392. * @param {BABYLON.Scene} The scene where to create the mesh
  56393. * @return {BABYLON.Mesh} the default mesh
  56394. */
  56395. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  56396. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  56397. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  56398. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  56399. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  56400. mesh.material = material;
  56401. return mesh;
  56402. };
  56403. __decorate([
  56404. BABYLON.serializeAsVector3()
  56405. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  56406. __decorate([
  56407. BABYLON.serialize()
  56408. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  56409. __decorate([
  56410. BABYLON.serialize()
  56411. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  56412. __decorate([
  56413. BABYLON.serializeAsMeshReference()
  56414. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  56415. __decorate([
  56416. BABYLON.serialize()
  56417. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  56418. __decorate([
  56419. BABYLON.serialize()
  56420. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  56421. __decorate([
  56422. BABYLON.serialize()
  56423. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  56424. __decorate([
  56425. BABYLON.serialize()
  56426. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  56427. __decorate([
  56428. BABYLON.serialize()
  56429. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  56430. return VolumetricLightScatteringPostProcess;
  56431. })(BABYLON.PostProcess);
  56432. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  56433. })(BABYLON || (BABYLON = {}));
  56434. // BABYLON.JS Chromatic Aberration GLSL Shader
  56435. // Author: Olivier Guyot
  56436. // Separates very slightly R, G and B colors on the edges of the screen
  56437. // Inspired by Francois Tarlier & Martins Upitis
  56438. var BABYLON;
  56439. (function (BABYLON) {
  56440. var LensRenderingPipeline = (function (_super) {
  56441. __extends(LensRenderingPipeline, _super);
  56442. /**
  56443. * @constructor
  56444. *
  56445. * Effect parameters are as follow:
  56446. * {
  56447. * chromatic_aberration: number; // from 0 to x (1 for realism)
  56448. * edge_blur: number; // from 0 to x (1 for realism)
  56449. * distortion: number; // from 0 to x (1 for realism)
  56450. * grain_amount: number; // from 0 to 1
  56451. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  56452. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  56453. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  56454. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  56455. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  56456. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  56457. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  56458. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  56459. * }
  56460. * Note: if an effect parameter is unset, effect is disabled
  56461. *
  56462. * @param {string} name - The rendering pipeline name
  56463. * @param {object} parameters - An object containing all parameters (see above)
  56464. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  56465. * @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)
  56466. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  56467. */
  56468. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  56469. var _this = this;
  56470. if (ratio === void 0) { ratio = 1.0; }
  56471. _super.call(this, scene.getEngine(), name);
  56472. // Lens effects can be of the following:
  56473. // - chromatic aberration (slight shift of RGB colors)
  56474. // - blur on the edge of the lens
  56475. // - lens distortion
  56476. // - depth-of-field blur & highlights enhancing
  56477. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  56478. // - grain effect (noise or custom texture)
  56479. // Two additional texture samplers are needed:
  56480. // - depth map (for depth-of-field)
  56481. // - grain texture
  56482. /**
  56483. * The chromatic aberration PostProcess id in the pipeline
  56484. * @type {string}
  56485. */
  56486. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  56487. /**
  56488. * The highlights enhancing PostProcess id in the pipeline
  56489. * @type {string}
  56490. */
  56491. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  56492. /**
  56493. * The depth-of-field PostProcess id in the pipeline
  56494. * @type {string}
  56495. */
  56496. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  56497. this._scene = scene;
  56498. // Fetch texture samplers
  56499. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  56500. if (parameters.grain_texture) {
  56501. this._grainTexture = parameters.grain_texture;
  56502. }
  56503. else {
  56504. this._createGrainTexture();
  56505. }
  56506. // save parameters
  56507. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  56508. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  56509. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  56510. this._distortion = parameters.distortion ? parameters.distortion : 0;
  56511. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  56512. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  56513. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  56514. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  56515. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  56516. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  56517. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  56518. // Create effects
  56519. this._createChromaticAberrationPostProcess(ratio);
  56520. this._createHighlightsPostProcess(ratio);
  56521. this._createDepthOfFieldPostProcess(ratio / 4);
  56522. // Set up pipeline
  56523. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  56524. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  56525. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  56526. if (this._highlightsGain === -1) {
  56527. this._disableEffect(this.HighlightsEnhancingEffect, null);
  56528. }
  56529. // Finish
  56530. scene.postProcessRenderPipelineManager.addPipeline(this);
  56531. if (cameras) {
  56532. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  56533. }
  56534. }
  56535. // public methods (self explanatory)
  56536. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  56537. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  56538. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  56539. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  56540. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  56541. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  56542. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  56543. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  56544. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  56545. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  56546. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  56547. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  56548. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  56549. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  56550. };
  56551. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  56552. this._highlightsPostProcess.updateEffect();
  56553. };
  56554. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  56555. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  56556. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  56557. this._highlightsGain = amount;
  56558. };
  56559. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  56560. if (this._highlightsGain === -1) {
  56561. this._highlightsGain = 1.0;
  56562. }
  56563. this._highlightsThreshold = amount;
  56564. };
  56565. LensRenderingPipeline.prototype.disableHighlights = function () {
  56566. this._highlightsGain = -1;
  56567. };
  56568. /**
  56569. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  56570. */
  56571. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  56572. if (disableDepthRender === void 0) { disableDepthRender = false; }
  56573. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  56574. this._chromaticAberrationPostProcess = undefined;
  56575. this._highlightsPostProcess = undefined;
  56576. this._depthOfFieldPostProcess = undefined;
  56577. this._grainTexture.dispose();
  56578. if (disableDepthRender)
  56579. this._scene.disableDepthRenderer();
  56580. };
  56581. // colors shifting and distortion
  56582. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  56583. var _this = this;
  56584. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  56585. [], // samplers
  56586. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  56587. this._chromaticAberrationPostProcess.onApply = function (effect) {
  56588. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  56589. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  56590. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  56591. };
  56592. };
  56593. // highlights enhancing
  56594. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  56595. var _this = this;
  56596. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  56597. [], // samplers
  56598. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  56599. this._highlightsPostProcess.onApply = function (effect) {
  56600. effect.setFloat('gain', _this._highlightsGain);
  56601. effect.setFloat('threshold', _this._highlightsThreshold);
  56602. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  56603. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  56604. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  56605. };
  56606. };
  56607. // colors shifting and distortion
  56608. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  56609. var _this = this;
  56610. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  56611. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  56612. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  56613. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  56614. this._depthOfFieldPostProcess.onApply = function (effect) {
  56615. effect.setTexture("depthSampler", _this._depthTexture);
  56616. effect.setTexture("grainSampler", _this._grainTexture);
  56617. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  56618. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  56619. effect.setFloat('grain_amount', _this._grainAmount);
  56620. effect.setBool('blur_noise', _this._blurNoise);
  56621. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  56622. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  56623. effect.setFloat('distortion', _this._distortion);
  56624. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  56625. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  56626. effect.setFloat('aperture', _this._dofAperture);
  56627. effect.setFloat('darken', _this._dofDarken);
  56628. effect.setFloat('edge_blur', _this._edgeBlur);
  56629. effect.setBool('highlights', (_this._highlightsGain !== -1));
  56630. effect.setFloat('near', _this._scene.activeCamera.minZ);
  56631. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  56632. };
  56633. };
  56634. // creates a black and white random noise texture, 512x512
  56635. LensRenderingPipeline.prototype._createGrainTexture = function () {
  56636. var size = 512;
  56637. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56638. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56639. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56640. var context = this._grainTexture.getContext();
  56641. var rand = function (min, max) {
  56642. return Math.random() * (max - min) + min;
  56643. };
  56644. var value;
  56645. for (var x = 0; x < size; x++) {
  56646. for (var y = 0; y < size; y++) {
  56647. value = Math.floor(rand(0.42, 0.58) * 255);
  56648. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  56649. context.fillRect(x, y, 1, 1);
  56650. }
  56651. }
  56652. this._grainTexture.update(false);
  56653. };
  56654. return LensRenderingPipeline;
  56655. })(BABYLON.PostProcessRenderPipeline);
  56656. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  56657. })(BABYLON || (BABYLON = {}));
  56658. //
  56659. // This post-process allows the modification of rendered colors by using
  56660. // a 'look-up table' (LUT). This effect is also called Color Grading.
  56661. //
  56662. // The object needs to be provided an url to a texture containing the color
  56663. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  56664. // Use an image editing software to tweak the LUT to match your needs.
  56665. //
  56666. // For an example of a color LUT, see here:
  56667. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  56668. // For explanations on color grading, see here:
  56669. // http://udn.epicgames.com/Three/ColorGrading.html
  56670. //
  56671. var BABYLON;
  56672. (function (BABYLON) {
  56673. var ColorCorrectionPostProcess = (function (_super) {
  56674. __extends(ColorCorrectionPostProcess, _super);
  56675. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  56676. var _this = this;
  56677. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  56678. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  56679. this._colorTableTexture.anisotropicFilteringLevel = 1;
  56680. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56681. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56682. this.onApply = function (effect) {
  56683. effect.setTexture("colorTable", _this._colorTableTexture);
  56684. };
  56685. }
  56686. return ColorCorrectionPostProcess;
  56687. })(BABYLON.PostProcess);
  56688. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  56689. })(BABYLON || (BABYLON = {}));
  56690. var BABYLON;
  56691. (function (BABYLON) {
  56692. var AnaglyphFreeCamera = (function (_super) {
  56693. __extends(AnaglyphFreeCamera, _super);
  56694. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  56695. _super.call(this, name, position, scene);
  56696. this.interaxialDistance = interaxialDistance;
  56697. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  56698. }
  56699. AnaglyphFreeCamera.prototype.getTypeName = function () {
  56700. return "AnaglyphFreeCamera";
  56701. };
  56702. return AnaglyphFreeCamera;
  56703. })(BABYLON.FreeCamera);
  56704. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  56705. var AnaglyphArcRotateCamera = (function (_super) {
  56706. __extends(AnaglyphArcRotateCamera, _super);
  56707. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  56708. _super.call(this, name, alpha, beta, radius, target, scene);
  56709. this.interaxialDistance = interaxialDistance;
  56710. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  56711. }
  56712. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  56713. return "AnaglyphArcRotateCamera";
  56714. };
  56715. return AnaglyphArcRotateCamera;
  56716. })(BABYLON.ArcRotateCamera);
  56717. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  56718. var AnaglyphGamepadCamera = (function (_super) {
  56719. __extends(AnaglyphGamepadCamera, _super);
  56720. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  56721. _super.call(this, name, position, scene);
  56722. this.interaxialDistance = interaxialDistance;
  56723. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  56724. }
  56725. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  56726. return "AnaglyphGamepadCamera";
  56727. };
  56728. return AnaglyphGamepadCamera;
  56729. })(BABYLON.GamepadCamera);
  56730. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  56731. var AnaglyphUniversalCamera = (function (_super) {
  56732. __extends(AnaglyphUniversalCamera, _super);
  56733. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  56734. _super.call(this, name, position, scene);
  56735. this.interaxialDistance = interaxialDistance;
  56736. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  56737. }
  56738. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  56739. return "AnaglyphUniversalCamera";
  56740. };
  56741. return AnaglyphUniversalCamera;
  56742. })(BABYLON.UniversalCamera);
  56743. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  56744. var StereoscopicFreeCamera = (function (_super) {
  56745. __extends(StereoscopicFreeCamera, _super);
  56746. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  56747. _super.call(this, name, position, scene);
  56748. this.interaxialDistance = interaxialDistance;
  56749. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  56750. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  56751. }
  56752. StereoscopicFreeCamera.prototype.getTypeName = function () {
  56753. return "StereoscopicFreeCamera";
  56754. };
  56755. return StereoscopicFreeCamera;
  56756. })(BABYLON.FreeCamera);
  56757. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  56758. var StereoscopicArcRotateCamera = (function (_super) {
  56759. __extends(StereoscopicArcRotateCamera, _super);
  56760. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  56761. _super.call(this, name, alpha, beta, radius, target, scene);
  56762. this.interaxialDistance = interaxialDistance;
  56763. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  56764. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  56765. }
  56766. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  56767. return "StereoscopicArcRotateCamera";
  56768. };
  56769. return StereoscopicArcRotateCamera;
  56770. })(BABYLON.ArcRotateCamera);
  56771. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  56772. var StereoscopicGamepadCamera = (function (_super) {
  56773. __extends(StereoscopicGamepadCamera, _super);
  56774. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  56775. _super.call(this, name, position, scene);
  56776. this.interaxialDistance = interaxialDistance;
  56777. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  56778. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  56779. }
  56780. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  56781. return "StereoscopicGamepadCamera";
  56782. };
  56783. return StereoscopicGamepadCamera;
  56784. })(BABYLON.GamepadCamera);
  56785. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  56786. var StereoscopicUniversalCamera = (function (_super) {
  56787. __extends(StereoscopicUniversalCamera, _super);
  56788. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  56789. _super.call(this, name, position, scene);
  56790. this.interaxialDistance = interaxialDistance;
  56791. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  56792. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  56793. }
  56794. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  56795. return "StereoscopicUniversalCamera";
  56796. };
  56797. return StereoscopicUniversalCamera;
  56798. })(BABYLON.UniversalCamera);
  56799. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  56800. })(BABYLON || (BABYLON = {}));
  56801. var BABYLON;
  56802. (function (BABYLON) {
  56803. var HDRRenderingPipeline = (function (_super) {
  56804. __extends(HDRRenderingPipeline, _super);
  56805. /**
  56806. * @constructor
  56807. * @param {string} name - The rendering pipeline name
  56808. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  56809. * @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)
  56810. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  56811. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  56812. */
  56813. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  56814. var _this = this;
  56815. if (originalPostProcess === void 0) { originalPostProcess = null; }
  56816. _super.call(this, scene.getEngine(), name);
  56817. /**
  56818. * Public members
  56819. */
  56820. // Gaussian Blur
  56821. /**
  56822. * Gaussian blur coefficient
  56823. * @type {number}
  56824. */
  56825. this.gaussCoeff = 0.3;
  56826. /**
  56827. * Gaussian blur mean
  56828. * @type {number}
  56829. */
  56830. this.gaussMean = 1.0;
  56831. /**
  56832. * Gaussian blur standard deviation
  56833. * @type {number}
  56834. */
  56835. this.gaussStandDev = 0.8;
  56836. /**
  56837. * Gaussian blur multiplier. Multiplies the blur effect
  56838. * @type {number}
  56839. */
  56840. this.gaussMultiplier = 4.0;
  56841. // HDR
  56842. /**
  56843. * Exposure, controls the overall intensity of the pipeline
  56844. * @type {number}
  56845. */
  56846. this.exposure = 1.0;
  56847. /**
  56848. * Minimum luminance that the post-process can output. Luminance is >= 0
  56849. * @type {number}
  56850. */
  56851. this.minimumLuminance = 1.0;
  56852. /**
  56853. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  56854. * @type {number}
  56855. */
  56856. this.maximumLuminance = 1e20;
  56857. /**
  56858. * Increase rate for luminance: eye adaptation speed to dark
  56859. * @type {number}
  56860. */
  56861. this.luminanceIncreaserate = 0.5;
  56862. /**
  56863. * Decrease rate for luminance: eye adaptation speed to bright
  56864. * @type {number}
  56865. */
  56866. this.luminanceDecreaseRate = 0.5;
  56867. // Bright pass
  56868. /**
  56869. * Minimum luminance needed to compute HDR
  56870. * @type {number}
  56871. */
  56872. this.brightThreshold = 0.8;
  56873. this._needUpdate = true;
  56874. this._scene = scene;
  56875. // Bright pass
  56876. this._createBrightPassPostProcess(scene, ratio);
  56877. // Down sample X4
  56878. this._createDownSampleX4PostProcess(scene, ratio);
  56879. // Create gaussian blur post-processes
  56880. this._createGaussianBlurPostProcess(scene, ratio);
  56881. // Texture adder
  56882. this._createTextureAdderPostProcess(scene, ratio);
  56883. // Luminance generator
  56884. this._createLuminanceGeneratorPostProcess(scene);
  56885. // HDR
  56886. this._createHDRPostProcess(scene, ratio);
  56887. // Pass postprocess
  56888. if (originalPostProcess === null) {
  56889. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  56890. }
  56891. else {
  56892. this._originalPostProcess = originalPostProcess;
  56893. }
  56894. // Configure pipeline
  56895. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  56896. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  56897. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  56898. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  56899. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  56900. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  56901. var addDownSamplerPostProcess = function (id) {
  56902. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  56903. };
  56904. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  56905. addDownSamplerPostProcess(i);
  56906. }
  56907. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  56908. // Finish
  56909. scene.postProcessRenderPipelineManager.addPipeline(this);
  56910. if (cameras !== null) {
  56911. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  56912. }
  56913. this.update();
  56914. }
  56915. /**
  56916. * Tells the pipeline to update its post-processes
  56917. */
  56918. HDRRenderingPipeline.prototype.update = function () {
  56919. this._needUpdate = true;
  56920. };
  56921. /**
  56922. * Returns the current calculated luminance
  56923. */
  56924. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  56925. return this._hdrCurrentLuminance;
  56926. };
  56927. /**
  56928. * Returns the currently drawn luminance
  56929. */
  56930. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  56931. return this._hdrOutputLuminance;
  56932. };
  56933. /**
  56934. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  56935. */
  56936. HDRRenderingPipeline.prototype.dispose = function () {
  56937. this._originalPostProcess = undefined;
  56938. this._brightPassPostProcess = undefined;
  56939. this._downSampleX4PostProcess = undefined;
  56940. this._guassianBlurHPostProcess = undefined;
  56941. this._guassianBlurVPostProcess = undefined;
  56942. this._textureAdderPostProcess = undefined;
  56943. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  56944. this._downSamplePostProcesses[i] = undefined;
  56945. }
  56946. this._hdrPostProcess = undefined;
  56947. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  56948. };
  56949. /**
  56950. * Creates the HDR post-process and computes the luminance adaptation
  56951. */
  56952. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  56953. var _this = this;
  56954. var hdrLastLuminance = 0.0;
  56955. this._hdrOutputLuminance = -1.0;
  56956. this._hdrCurrentLuminance = 1.0;
  56957. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  56958. this._hdrPostProcess.onApply = function (effect) {
  56959. if (_this._hdrOutputLuminance < 0.0) {
  56960. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  56961. }
  56962. else {
  56963. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  56964. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  56965. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  56966. }
  56967. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  56968. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  56969. }
  56970. else {
  56971. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  56972. }
  56973. }
  56974. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  56975. hdrLastLuminance += scene.getEngine().getDeltaTime();
  56976. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  56977. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  56978. effect.setFloat("exposure", _this.exposure);
  56979. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  56980. _this._needUpdate = false;
  56981. };
  56982. };
  56983. /**
  56984. * Texture Adder post-process
  56985. */
  56986. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  56987. var _this = this;
  56988. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  56989. this._textureAdderPostProcess.onApply = function (effect) {
  56990. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  56991. };
  56992. };
  56993. /**
  56994. * Down sample X4 post-process
  56995. */
  56996. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  56997. var _this = this;
  56998. var downSampleX4Offsets = new Array(32);
  56999. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  57000. this._downSampleX4PostProcess.onApply = function (effect) {
  57001. if (_this._needUpdate) {
  57002. var id = 0;
  57003. for (var i = -2; i < 2; i++) {
  57004. for (var j = -2; j < 2; j++) {
  57005. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  57006. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  57007. id += 2;
  57008. }
  57009. }
  57010. }
  57011. effect.setArray2("dsOffsets", downSampleX4Offsets);
  57012. };
  57013. };
  57014. /**
  57015. * Bright pass post-process
  57016. */
  57017. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  57018. var _this = this;
  57019. var brightOffsets = new Array(8);
  57020. var brightPassCallback = function (effect) {
  57021. if (_this._needUpdate) {
  57022. var sU = (1.0 / _this._brightPassPostProcess.width);
  57023. var sV = (1.0 / _this._brightPassPostProcess.height);
  57024. brightOffsets[0] = -0.5 * sU;
  57025. brightOffsets[1] = 0.5 * sV;
  57026. brightOffsets[2] = 0.5 * sU;
  57027. brightOffsets[3] = 0.5 * sV;
  57028. brightOffsets[4] = -0.5 * sU;
  57029. brightOffsets[5] = -0.5 * sV;
  57030. brightOffsets[6] = 0.5 * sU;
  57031. brightOffsets[7] = -0.5 * sV;
  57032. }
  57033. effect.setArray2("dsOffsets", brightOffsets);
  57034. effect.setFloat("brightThreshold", _this.brightThreshold);
  57035. };
  57036. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  57037. this._brightPassPostProcess.onApply = brightPassCallback;
  57038. };
  57039. /**
  57040. * Luminance generator. Creates the luminance post-process and down sample post-processes
  57041. */
  57042. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  57043. var _this = this;
  57044. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  57045. var luminanceOffsets = new Array(8);
  57046. var downSampleOffsets = new Array(18);
  57047. var halfDestPixelSize;
  57048. this._downSamplePostProcesses = new Array(lumSteps);
  57049. // Utils for luminance
  57050. var luminanceUpdateSourceOffsets = function (width, height) {
  57051. var sU = (1.0 / width);
  57052. var sV = (1.0 / height);
  57053. luminanceOffsets[0] = -0.5 * sU;
  57054. luminanceOffsets[1] = 0.5 * sV;
  57055. luminanceOffsets[2] = 0.5 * sU;
  57056. luminanceOffsets[3] = 0.5 * sV;
  57057. luminanceOffsets[4] = -0.5 * sU;
  57058. luminanceOffsets[5] = -0.5 * sV;
  57059. luminanceOffsets[6] = 0.5 * sU;
  57060. luminanceOffsets[7] = -0.5 * sV;
  57061. };
  57062. var luminanceUpdateDestOffsets = function (width, height) {
  57063. var id = 0;
  57064. for (var x = -1; x < 2; x++) {
  57065. for (var y = -1; y < 2; y++) {
  57066. downSampleOffsets[id] = (x) / width;
  57067. downSampleOffsets[id + 1] = (y) / height;
  57068. id += 2;
  57069. }
  57070. }
  57071. };
  57072. // Luminance callback
  57073. var luminanceCallback = function (effect) {
  57074. if (_this._needUpdate) {
  57075. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  57076. }
  57077. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  57078. effect.setArray2("lumOffsets", luminanceOffsets);
  57079. };
  57080. // Down sample callbacks
  57081. var downSampleCallback = function (indice) {
  57082. var i = indice;
  57083. return function (effect) {
  57084. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  57085. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  57086. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  57087. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  57088. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  57089. effect.setArray2("dsOffsets", downSampleOffsets);
  57090. };
  57091. };
  57092. var downSampleAfterRenderCallback = function (effect) {
  57093. // Unpack result
  57094. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  57095. 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);
  57096. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  57097. };
  57098. // Create luminance post-process
  57099. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  57100. 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);
  57101. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  57102. // Create down sample post-processes
  57103. for (var i = lumSteps - 2; i >= 0; i--) {
  57104. var length = Math.pow(3, i);
  57105. ratio = { width: length, height: length };
  57106. var defines = "#define DOWN_SAMPLE\n";
  57107. if (i === 0) {
  57108. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  57109. }
  57110. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57111. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  57112. if (i === 0) {
  57113. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  57114. }
  57115. }
  57116. };
  57117. /**
  57118. * Gaussian blur post-processes. Horizontal and Vertical
  57119. */
  57120. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  57121. var _this = this;
  57122. var blurOffsetsW = new Array(9);
  57123. var blurOffsetsH = new Array(9);
  57124. var blurWeights = new Array(9);
  57125. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  57126. // Utils for gaussian blur
  57127. var calculateBlurOffsets = function (height) {
  57128. var lastOutputDimensions = {
  57129. width: scene.getEngine().getRenderWidth(),
  57130. height: scene.getEngine().getRenderHeight()
  57131. };
  57132. for (var i = 0; i < 9; i++) {
  57133. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  57134. if (height) {
  57135. blurOffsetsH[i] = value;
  57136. }
  57137. else {
  57138. blurOffsetsW[i] = value;
  57139. }
  57140. }
  57141. };
  57142. var calculateWeights = function () {
  57143. var x = 0.0;
  57144. for (var i = 0; i < 9; i++) {
  57145. x = (i - 4.0) / 4.0;
  57146. 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));
  57147. }
  57148. };
  57149. // Callback
  57150. var gaussianBlurCallback = function (height) {
  57151. return function (effect) {
  57152. if (_this._needUpdate) {
  57153. calculateWeights();
  57154. calculateBlurOffsets(height);
  57155. }
  57156. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  57157. effect.setArray("blurWeights", blurWeights);
  57158. effect.setFloat("multiplier", _this.gaussMultiplier);
  57159. };
  57160. };
  57161. // Create horizontal gaussian blur post-processes
  57162. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  57163. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  57164. // Create vertical gaussian blur post-process
  57165. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  57166. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  57167. };
  57168. // Luminance generator
  57169. HDRRenderingPipeline.LUM_STEPS = 6;
  57170. return HDRRenderingPipeline;
  57171. })(BABYLON.PostProcessRenderPipeline);
  57172. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  57173. })(BABYLON || (BABYLON = {}));
  57174. var BABYLON;
  57175. (function (BABYLON) {
  57176. var FaceAdjacencies = (function () {
  57177. function FaceAdjacencies() {
  57178. this.edges = new Array();
  57179. this.edgesConnectedCount = 0;
  57180. }
  57181. return FaceAdjacencies;
  57182. })();
  57183. var EdgesRenderer = (function () {
  57184. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  57185. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  57186. if (epsilon === void 0) { epsilon = 0.95; }
  57187. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  57188. this.edgesWidthScalerForOrthographic = 1000.0;
  57189. this.edgesWidthScalerForPerspective = 50.0;
  57190. this._linesPositions = new Array();
  57191. this._linesNormals = new Array();
  57192. this._linesIndices = new Array();
  57193. this._buffers = {};
  57194. this._checkVerticesInsteadOfIndices = false;
  57195. this._source = source;
  57196. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  57197. this._epsilon = epsilon;
  57198. this._prepareRessources();
  57199. this._generateEdgesLines();
  57200. }
  57201. EdgesRenderer.prototype._prepareRessources = function () {
  57202. if (this._lineShader) {
  57203. return;
  57204. }
  57205. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  57206. attributes: ["position", "normal"],
  57207. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  57208. });
  57209. this._lineShader.disableDepthWrite = true;
  57210. this._lineShader.backFaceCulling = false;
  57211. };
  57212. EdgesRenderer.prototype.dispose = function () {
  57213. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  57214. if (buffer) {
  57215. buffer.dispose();
  57216. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  57217. }
  57218. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  57219. if (buffer) {
  57220. buffer.dispose();
  57221. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  57222. }
  57223. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  57224. this._lineShader.dispose();
  57225. };
  57226. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  57227. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  57228. return 0;
  57229. }
  57230. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  57231. return 1;
  57232. }
  57233. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  57234. return 2;
  57235. }
  57236. return -1;
  57237. };
  57238. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  57239. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  57240. return 0;
  57241. }
  57242. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  57243. return 1;
  57244. }
  57245. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  57246. return 2;
  57247. }
  57248. return -1;
  57249. };
  57250. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  57251. var needToCreateLine;
  57252. if (edge === undefined) {
  57253. needToCreateLine = true;
  57254. }
  57255. else {
  57256. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  57257. needToCreateLine = dotProduct < this._epsilon;
  57258. }
  57259. if (needToCreateLine) {
  57260. var offset = this._linesPositions.length / 3;
  57261. var normal = p0.subtract(p1);
  57262. normal.normalize();
  57263. // Positions
  57264. this._linesPositions.push(p0.x);
  57265. this._linesPositions.push(p0.y);
  57266. this._linesPositions.push(p0.z);
  57267. this._linesPositions.push(p0.x);
  57268. this._linesPositions.push(p0.y);
  57269. this._linesPositions.push(p0.z);
  57270. this._linesPositions.push(p1.x);
  57271. this._linesPositions.push(p1.y);
  57272. this._linesPositions.push(p1.z);
  57273. this._linesPositions.push(p1.x);
  57274. this._linesPositions.push(p1.y);
  57275. this._linesPositions.push(p1.z);
  57276. // Normals
  57277. this._linesNormals.push(p1.x);
  57278. this._linesNormals.push(p1.y);
  57279. this._linesNormals.push(p1.z);
  57280. this._linesNormals.push(-1);
  57281. this._linesNormals.push(p1.x);
  57282. this._linesNormals.push(p1.y);
  57283. this._linesNormals.push(p1.z);
  57284. this._linesNormals.push(1);
  57285. this._linesNormals.push(p0.x);
  57286. this._linesNormals.push(p0.y);
  57287. this._linesNormals.push(p0.z);
  57288. this._linesNormals.push(-1);
  57289. this._linesNormals.push(p0.x);
  57290. this._linesNormals.push(p0.y);
  57291. this._linesNormals.push(p0.z);
  57292. this._linesNormals.push(1);
  57293. // Indices
  57294. this._linesIndices.push(offset);
  57295. this._linesIndices.push(offset + 1);
  57296. this._linesIndices.push(offset + 2);
  57297. this._linesIndices.push(offset);
  57298. this._linesIndices.push(offset + 2);
  57299. this._linesIndices.push(offset + 3);
  57300. }
  57301. };
  57302. EdgesRenderer.prototype._generateEdgesLines = function () {
  57303. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57304. var indices = this._source.getIndices();
  57305. // First let's find adjacencies
  57306. var adjacencies = new Array();
  57307. var faceNormals = new Array();
  57308. var index;
  57309. var faceAdjacencies;
  57310. // Prepare faces
  57311. for (index = 0; index < indices.length; index += 3) {
  57312. faceAdjacencies = new FaceAdjacencies();
  57313. var p0Index = indices[index];
  57314. var p1Index = indices[index + 1];
  57315. var p2Index = indices[index + 2];
  57316. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  57317. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  57318. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  57319. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  57320. faceNormal.normalize();
  57321. faceNormals.push(faceNormal);
  57322. adjacencies.push(faceAdjacencies);
  57323. }
  57324. // Scan
  57325. for (index = 0; index < adjacencies.length; index++) {
  57326. faceAdjacencies = adjacencies[index];
  57327. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  57328. var otherFaceAdjacencies = adjacencies[otherIndex];
  57329. if (faceAdjacencies.edgesConnectedCount === 3) {
  57330. break;
  57331. }
  57332. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  57333. continue;
  57334. }
  57335. var otherP0 = indices[otherIndex * 3];
  57336. var otherP1 = indices[otherIndex * 3 + 1];
  57337. var otherP2 = indices[otherIndex * 3 + 2];
  57338. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  57339. var otherEdgeIndex;
  57340. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  57341. continue;
  57342. }
  57343. switch (edgeIndex) {
  57344. case 0:
  57345. if (this._checkVerticesInsteadOfIndices) {
  57346. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  57347. }
  57348. else {
  57349. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  57350. }
  57351. break;
  57352. case 1:
  57353. if (this._checkVerticesInsteadOfIndices) {
  57354. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  57355. }
  57356. else {
  57357. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  57358. }
  57359. break;
  57360. case 2:
  57361. if (this._checkVerticesInsteadOfIndices) {
  57362. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  57363. }
  57364. else {
  57365. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  57366. }
  57367. break;
  57368. }
  57369. if (otherEdgeIndex === -1) {
  57370. continue;
  57371. }
  57372. faceAdjacencies.edges[edgeIndex] = otherIndex;
  57373. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  57374. faceAdjacencies.edgesConnectedCount++;
  57375. otherFaceAdjacencies.edgesConnectedCount++;
  57376. if (faceAdjacencies.edgesConnectedCount === 3) {
  57377. break;
  57378. }
  57379. }
  57380. }
  57381. }
  57382. // Create lines
  57383. for (index = 0; index < adjacencies.length; index++) {
  57384. // 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
  57385. var current = adjacencies[index];
  57386. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  57387. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  57388. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  57389. }
  57390. // Merge into a single mesh
  57391. var engine = this._source.getScene().getEngine();
  57392. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  57393. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  57394. this._ib = engine.createIndexBuffer(this._linesIndices);
  57395. this._indicesCount = this._linesIndices.length;
  57396. };
  57397. EdgesRenderer.prototype.render = function () {
  57398. if (!this._lineShader.isReady()) {
  57399. return;
  57400. }
  57401. var scene = this._source.getScene();
  57402. var engine = scene.getEngine();
  57403. this._lineShader._preBind();
  57404. // VBOs
  57405. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  57406. scene.resetCachedMaterial();
  57407. this._lineShader.setColor4("color", this._source.edgesColor);
  57408. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  57409. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  57410. }
  57411. else {
  57412. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  57413. }
  57414. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  57415. this._lineShader.bind(this._source.getWorldMatrix());
  57416. // Draw order
  57417. engine.draw(true, 0, this._indicesCount);
  57418. this._lineShader.unbind();
  57419. engine.setDepthWrite(true);
  57420. };
  57421. return EdgesRenderer;
  57422. })();
  57423. BABYLON.EdgesRenderer = EdgesRenderer;
  57424. })(BABYLON || (BABYLON = {}));
  57425. var BABYLON;
  57426. (function (BABYLON) {
  57427. (function (TonemappingOperator) {
  57428. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  57429. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  57430. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  57431. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  57432. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  57433. var TonemappingOperator = BABYLON.TonemappingOperator;
  57434. ;
  57435. var TonemapPostProcess = (function (_super) {
  57436. __extends(TonemapPostProcess, _super);
  57437. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  57438. var _this = this;
  57439. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  57440. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57441. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  57442. this._operator = _operator;
  57443. this.exposureAdjustment = exposureAdjustment;
  57444. var defines = "#define ";
  57445. if (this._operator === TonemappingOperator.Hable)
  57446. defines += "HABLE_TONEMAPPING";
  57447. else if (this._operator === TonemappingOperator.Reinhard)
  57448. defines += "REINHARD_TONEMAPPING";
  57449. else if (this._operator === TonemappingOperator.HejiDawson)
  57450. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  57451. else if (this._operator === TonemappingOperator.Photographic)
  57452. defines += "PHOTOGRAPHIC_TONEMAPPING";
  57453. //sadly a second call to create the effect.
  57454. this.updateEffect(defines);
  57455. this.onApply = function (effect) {
  57456. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  57457. };
  57458. }
  57459. return TonemapPostProcess;
  57460. })(BABYLON.PostProcess);
  57461. BABYLON.TonemapPostProcess = TonemapPostProcess;
  57462. })(BABYLON || (BABYLON = {}));
  57463. var BABYLON;
  57464. (function (BABYLON) {
  57465. var ReflectionProbe = (function () {
  57466. function ReflectionProbe(name, size, scene, generateMipMaps) {
  57467. var _this = this;
  57468. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57469. this.name = name;
  57470. this._viewMatrix = BABYLON.Matrix.Identity();
  57471. this._target = BABYLON.Vector3.Zero();
  57472. this._add = BABYLON.Vector3.Zero();
  57473. this.invertYAxis = false;
  57474. this.position = BABYLON.Vector3.Zero();
  57475. this._scene = scene;
  57476. this._scene.reflectionProbes.push(this);
  57477. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  57478. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  57479. switch (faceIndex) {
  57480. case 0:
  57481. _this._add.copyFromFloats(1, 0, 0);
  57482. break;
  57483. case 1:
  57484. _this._add.copyFromFloats(-1, 0, 0);
  57485. break;
  57486. case 2:
  57487. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  57488. break;
  57489. case 3:
  57490. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  57491. break;
  57492. case 4:
  57493. _this._add.copyFromFloats(0, 0, 1);
  57494. break;
  57495. case 5:
  57496. _this._add.copyFromFloats(0, 0, -1);
  57497. break;
  57498. }
  57499. if (_this._attachedMesh) {
  57500. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  57501. }
  57502. _this.position.addToRef(_this._add, _this._target);
  57503. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  57504. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  57505. });
  57506. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  57507. scene.updateTransformMatrix(true);
  57508. });
  57509. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  57510. }
  57511. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  57512. get: function () {
  57513. return this._renderTargetTexture.refreshRate;
  57514. },
  57515. set: function (value) {
  57516. this._renderTargetTexture.refreshRate = value;
  57517. },
  57518. enumerable: true,
  57519. configurable: true
  57520. });
  57521. ReflectionProbe.prototype.getScene = function () {
  57522. return this._scene;
  57523. };
  57524. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  57525. get: function () {
  57526. return this._renderTargetTexture;
  57527. },
  57528. enumerable: true,
  57529. configurable: true
  57530. });
  57531. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  57532. get: function () {
  57533. return this._renderTargetTexture.renderList;
  57534. },
  57535. enumerable: true,
  57536. configurable: true
  57537. });
  57538. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  57539. this._attachedMesh = mesh;
  57540. };
  57541. ReflectionProbe.prototype.dispose = function () {
  57542. var index = this._scene.reflectionProbes.indexOf(this);
  57543. if (index !== -1) {
  57544. // Remove from the scene if found
  57545. this._scene.reflectionProbes.splice(index, 1);
  57546. }
  57547. if (this._renderTargetTexture) {
  57548. this._renderTargetTexture.dispose();
  57549. this._renderTargetTexture = null;
  57550. }
  57551. };
  57552. return ReflectionProbe;
  57553. })();
  57554. BABYLON.ReflectionProbe = ReflectionProbe;
  57555. })(BABYLON || (BABYLON = {}));
  57556. var BABYLON;
  57557. (function (BABYLON) {
  57558. var SolidParticle = (function () {
  57559. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  57560. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  57561. this.position = BABYLON.Vector3.Zero(); // position
  57562. this.rotation = BABYLON.Vector3.Zero(); // rotation
  57563. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  57564. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  57565. this.velocity = BABYLON.Vector3.Zero(); // velocity
  57566. this.alive = true; // alive
  57567. this.isVisible = true; // visibility
  57568. this.idx = particleIndex;
  57569. this._pos = positionIndex;
  57570. this._model = model;
  57571. this.shapeId = shapeId;
  57572. this.idxInShape = idxInShape;
  57573. }
  57574. Object.defineProperty(SolidParticle.prototype, "scale", {
  57575. //legacy support, changed scale to scaling
  57576. get: function () {
  57577. return this.scaling;
  57578. },
  57579. set: function (scale) {
  57580. this.scaling = scale;
  57581. },
  57582. enumerable: true,
  57583. configurable: true
  57584. });
  57585. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57586. //legacy support, changed quaternion to rotationQuaternion
  57587. get: function () {
  57588. return this.rotationQuaternion;
  57589. },
  57590. set: function (q) {
  57591. this.rotationQuaternion = q;
  57592. },
  57593. enumerable: true,
  57594. configurable: true
  57595. });
  57596. return SolidParticle;
  57597. })();
  57598. BABYLON.SolidParticle = SolidParticle;
  57599. var ModelShape = (function () {
  57600. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  57601. this.shapeID = id;
  57602. this._shape = shape;
  57603. this._shapeUV = shapeUV;
  57604. this._positionFunction = posFunction;
  57605. this._vertexFunction = vtxFunction;
  57606. }
  57607. return ModelShape;
  57608. })();
  57609. BABYLON.ModelShape = ModelShape;
  57610. })(BABYLON || (BABYLON = {}));
  57611. var BABYLON;
  57612. (function (BABYLON) {
  57613. /**
  57614. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  57615. */
  57616. var SolidParticleSystem = (function () {
  57617. /**
  57618. * Creates a SPS (Solid Particle System) object.
  57619. * `name` (String) is the SPS name, this will be the underlying mesh name.
  57620. * `scene` (Scene) is the scene in which the SPS is added.
  57621. * `updatable` (default true) : if the SPS must be updatable or immutable.
  57622. * `isPickable` (default false) : if the solid particles must be pickable.
  57623. */
  57624. function SolidParticleSystem(name, scene, options) {
  57625. // public members
  57626. /**
  57627. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  57628. * Example : var p = SPS.particles[i];
  57629. */
  57630. this.particles = new Array();
  57631. /**
  57632. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  57633. */
  57634. this.nbParticles = 0;
  57635. /**
  57636. * If the particles must ever face the camera (default false). Useful for planar particles.
  57637. */
  57638. this.billboard = false;
  57639. /**
  57640. * Recompute normals when adding a shape
  57641. */
  57642. this.recomputeNormals = true;
  57643. /**
  57644. * This a counter ofr your own usage. It's not set by any SPS functions.
  57645. */
  57646. this.counter = 0;
  57647. /**
  57648. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  57649. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  57650. */
  57651. this.vars = {};
  57652. this._positions = new Array();
  57653. this._indices = new Array();
  57654. this._normals = new Array();
  57655. this._colors = new Array();
  57656. this._uvs = new Array();
  57657. this._index = 0; // indices index
  57658. this._updatable = true;
  57659. this._pickable = false;
  57660. this._isVisibilityBoxLocked = false;
  57661. this._alwaysVisible = false;
  57662. this._shapeCounter = 0;
  57663. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  57664. this._color = new BABYLON.Color4(0, 0, 0, 0);
  57665. this._computeParticleColor = true;
  57666. this._computeParticleTexture = true;
  57667. this._computeParticleRotation = true;
  57668. this._computeParticleVertex = false;
  57669. this._computeBoundingBox = false;
  57670. this._cam_axisZ = BABYLON.Vector3.Zero();
  57671. this._cam_axisY = BABYLON.Vector3.Zero();
  57672. this._cam_axisX = BABYLON.Vector3.Zero();
  57673. this._axisX = BABYLON.Axis.X;
  57674. this._axisY = BABYLON.Axis.Y;
  57675. this._axisZ = BABYLON.Axis.Z;
  57676. this._camDir = BABYLON.Vector3.Zero();
  57677. this._rotMatrix = new BABYLON.Matrix();
  57678. this._invertMatrix = new BABYLON.Matrix();
  57679. this._rotated = BABYLON.Vector3.Zero();
  57680. this._quaternion = new BABYLON.Quaternion();
  57681. this._vertex = BABYLON.Vector3.Zero();
  57682. this._normal = BABYLON.Vector3.Zero();
  57683. this._yaw = 0.0;
  57684. this._pitch = 0.0;
  57685. this._roll = 0.0;
  57686. this._halfroll = 0.0;
  57687. this._halfpitch = 0.0;
  57688. this._halfyaw = 0.0;
  57689. this._sinRoll = 0.0;
  57690. this._cosRoll = 0.0;
  57691. this._sinPitch = 0.0;
  57692. this._cosPitch = 0.0;
  57693. this._sinYaw = 0.0;
  57694. this._cosYaw = 0.0;
  57695. this._w = 0.0;
  57696. this._minimum = BABYLON.Tmp.Vector3[0];
  57697. this._maximum = BABYLON.Tmp.Vector3[1];
  57698. this.name = name;
  57699. this._scene = scene;
  57700. this._camera = scene.activeCamera;
  57701. this._pickable = options ? options.isPickable : false;
  57702. if (options && options.updatable) {
  57703. this._updatable = options.updatable;
  57704. }
  57705. else {
  57706. this._updatable = true;
  57707. }
  57708. if (this._pickable) {
  57709. this.pickedParticles = [];
  57710. }
  57711. }
  57712. /**
  57713. * Builds the SPS underlying mesh. Returns a standard Mesh.
  57714. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  57715. */
  57716. SolidParticleSystem.prototype.buildMesh = function () {
  57717. if (this.nbParticles === 0) {
  57718. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  57719. this.addShape(triangle, 1);
  57720. triangle.dispose();
  57721. }
  57722. this._positions32 = new Float32Array(this._positions);
  57723. this._uvs32 = new Float32Array(this._uvs);
  57724. this._colors32 = new Float32Array(this._colors);
  57725. if (this.recomputeNormals) {
  57726. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  57727. }
  57728. this._normals32 = new Float32Array(this._normals);
  57729. this._fixedNormal32 = new Float32Array(this._normals);
  57730. var vertexData = new BABYLON.VertexData();
  57731. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  57732. vertexData.indices = this._indices;
  57733. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  57734. if (this._uvs32) {
  57735. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  57736. ;
  57737. }
  57738. if (this._colors32) {
  57739. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  57740. }
  57741. var mesh = new BABYLON.Mesh(this.name, this._scene);
  57742. vertexData.applyToMesh(mesh, this._updatable);
  57743. this.mesh = mesh;
  57744. this.mesh.isPickable = this._pickable;
  57745. // free memory
  57746. this._positions = null;
  57747. this._normals = null;
  57748. this._uvs = null;
  57749. this._colors = null;
  57750. if (!this._updatable) {
  57751. this.particles.length = 0;
  57752. }
  57753. return mesh;
  57754. };
  57755. /**
  57756. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  57757. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  57758. * Thus the particles generated from `digest()` have their property `position` set yet.
  57759. * `mesh` ( Mesh ) is the mesh to be digested
  57760. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  57761. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  57762. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  57763. */
  57764. SolidParticleSystem.prototype.digest = function (mesh, options) {
  57765. var size = (options && options.facetNb) || 1;
  57766. var number = (options && options.number);
  57767. var delta = (options && options.delta) || 0;
  57768. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57769. var meshInd = mesh.getIndices();
  57770. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57771. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57772. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57773. var f = 0; // facet counter
  57774. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  57775. // compute size from number
  57776. if (number) {
  57777. number = (number > totalFacets) ? totalFacets : number;
  57778. size = Math.round(totalFacets / number);
  57779. delta = 0;
  57780. }
  57781. else {
  57782. size = (size > totalFacets) ? totalFacets : size;
  57783. }
  57784. var facetPos = []; // submesh positions
  57785. var facetInd = []; // submesh indices
  57786. var facetUV = []; // submesh UV
  57787. var facetCol = []; // submesh colors
  57788. var barycenter = BABYLON.Tmp.Vector3[0];
  57789. var rand;
  57790. var sizeO = size;
  57791. while (f < totalFacets) {
  57792. size = sizeO + Math.floor((1 + delta) * Math.random());
  57793. if (f > totalFacets - size) {
  57794. size = totalFacets - f;
  57795. }
  57796. // reset temp arrays
  57797. facetPos.length = 0;
  57798. facetInd.length = 0;
  57799. facetUV.length = 0;
  57800. facetCol.length = 0;
  57801. // iterate over "size" facets
  57802. var fi = 0;
  57803. for (var j = f * 3; j < (f + size) * 3; j++) {
  57804. facetInd.push(fi);
  57805. var i = meshInd[j];
  57806. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  57807. if (meshUV) {
  57808. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  57809. }
  57810. if (meshCol) {
  57811. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  57812. }
  57813. fi++;
  57814. }
  57815. // create a model shape for each single particle
  57816. var idx = this.nbParticles;
  57817. var shape = this._posToShape(facetPos);
  57818. var shapeUV = this._uvsToShapeUV(facetUV);
  57819. // compute the barycenter of the shape
  57820. var v;
  57821. for (v = 0; v < shape.length; v++) {
  57822. barycenter.addInPlace(shape[v]);
  57823. }
  57824. barycenter.scaleInPlace(1 / shape.length);
  57825. // shift the shape from its barycenter to the origin
  57826. for (v = 0; v < shape.length; v++) {
  57827. shape[v].subtractInPlace(barycenter);
  57828. }
  57829. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  57830. // add the particle in the SPS
  57831. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  57832. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  57833. // initialize the particle position
  57834. this.particles[this.nbParticles].position.addInPlace(barycenter);
  57835. this._index += shape.length;
  57836. idx++;
  57837. this.nbParticles++;
  57838. this._shapeCounter++;
  57839. f += size;
  57840. }
  57841. return this;
  57842. };
  57843. //reset copy
  57844. SolidParticleSystem.prototype._resetCopy = function () {
  57845. this._copy.position.x = 0;
  57846. this._copy.position.y = 0;
  57847. this._copy.position.z = 0;
  57848. this._copy.rotation.x = 0;
  57849. this._copy.rotation.y = 0;
  57850. this._copy.rotation.z = 0;
  57851. this._copy.rotationQuaternion = null;
  57852. this._copy.scaling.x = 1;
  57853. this._copy.scaling.y = 1;
  57854. this._copy.scaling.z = 1;
  57855. this._copy.uvs.x = 0;
  57856. this._copy.uvs.y = 0;
  57857. this._copy.uvs.z = 1;
  57858. this._copy.uvs.w = 1;
  57859. this._copy.color = null;
  57860. };
  57861. // _meshBuilder : inserts the shape model in the global SPS mesh
  57862. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  57863. var i;
  57864. var u = 0;
  57865. var c = 0;
  57866. var n = 0;
  57867. this._resetCopy();
  57868. if (options && options.positionFunction) {
  57869. options.positionFunction(this._copy, idx, idxInShape);
  57870. }
  57871. if (this._copy.rotationQuaternion) {
  57872. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57873. }
  57874. else {
  57875. this._yaw = this._copy.rotation.y;
  57876. this._pitch = this._copy.rotation.x;
  57877. this._roll = this._copy.rotation.z;
  57878. this._quaternionRotationYPR();
  57879. }
  57880. this._quaternionToRotationMatrix();
  57881. for (i = 0; i < shape.length; i++) {
  57882. this._vertex.x = shape[i].x;
  57883. this._vertex.y = shape[i].y;
  57884. this._vertex.z = shape[i].z;
  57885. if (options && options.vertexFunction) {
  57886. options.vertexFunction(this._copy, this._vertex, i);
  57887. }
  57888. this._vertex.x *= this._copy.scaling.x;
  57889. this._vertex.y *= this._copy.scaling.y;
  57890. this._vertex.z *= this._copy.scaling.z;
  57891. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57892. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  57893. if (meshUV) {
  57894. 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);
  57895. u += 2;
  57896. }
  57897. if (this._copy.color) {
  57898. this._color = this._copy.color;
  57899. }
  57900. else if (meshCol && meshCol[c] !== undefined) {
  57901. this._color.r = meshCol[c];
  57902. this._color.g = meshCol[c + 1];
  57903. this._color.b = meshCol[c + 2];
  57904. this._color.a = meshCol[c + 3];
  57905. }
  57906. else {
  57907. this._color.r = 1;
  57908. this._color.g = 1;
  57909. this._color.b = 1;
  57910. this._color.a = 1;
  57911. }
  57912. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  57913. c += 4;
  57914. if (!this.recomputeNormals && meshNor) {
  57915. this._normal.x = meshNor[n];
  57916. this._normal.y = meshNor[n + 1];
  57917. this._normal.z = meshNor[n + 2];
  57918. BABYLON.Vector3.TransformCoordinatesToRef(this._normal, this._rotMatrix, this._normal);
  57919. normals.push(this._normal.x, this._normal.y, this._normal.z);
  57920. n += 3;
  57921. }
  57922. }
  57923. for (i = 0; i < meshInd.length; i++) {
  57924. indices.push(p + meshInd[i]);
  57925. }
  57926. if (this._pickable) {
  57927. var nbfaces = meshInd.length / 3;
  57928. for (i = 0; i < nbfaces; i++) {
  57929. this.pickedParticles.push({ idx: idx, faceId: i });
  57930. }
  57931. }
  57932. };
  57933. // returns a shape array from positions array
  57934. SolidParticleSystem.prototype._posToShape = function (positions) {
  57935. var shape = [];
  57936. for (var i = 0; i < positions.length; i += 3) {
  57937. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  57938. }
  57939. return shape;
  57940. };
  57941. // returns a shapeUV array from a Vector4 uvs
  57942. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  57943. var shapeUV = [];
  57944. if (uvs) {
  57945. for (var i = 0; i < uvs.length; i++)
  57946. shapeUV.push(uvs[i]);
  57947. }
  57948. return shapeUV;
  57949. };
  57950. // adds a new particle object in the particles array
  57951. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  57952. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  57953. };
  57954. /**
  57955. * Adds some particles to the SPS from the model shape. Returns the shape id.
  57956. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  57957. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  57958. * `nb` (positive integer) the number of particles to be created from this model
  57959. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  57960. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  57961. */
  57962. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  57963. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57964. var meshInd = mesh.getIndices();
  57965. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57966. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57967. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57968. var shape = this._posToShape(meshPos);
  57969. var shapeUV = this._uvsToShapeUV(meshUV);
  57970. var posfunc = options ? options.positionFunction : null;
  57971. var vtxfunc = options ? options.vertexFunction : null;
  57972. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  57973. // particles
  57974. var idx = this.nbParticles;
  57975. for (var i = 0; i < nb; i++) {
  57976. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  57977. if (this._updatable) {
  57978. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  57979. }
  57980. this._index += shape.length;
  57981. idx++;
  57982. }
  57983. this.nbParticles += nb;
  57984. this._shapeCounter++;
  57985. return this._shapeCounter - 1;
  57986. };
  57987. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  57988. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  57989. this._resetCopy();
  57990. if (particle._model._positionFunction) {
  57991. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  57992. }
  57993. if (this._copy.rotationQuaternion) {
  57994. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57995. }
  57996. else {
  57997. this._yaw = this._copy.rotation.y;
  57998. this._pitch = this._copy.rotation.x;
  57999. this._roll = this._copy.rotation.z;
  58000. this._quaternionRotationYPR();
  58001. }
  58002. this._quaternionToRotationMatrix();
  58003. this._shape = particle._model._shape;
  58004. for (var pt = 0; pt < this._shape.length; pt++) {
  58005. this._vertex.x = this._shape[pt].x;
  58006. this._vertex.y = this._shape[pt].y;
  58007. this._vertex.z = this._shape[pt].z;
  58008. if (particle._model._vertexFunction) {
  58009. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58010. }
  58011. this._vertex.x *= this._copy.scaling.x;
  58012. this._vertex.y *= this._copy.scaling.y;
  58013. this._vertex.z *= this._copy.scaling.z;
  58014. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58015. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58016. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58017. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58018. }
  58019. particle.position.x = 0;
  58020. particle.position.y = 0;
  58021. particle.position.z = 0;
  58022. particle.rotation.x = 0;
  58023. particle.rotation.y = 0;
  58024. particle.rotation.z = 0;
  58025. particle.rotationQuaternion = null;
  58026. particle.scaling.x = 1;
  58027. particle.scaling.y = 1;
  58028. particle.scaling.z = 1;
  58029. };
  58030. /**
  58031. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58032. */
  58033. SolidParticleSystem.prototype.rebuildMesh = function () {
  58034. for (var p = 0; p < this.particles.length; p++) {
  58035. this._rebuildParticle(this.particles[p]);
  58036. }
  58037. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58038. };
  58039. /**
  58040. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58041. * This method calls `updateParticle()` for each particle of the SPS.
  58042. * For an animated SPS, it is usually called within the render loop.
  58043. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58044. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58045. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58046. */
  58047. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58048. if (start === void 0) { start = 0; }
  58049. if (end === void 0) { end = this.nbParticles - 1; }
  58050. if (update === void 0) { update = true; }
  58051. if (!this._updatable) {
  58052. return;
  58053. }
  58054. // custom beforeUpdate
  58055. this.beforeUpdateParticles(start, end, update);
  58056. this._cam_axisX.x = 1.0;
  58057. this._cam_axisX.y = 0.0;
  58058. this._cam_axisX.z = 0.0;
  58059. this._cam_axisY.x = 0.0;
  58060. this._cam_axisY.y = 1.0;
  58061. this._cam_axisY.z = 0.0;
  58062. this._cam_axisZ.x = 0.0;
  58063. this._cam_axisZ.y = 0.0;
  58064. this._cam_axisZ.z = 1.0;
  58065. // if the particles will always face the camera
  58066. if (this.billboard) {
  58067. // compute the camera position and un-rotate it by the current mesh rotation
  58068. this._yaw = this.mesh.rotation.y;
  58069. this._pitch = this.mesh.rotation.x;
  58070. this._roll = this.mesh.rotation.z;
  58071. this._quaternionRotationYPR();
  58072. this._quaternionToRotationMatrix();
  58073. this._rotMatrix.invertToRef(this._invertMatrix);
  58074. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  58075. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58076. this._cam_axisZ.normalize();
  58077. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  58078. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  58079. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58080. this._cam_axisY.normalize();
  58081. this._cam_axisX.normalize();
  58082. }
  58083. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58084. var idx = 0;
  58085. var index = 0;
  58086. var colidx = 0;
  58087. var colorIndex = 0;
  58088. var uvidx = 0;
  58089. var uvIndex = 0;
  58090. var pt = 0;
  58091. if (this._computeBoundingBox) {
  58092. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58093. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58094. }
  58095. // particle loop
  58096. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  58097. for (var p = start; p <= end; p++) {
  58098. this._particle = this.particles[p];
  58099. this._shape = this._particle._model._shape;
  58100. this._shapeUV = this._particle._model._shapeUV;
  58101. // call to custom user function to update the particle properties
  58102. this.updateParticle(this._particle);
  58103. if (this._particle.isVisible) {
  58104. // particle rotation matrix
  58105. if (this.billboard) {
  58106. this._particle.rotation.x = 0.0;
  58107. this._particle.rotation.y = 0.0;
  58108. }
  58109. if (this._computeParticleRotation || this.billboard) {
  58110. if (this._particle.rotationQuaternion) {
  58111. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58112. }
  58113. else {
  58114. this._yaw = this._particle.rotation.y;
  58115. this._pitch = this._particle.rotation.x;
  58116. this._roll = this._particle.rotation.z;
  58117. this._quaternionRotationYPR();
  58118. }
  58119. this._quaternionToRotationMatrix();
  58120. }
  58121. // particle vertex loop
  58122. for (pt = 0; pt < this._shape.length; pt++) {
  58123. idx = index + pt * 3;
  58124. colidx = colorIndex + pt * 4;
  58125. uvidx = uvIndex + pt * 2;
  58126. this._vertex.x = this._shape[pt].x;
  58127. this._vertex.y = this._shape[pt].y;
  58128. this._vertex.z = this._shape[pt].z;
  58129. if (this._computeParticleVertex) {
  58130. this.updateParticleVertex(this._particle, this._vertex, pt);
  58131. }
  58132. // positions
  58133. this._vertex.x *= this._particle.scaling.x;
  58134. this._vertex.y *= this._particle.scaling.y;
  58135. this._vertex.z *= this._particle.scaling.z;
  58136. 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];
  58137. 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;
  58138. 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;
  58139. 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;
  58140. 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;
  58141. 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;
  58142. 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;
  58143. if (this._computeBoundingBox) {
  58144. if (this._positions32[idx] < this._minimum.x) {
  58145. this._minimum.x = this._positions32[idx];
  58146. }
  58147. if (this._positions32[idx] > this._maximum.x) {
  58148. this._maximum.x = this._positions32[idx];
  58149. }
  58150. if (this._positions32[idx + 1] < this._minimum.y) {
  58151. this._minimum.y = this._positions32[idx + 1];
  58152. }
  58153. if (this._positions32[idx + 1] > this._maximum.y) {
  58154. this._maximum.y = this._positions32[idx + 1];
  58155. }
  58156. if (this._positions32[idx + 2] < this._minimum.z) {
  58157. this._minimum.z = this._positions32[idx + 2];
  58158. }
  58159. if (this._positions32[idx + 2] > this._maximum.z) {
  58160. this._maximum.z = this._positions32[idx + 2];
  58161. }
  58162. }
  58163. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  58164. if (!this._computeParticleVertex) {
  58165. this._normal.x = this._fixedNormal32[idx];
  58166. this._normal.y = this._fixedNormal32[idx + 1];
  58167. this._normal.z = this._fixedNormal32[idx + 2];
  58168. 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];
  58169. 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;
  58170. 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;
  58171. 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;
  58172. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58173. 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;
  58174. 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;
  58175. }
  58176. if (this._computeParticleColor) {
  58177. this._colors32[colidx] = this._particle.color.r;
  58178. this._colors32[colidx + 1] = this._particle.color.g;
  58179. this._colors32[colidx + 2] = this._particle.color.b;
  58180. this._colors32[colidx + 3] = this._particle.color.a;
  58181. }
  58182. if (this._computeParticleTexture) {
  58183. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58184. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58185. }
  58186. }
  58187. }
  58188. else {
  58189. for (pt = 0; pt < this._shape.length; pt++) {
  58190. idx = index + pt * 3;
  58191. colidx = colorIndex + pt * 4;
  58192. uvidx = uvIndex + pt * 2;
  58193. this._positions32[idx] = this._camera.position.x;
  58194. this._positions32[idx + 1] = this._camera.position.y;
  58195. this._positions32[idx + 2] = this._camera.position.z;
  58196. this._normals32[idx] = 0.0;
  58197. this._normals32[idx + 1] = 0.0;
  58198. this._normals32[idx + 2] = 0.0;
  58199. if (this._computeParticleColor) {
  58200. this._colors32[colidx] = this._particle.color.r;
  58201. this._colors32[colidx + 1] = this._particle.color.g;
  58202. this._colors32[colidx + 2] = this._particle.color.b;
  58203. this._colors32[colidx + 3] = this._particle.color.a;
  58204. }
  58205. if (this._computeParticleTexture) {
  58206. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58207. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58208. }
  58209. }
  58210. }
  58211. // increment indexes for the next particle
  58212. index = idx + 3;
  58213. colorIndex = colidx + 4;
  58214. uvIndex = uvidx + 2;
  58215. }
  58216. // if the VBO must be updated
  58217. if (update) {
  58218. if (this._computeParticleColor) {
  58219. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58220. }
  58221. if (this._computeParticleTexture) {
  58222. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58223. }
  58224. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58225. if (!this.mesh.areNormalsFrozen) {
  58226. if (this._computeParticleVertex) {
  58227. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58228. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  58229. for (var i = 0; i < this._normals32.length; i++) {
  58230. this._fixedNormal32[i] = this._normals32[i];
  58231. }
  58232. }
  58233. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58234. }
  58235. }
  58236. if (this._computeBoundingBox) {
  58237. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58238. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58239. }
  58240. this.afterUpdateParticles(start, end, update);
  58241. };
  58242. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58243. this._halfroll = this._roll * 0.5;
  58244. this._halfpitch = this._pitch * 0.5;
  58245. this._halfyaw = this._yaw * 0.5;
  58246. this._sinRoll = Math.sin(this._halfroll);
  58247. this._cosRoll = Math.cos(this._halfroll);
  58248. this._sinPitch = Math.sin(this._halfpitch);
  58249. this._cosPitch = Math.cos(this._halfpitch);
  58250. this._sinYaw = Math.sin(this._halfyaw);
  58251. this._cosYaw = Math.cos(this._halfyaw);
  58252. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  58253. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  58254. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  58255. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  58256. };
  58257. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58258. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58259. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58260. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58261. this._rotMatrix.m[3] = 0;
  58262. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58263. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58264. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58265. this._rotMatrix.m[7] = 0;
  58266. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58267. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58268. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58269. this._rotMatrix.m[11] = 0;
  58270. this._rotMatrix.m[12] = 0;
  58271. this._rotMatrix.m[13] = 0;
  58272. this._rotMatrix.m[14] = 0;
  58273. this._rotMatrix.m[15] = 1.0;
  58274. };
  58275. /**
  58276. * Disposes the SPS
  58277. */
  58278. SolidParticleSystem.prototype.dispose = function () {
  58279. this.mesh.dispose();
  58280. this.vars = null;
  58281. // drop references to internal big arrays for the GC
  58282. this._positions = null;
  58283. this._indices = null;
  58284. this._normals = null;
  58285. this._uvs = null;
  58286. this._colors = null;
  58287. this._positions32 = null;
  58288. this._normals32 = null;
  58289. this._fixedNormal32 = null;
  58290. this._uvs32 = null;
  58291. this._colors32 = null;
  58292. this.pickedParticles = null;
  58293. };
  58294. /**
  58295. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58296. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58297. */
  58298. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58299. if (!this._isVisibilityBoxLocked) {
  58300. this.mesh.refreshBoundingInfo();
  58301. }
  58302. };
  58303. /**
  58304. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58305. * @param size the size (float) of the visibility box
  58306. * note : this doesn't lock the SPS mesh bounding box.
  58307. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58308. */
  58309. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58310. var vis = size / 2;
  58311. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58312. };
  58313. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  58314. // getter and setter
  58315. get: function () {
  58316. return this._alwaysVisible;
  58317. },
  58318. /**
  58319. * Sets the SPS as always visible or not
  58320. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58321. */
  58322. set: function (val) {
  58323. this._alwaysVisible = val;
  58324. this.mesh.alwaysSelectAsActiveMesh = val;
  58325. },
  58326. enumerable: true,
  58327. configurable: true
  58328. });
  58329. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  58330. get: function () {
  58331. return this._isVisibilityBoxLocked;
  58332. },
  58333. /**
  58334. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58335. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58336. */
  58337. set: function (val) {
  58338. this._isVisibilityBoxLocked = val;
  58339. this.mesh.getBoundingInfo().isLocked = val;
  58340. },
  58341. enumerable: true,
  58342. configurable: true
  58343. });
  58344. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  58345. // getters
  58346. get: function () {
  58347. return this._computeParticleRotation;
  58348. },
  58349. // Optimizer setters
  58350. /**
  58351. * Tells to `setParticles()` to compute the particle rotations or not.
  58352. * Default value : true. The SPS is faster when it's set to false.
  58353. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58354. */
  58355. set: function (val) {
  58356. this._computeParticleRotation = val;
  58357. },
  58358. enumerable: true,
  58359. configurable: true
  58360. });
  58361. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  58362. get: function () {
  58363. return this._computeParticleColor;
  58364. },
  58365. /**
  58366. * Tells to `setParticles()` to compute the particle colors or not.
  58367. * Default value : true. The SPS is faster when it's set to false.
  58368. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58369. */
  58370. set: function (val) {
  58371. this._computeParticleColor = val;
  58372. },
  58373. enumerable: true,
  58374. configurable: true
  58375. });
  58376. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  58377. get: function () {
  58378. return this._computeParticleTexture;
  58379. },
  58380. /**
  58381. * Tells to `setParticles()` to compute the particle textures or not.
  58382. * Default value : true. The SPS is faster when it's set to false.
  58383. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  58384. */
  58385. set: function (val) {
  58386. this._computeParticleTexture = val;
  58387. },
  58388. enumerable: true,
  58389. configurable: true
  58390. });
  58391. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  58392. get: function () {
  58393. return this._computeParticleVertex;
  58394. },
  58395. /**
  58396. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  58397. * Default value : false. The SPS is faster when it's set to false.
  58398. * Note : the particle custom vertex positions aren't stored values.
  58399. */
  58400. set: function (val) {
  58401. this._computeParticleVertex = val;
  58402. },
  58403. enumerable: true,
  58404. configurable: true
  58405. });
  58406. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  58407. get: function () {
  58408. return this._computeBoundingBox;
  58409. },
  58410. /**
  58411. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  58412. */
  58413. set: function (val) {
  58414. this._computeBoundingBox = val;
  58415. },
  58416. enumerable: true,
  58417. configurable: true
  58418. });
  58419. // =======================================================================
  58420. // Particle behavior logic
  58421. // these following methods may be overwritten by the user to fit his needs
  58422. /**
  58423. * This function does nothing. It may be overwritten to set all the particle first values.
  58424. * The SPS doesn't call this function, you may have to call it by your own.
  58425. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58426. */
  58427. SolidParticleSystem.prototype.initParticles = function () {
  58428. };
  58429. /**
  58430. * This function does nothing. It may be overwritten to recycle a particle.
  58431. * The SPS doesn't call this function, you may have to call it by your own.
  58432. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58433. */
  58434. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  58435. return particle;
  58436. };
  58437. /**
  58438. * Updates a particle : this function should be overwritten by the user.
  58439. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  58440. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58441. * ex : just set a particle position or velocity and recycle conditions
  58442. */
  58443. SolidParticleSystem.prototype.updateParticle = function (particle) {
  58444. return particle;
  58445. };
  58446. /**
  58447. * Updates a vertex of a particle : it can be overwritten by the user.
  58448. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  58449. * @param particle the current particle
  58450. * @param vertex the current index of the current particle
  58451. * @param pt the index of the current vertex in the particle shape
  58452. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  58453. * ex : just set a vertex particle position
  58454. */
  58455. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  58456. return vertex;
  58457. };
  58458. /**
  58459. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  58460. * This does nothing and may be overwritten by the user.
  58461. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58462. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58463. * @param update the boolean update value actually passed to setParticles()
  58464. */
  58465. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  58466. };
  58467. /**
  58468. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  58469. * This will be passed three parameters.
  58470. * This does nothing and may be overwritten by the user.
  58471. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58472. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58473. * @param update the boolean update value actually passed to setParticles()
  58474. */
  58475. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  58476. };
  58477. return SolidParticleSystem;
  58478. })();
  58479. BABYLON.SolidParticleSystem = SolidParticleSystem;
  58480. })(BABYLON || (BABYLON = {}));
  58481. var BABYLON;
  58482. (function (BABYLON) {
  58483. var Internals;
  58484. (function (Internals) {
  58485. var FileFaceOrientation = (function () {
  58486. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  58487. this.name = name;
  58488. this.worldAxisForNormal = worldAxisForNormal;
  58489. this.worldAxisForFileX = worldAxisForFileX;
  58490. this.worldAxisForFileY = worldAxisForFileY;
  58491. }
  58492. return FileFaceOrientation;
  58493. })();
  58494. ;
  58495. /**
  58496. * Helper class dealing with the extraction of spherical polynomial dataArray
  58497. * from a cube map.
  58498. */
  58499. var CubeMapToSphericalPolynomialTools = (function () {
  58500. function CubeMapToSphericalPolynomialTools() {
  58501. }
  58502. /**
  58503. * Converts a cubemap to the according Spherical Polynomial data.
  58504. * This extracts the first 3 orders only as they are the only one used in the lighting.
  58505. *
  58506. * @param cubeInfo The Cube map to extract the information from.
  58507. * @return The Spherical Polynomial data.
  58508. */
  58509. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  58510. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  58511. var totalSolidAngle = 0.0;
  58512. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  58513. var du = 2.0 / cubeInfo.size;
  58514. var dv = du;
  58515. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  58516. var minUV = du * 0.5 - 1.0;
  58517. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  58518. var fileFace = this.FileFaces[faceIndex];
  58519. var dataArray = cubeInfo[fileFace.name];
  58520. var v = minUV;
  58521. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  58522. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  58523. // Because SP is still linear, so summation is fine in that basis.
  58524. for (var y = 0; y < cubeInfo.size; y++) {
  58525. var u = minUV;
  58526. for (var x = 0; x < cubeInfo.size; x++) {
  58527. // World direction (not normalised)
  58528. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  58529. worldDirection.normalize();
  58530. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  58531. if (1) {
  58532. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  58533. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  58534. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  58535. var color = new BABYLON.Color3(r, g, b);
  58536. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  58537. }
  58538. else {
  58539. if (faceIndex == 0) {
  58540. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  58541. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  58542. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  58543. }
  58544. else if (faceIndex == 1) {
  58545. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  58546. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  58547. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  58548. }
  58549. else if (faceIndex == 2) {
  58550. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  58551. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  58552. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  58553. }
  58554. else if (faceIndex == 3) {
  58555. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  58556. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  58557. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  58558. }
  58559. else if (faceIndex == 4) {
  58560. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  58561. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  58562. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  58563. }
  58564. else if (faceIndex == 5) {
  58565. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  58566. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  58567. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  58568. }
  58569. 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]);
  58570. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  58571. }
  58572. totalSolidAngle += deltaSolidAngle;
  58573. u += du;
  58574. }
  58575. v += dv;
  58576. }
  58577. }
  58578. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  58579. var correction = correctSolidAngle / totalSolidAngle;
  58580. sphericalHarmonics.scale(correction);
  58581. // Additionally scale by pi -- audit needed
  58582. sphericalHarmonics.scale(1.0 / Math.PI);
  58583. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  58584. };
  58585. CubeMapToSphericalPolynomialTools.FileFaces = [
  58586. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  58587. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  58588. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  58589. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  58590. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  58591. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  58592. ];
  58593. return CubeMapToSphericalPolynomialTools;
  58594. })();
  58595. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  58596. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58597. })(BABYLON || (BABYLON = {}));
  58598. var BABYLON;
  58599. (function (BABYLON) {
  58600. var Internals;
  58601. (function (Internals) {
  58602. /**
  58603. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  58604. */
  58605. var PanoramaToCubeMapTools = (function () {
  58606. function PanoramaToCubeMapTools() {
  58607. }
  58608. /**
  58609. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  58610. *
  58611. * @param float32Array The source data.
  58612. * @param inputWidth The width of the input panorama.
  58613. * @param inputhHeight The height of the input panorama.
  58614. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  58615. * @return The cubemap data
  58616. */
  58617. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  58618. if (!float32Array) {
  58619. throw "ConvertPanoramaToCubemap: input cannot be null";
  58620. }
  58621. if (float32Array.length != inputWidth * inputHeight * 3) {
  58622. throw "ConvertPanoramaToCubemap: input size is wrong";
  58623. }
  58624. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  58625. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  58626. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  58627. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  58628. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  58629. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  58630. return {
  58631. front: textureFront,
  58632. back: textureBack,
  58633. left: textureLeft,
  58634. right: textureRight,
  58635. up: textureUp,
  58636. down: textureDown,
  58637. size: size
  58638. };
  58639. };
  58640. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  58641. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  58642. var textureArray = new Float32Array(buffer);
  58643. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  58644. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  58645. var dy = 1 / texSize;
  58646. var fy = 0;
  58647. for (var y = 0; y < texSize; y++) {
  58648. var xv1 = faceData[0];
  58649. var xv2 = faceData[2];
  58650. for (var x = 0; x < texSize; x++) {
  58651. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  58652. v.normalize();
  58653. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  58654. // 3 channels per pixels
  58655. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  58656. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  58657. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  58658. xv1 = xv1.add(rotDX1);
  58659. xv2 = xv2.add(rotDX2);
  58660. }
  58661. fy += dy;
  58662. }
  58663. return textureArray;
  58664. };
  58665. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  58666. var theta = Math.atan2(vDir.z, vDir.x);
  58667. var phi = Math.acos(vDir.y);
  58668. while (theta < -Math.PI)
  58669. theta += 2 * Math.PI;
  58670. while (theta > Math.PI)
  58671. theta -= 2 * Math.PI;
  58672. var dx = theta / Math.PI;
  58673. var dy = phi / Math.PI;
  58674. // recenter.
  58675. dx = dx * 0.5 + 0.5;
  58676. var px = Math.round(dx * inputWidth);
  58677. if (px < 0)
  58678. px = 0;
  58679. else if (px >= inputWidth)
  58680. px = inputWidth - 1;
  58681. var py = Math.round(dy * inputHeight);
  58682. if (py < 0)
  58683. py = 0;
  58684. else if (py >= inputHeight)
  58685. py = inputHeight - 1;
  58686. var inputY = (inputHeight - py - 1);
  58687. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  58688. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  58689. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  58690. return {
  58691. r: r,
  58692. g: g,
  58693. b: b
  58694. };
  58695. };
  58696. PanoramaToCubeMapTools.FACE_FRONT = [
  58697. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  58698. new BABYLON.Vector3(1.0, -1.0, -1.0),
  58699. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  58700. new BABYLON.Vector3(1.0, 1.0, -1.0)
  58701. ];
  58702. PanoramaToCubeMapTools.FACE_BACK = [
  58703. new BABYLON.Vector3(1.0, -1.0, 1.0),
  58704. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  58705. new BABYLON.Vector3(1.0, 1.0, 1.0),
  58706. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  58707. ];
  58708. PanoramaToCubeMapTools.FACE_RIGHT = [
  58709. new BABYLON.Vector3(1.0, -1.0, -1.0),
  58710. new BABYLON.Vector3(1.0, -1.0, 1.0),
  58711. new BABYLON.Vector3(1.0, 1.0, -1.0),
  58712. new BABYLON.Vector3(1.0, 1.0, 1.0)
  58713. ];
  58714. PanoramaToCubeMapTools.FACE_LEFT = [
  58715. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  58716. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  58717. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  58718. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  58719. ];
  58720. PanoramaToCubeMapTools.FACE_DOWN = [
  58721. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  58722. new BABYLON.Vector3(1.0, 1.0, -1.0),
  58723. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  58724. new BABYLON.Vector3(1.0, 1.0, 1.0)
  58725. ];
  58726. PanoramaToCubeMapTools.FACE_UP = [
  58727. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  58728. new BABYLON.Vector3(1.0, -1.0, 1.0),
  58729. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  58730. new BABYLON.Vector3(1.0, -1.0, -1.0)
  58731. ];
  58732. return PanoramaToCubeMapTools;
  58733. })();
  58734. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  58735. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58736. })(BABYLON || (BABYLON = {}));
  58737. var BABYLON;
  58738. (function (BABYLON) {
  58739. var Internals;
  58740. (function (Internals) {
  58741. ;
  58742. /**
  58743. * This groups tools to convert HDR texture to native colors array.
  58744. */
  58745. var HDRTools = (function () {
  58746. function HDRTools() {
  58747. }
  58748. HDRTools.Ldexp = function (mantissa, exponent) {
  58749. if (exponent > 1023) {
  58750. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  58751. }
  58752. if (exponent < -1074) {
  58753. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  58754. }
  58755. return mantissa * Math.pow(2, exponent);
  58756. };
  58757. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  58758. if (exponent > 0) {
  58759. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  58760. float32array[index + 0] = red * exponent;
  58761. float32array[index + 1] = green * exponent;
  58762. float32array[index + 2] = blue * exponent;
  58763. }
  58764. else {
  58765. float32array[index + 0] = 0;
  58766. float32array[index + 1] = 0;
  58767. float32array[index + 2] = 0;
  58768. }
  58769. };
  58770. HDRTools.readStringLine = function (uint8array, startIndex) {
  58771. var line = "";
  58772. var character = "";
  58773. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  58774. character = String.fromCharCode(uint8array[i]);
  58775. if (character == "\n") {
  58776. break;
  58777. }
  58778. line += character;
  58779. }
  58780. return line;
  58781. };
  58782. /**
  58783. * Reads header information from an RGBE texture stored in a native array.
  58784. * More information on this format are available here:
  58785. * https://en.wikipedia.org/wiki/RGBE_image_format
  58786. *
  58787. * @param uint8array The binary file stored in native array.
  58788. * @return The header information.
  58789. */
  58790. HDRTools.RGBE_ReadHeader = function (uint8array) {
  58791. var height = 0;
  58792. var width = 0;
  58793. var line = this.readStringLine(uint8array, 0);
  58794. if (line[0] != '#' || line[1] != '?') {
  58795. throw "Bad HDR Format.";
  58796. }
  58797. var endOfHeader = false;
  58798. var findFormat = false;
  58799. var lineIndex = 0;
  58800. do {
  58801. lineIndex += (line.length + 1);
  58802. line = this.readStringLine(uint8array, lineIndex);
  58803. if (line == "FORMAT=32-bit_rle_rgbe") {
  58804. findFormat = true;
  58805. }
  58806. else if (line.length == 0) {
  58807. endOfHeader = true;
  58808. }
  58809. } while (!endOfHeader);
  58810. if (!findFormat) {
  58811. throw "HDR Bad header format, unsupported FORMAT";
  58812. }
  58813. lineIndex += (line.length + 1);
  58814. line = this.readStringLine(uint8array, lineIndex);
  58815. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  58816. var match = sizeRegexp.exec(line);
  58817. // TODO. Support +Y and -X if needed.
  58818. if (match.length < 3) {
  58819. throw "HDR Bad header format, no size";
  58820. }
  58821. width = parseInt(match[2]);
  58822. height = parseInt(match[1]);
  58823. if (width < 8 || width > 0x7fff) {
  58824. throw "HDR Bad header format, unsupported size";
  58825. }
  58826. lineIndex += (line.length + 1);
  58827. return {
  58828. height: height,
  58829. width: width,
  58830. dataPosition: lineIndex
  58831. };
  58832. };
  58833. /**
  58834. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  58835. * This RGBE texture needs to store the information as a panorama.
  58836. *
  58837. * More information on this format are available here:
  58838. * https://en.wikipedia.org/wiki/RGBE_image_format
  58839. *
  58840. * @param buffer The binary file stored in an array buffer.
  58841. * @param size The expected size of the extracted cubemap.
  58842. * @return The Cube Map information.
  58843. */
  58844. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  58845. var uint8array = new Uint8Array(buffer);
  58846. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  58847. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  58848. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  58849. return cubeMapData;
  58850. };
  58851. /**
  58852. * Returns the pixels data extracted from an RGBE texture.
  58853. * This pixels will be stored left to right up to down in the R G B order in one array.
  58854. *
  58855. * More information on this format are available here:
  58856. * https://en.wikipedia.org/wiki/RGBE_image_format
  58857. *
  58858. * @param uint8array The binary file stored in an array buffer.
  58859. * @param hdrInfo The header information of the file.
  58860. * @return The pixels data in RGB right to left up to down order.
  58861. */
  58862. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  58863. // Keep for multi format supports.
  58864. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  58865. };
  58866. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  58867. var num_scanlines = hdrInfo.height;
  58868. var scanline_width = hdrInfo.width;
  58869. var a, b, c, d, count;
  58870. var dataIndex = hdrInfo.dataPosition;
  58871. var index = 0, endIndex = 0, i = 0;
  58872. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  58873. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  58874. // 3 channels of 4 bytes per pixel in float.
  58875. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  58876. var resultArray = new Float32Array(resultBuffer);
  58877. // read in each successive scanline
  58878. while (num_scanlines > 0) {
  58879. a = uint8array[dataIndex++];
  58880. b = uint8array[dataIndex++];
  58881. c = uint8array[dataIndex++];
  58882. d = uint8array[dataIndex++];
  58883. if (a != 2 || b != 2 || (c & 0x80)) {
  58884. // this file is not run length encoded
  58885. throw "HDR Bad header format, not RLE";
  58886. }
  58887. if (((c << 8) | d) != scanline_width) {
  58888. throw "HDR Bad header format, wrong scan line width";
  58889. }
  58890. index = 0;
  58891. // read each of the four channels for the scanline into the buffer
  58892. for (i = 0; i < 4; i++) {
  58893. endIndex = (i + 1) * scanline_width;
  58894. while (index < endIndex) {
  58895. a = uint8array[dataIndex++];
  58896. b = uint8array[dataIndex++];
  58897. if (a > 128) {
  58898. // a run of the same value
  58899. count = a - 128;
  58900. if ((count == 0) || (count > endIndex - index)) {
  58901. throw "HDR Bad Format, bad scanline data (run)";
  58902. }
  58903. while (count-- > 0) {
  58904. scanLineArray[index++] = b;
  58905. }
  58906. }
  58907. else {
  58908. // a non-run
  58909. count = a;
  58910. if ((count == 0) || (count > endIndex - index)) {
  58911. throw "HDR Bad Format, bad scanline data (non-run)";
  58912. }
  58913. scanLineArray[index++] = b;
  58914. if (--count > 0) {
  58915. for (var j = 0; j < count; j++) {
  58916. scanLineArray[index++] = uint8array[dataIndex++];
  58917. }
  58918. }
  58919. }
  58920. }
  58921. }
  58922. // now convert data from buffer into floats
  58923. for (i = 0; i < scanline_width; i++) {
  58924. a = scanLineArray[i];
  58925. b = scanLineArray[i + scanline_width];
  58926. c = scanLineArray[i + 2 * scanline_width];
  58927. d = scanLineArray[i + 3 * scanline_width];
  58928. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  58929. }
  58930. num_scanlines--;
  58931. }
  58932. return resultArray;
  58933. };
  58934. return HDRTools;
  58935. })();
  58936. Internals.HDRTools = HDRTools;
  58937. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58938. })(BABYLON || (BABYLON = {}));
  58939. //_______________________________________________________________
  58940. // Extracted from CubeMapGen:
  58941. // https://code.google.com/archive/p/cubemapgen/
  58942. //
  58943. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  58944. //_______________________________________________________________
  58945. var BABYLON;
  58946. (function (BABYLON) {
  58947. var Internals;
  58948. (function (Internals) {
  58949. /**
  58950. * The bounding box information used during the conversion process.
  58951. */
  58952. var CMGBoundinBox = (function () {
  58953. function CMGBoundinBox() {
  58954. this.min = new BABYLON.Vector3(0, 0, 0);
  58955. this.max = new BABYLON.Vector3(0, 0, 0);
  58956. this.clear();
  58957. }
  58958. CMGBoundinBox.prototype.clear = function () {
  58959. this.min.x = CMGBoundinBox.MAX;
  58960. this.min.y = CMGBoundinBox.MAX;
  58961. this.min.z = CMGBoundinBox.MAX;
  58962. this.max.x = CMGBoundinBox.MIN;
  58963. this.max.y = CMGBoundinBox.MIN;
  58964. this.max.z = CMGBoundinBox.MIN;
  58965. };
  58966. CMGBoundinBox.prototype.augment = function (x, y, z) {
  58967. this.min.x = Math.min(this.min.x, x);
  58968. this.min.y = Math.min(this.min.y, y);
  58969. this.min.z = Math.min(this.min.z, z);
  58970. this.max.x = Math.max(this.max.x, x);
  58971. this.max.y = Math.max(this.max.y, y);
  58972. this.max.z = Math.max(this.max.z, z);
  58973. };
  58974. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  58975. this.min.x = Math.max(this.min.x, x);
  58976. this.min.y = Math.max(this.min.y, y);
  58977. this.min.z = Math.max(this.min.z, z);
  58978. };
  58979. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  58980. this.max.x = Math.min(this.max.x, x);
  58981. this.max.y = Math.min(this.max.y, y);
  58982. this.max.z = Math.min(this.max.z, z);
  58983. };
  58984. CMGBoundinBox.prototype.empty = function () {
  58985. if ((this.min.x > this.max.y) ||
  58986. (this.min.y > this.max.y) ||
  58987. (this.min.z > this.max.y)) {
  58988. return true;
  58989. }
  58990. else {
  58991. return false;
  58992. }
  58993. };
  58994. CMGBoundinBox.MAX = Number.MAX_VALUE;
  58995. CMGBoundinBox.MIN = Number.MIN_VALUE;
  58996. return CMGBoundinBox;
  58997. })();
  58998. /**
  58999. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  59000. * required by the glossinees of a material.
  59001. *
  59002. * This only supports the cosine drop power as well as Warp fixup generation method.
  59003. *
  59004. * This is using the process from CubeMapGen described here:
  59005. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  59006. */
  59007. var PMREMGenerator = (function () {
  59008. /**
  59009. * Constructor of the generator.
  59010. *
  59011. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  59012. * @param inputSize The size of the cubemap faces
  59013. * @param outputSize The size of the output cubemap faces
  59014. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  59015. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  59016. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  59017. * @param specularPower The max specular level of the desired cubemap
  59018. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  59019. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  59020. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  59021. */
  59022. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  59023. this.input = input;
  59024. this.inputSize = inputSize;
  59025. this.outputSize = outputSize;
  59026. this.maxNumMipLevels = maxNumMipLevels;
  59027. this.numChannels = numChannels;
  59028. this.isFloat = isFloat;
  59029. this.specularPower = specularPower;
  59030. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  59031. this.excludeBase = excludeBase;
  59032. this.fixup = fixup;
  59033. this._outputSurface = [];
  59034. this._numMipLevels = 0;
  59035. }
  59036. /**
  59037. * Launches the filter process and return the result.
  59038. *
  59039. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  59040. */
  59041. PMREMGenerator.prototype.filterCubeMap = function () {
  59042. // Init cubemap processor
  59043. this.init();
  59044. // Filters the cubemap
  59045. this.filterCubeMapMipChain();
  59046. // Returns the filtered mips.
  59047. return this._outputSurface;
  59048. };
  59049. PMREMGenerator.prototype.init = function () {
  59050. var i;
  59051. var j;
  59052. var mipLevelSize;
  59053. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  59054. if (this.maxNumMipLevels == 0) {
  59055. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  59056. }
  59057. //first miplevel size
  59058. mipLevelSize = this.outputSize;
  59059. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  59060. for (j = 0; j < this.maxNumMipLevels; j++) {
  59061. this._outputSurface.length++;
  59062. this._outputSurface[j] = [];
  59063. //Iterate over faces for output images
  59064. for (i = 0; i < 6; i++) {
  59065. this._outputSurface[j].length++;
  59066. // Initializes a new array for the output.
  59067. if (this.isFloat) {
  59068. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  59069. }
  59070. else {
  59071. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  59072. }
  59073. }
  59074. //next mip level is half size
  59075. mipLevelSize >>= 1;
  59076. this._numMipLevels++;
  59077. //terminate if mip chain becomes too small
  59078. if (mipLevelSize == 0) {
  59079. this.maxNumMipLevels = j;
  59080. return;
  59081. }
  59082. }
  59083. };
  59084. //--------------------------------------------------------------------------------------
  59085. //Cube map filtering and mip chain generation.
  59086. // the cube map filtereing is specified using a number of parameters:
  59087. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  59088. // indicates the region of the hemisphere to filter over for each tap.
  59089. //
  59090. // Note that the top mip level is also a filtered version of the original input images
  59091. // as well in order to create mip chains for diffuse environment illumination.
  59092. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  59093. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  59094. //
  59095. // Then the mip angle used to genreate the next level of the mip chain from the first level
  59096. // is a_InitialMipAngle
  59097. //
  59098. // The angle for the subsequent levels of the mip chain are specified by their parents
  59099. // filtering angle and a per-level scale and bias
  59100. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  59101. //
  59102. //--------------------------------------------------------------------------------------
  59103. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  59104. // First, take count of the lighting model to modify SpecularPower
  59105. // 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;
  59106. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  59107. //Cone angle start (for generating subsequent mip levels)
  59108. var currentSpecularPower = this.specularPower;
  59109. //Build filter lookup tables based on the source miplevel size
  59110. this.precomputeFilterLookupTables(this.inputSize);
  59111. // Note that we need to filter the first level before generating mipmap
  59112. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  59113. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  59114. // TODO : Write a function to copy and scale the base mipmap in output
  59115. // I am just lazy here and just put a high specular power value, and do some if.
  59116. if (this.excludeBase && (levelIndex == 0)) {
  59117. // 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).
  59118. currentSpecularPower = 100000.0;
  59119. }
  59120. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  59121. var srcCubeImage = this.input;
  59122. var dstCubeImage = this._outputSurface[levelIndex];
  59123. var dstSize = this.outputSize >> levelIndex;
  59124. // Compute required angle.
  59125. var angle = this.getBaseFilterAngle(currentSpecularPower);
  59126. // filter cube surfaces
  59127. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  59128. // fix seams
  59129. if (this.fixup) {
  59130. this.fixupCubeEdges(dstCubeImage, dstSize);
  59131. }
  59132. // Decrease the specular power to generate the mipmap chain
  59133. // TODO : Use another method for Exclude (see first comment at start of the function
  59134. if (this.excludeBase && (levelIndex == 0)) {
  59135. currentSpecularPower = this.specularPower;
  59136. }
  59137. currentSpecularPower *= this.cosinePowerDropPerMip;
  59138. }
  59139. };
  59140. //--------------------------------------------------------------------------------------
  59141. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  59142. // It allow to optimize the texel to access base on the specular power.
  59143. //--------------------------------------------------------------------------------------
  59144. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  59145. // We want to find the alpha such that:
  59146. // cos(alpha)^cosinePower = epsilon
  59147. // That's: acos(epsilon^(1/cosinePower))
  59148. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  59149. var angle = 180.0;
  59150. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  59151. angle *= 180.0 / Math.PI; // Convert to degree
  59152. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  59153. return angle;
  59154. };
  59155. //--------------------------------------------------------------------------------------
  59156. //Builds the following lookup tables prior to filtering:
  59157. // -normalizer cube map
  59158. // -tap weight lookup table
  59159. //
  59160. //--------------------------------------------------------------------------------------
  59161. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  59162. var srcTexelAngle;
  59163. var iCubeFace;
  59164. //clear pre-existing normalizer cube map
  59165. this._normCubeMap = [];
  59166. //Normalized vectors per cubeface and per-texel solid angle
  59167. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  59168. };
  59169. //--------------------------------------------------------------------------------------
  59170. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  59171. //
  59172. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  59173. //
  59174. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  59175. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  59176. // below
  59177. //--------------------------------------------------------------------------------------
  59178. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  59179. var iCubeFace;
  59180. var u;
  59181. var v;
  59182. //iterate over cube faces
  59183. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  59184. //First three channels for norm cube, and last channel for solid angle
  59185. this._normCubeMap.push(new Float32Array(size * size * 4));
  59186. //fast texture walk, build normalizer cube map
  59187. var facesData = this.input[iCubeFace];
  59188. for (v = 0; v < size; v++) {
  59189. for (u = 0; u < size; u++) {
  59190. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  59191. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  59192. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  59193. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  59194. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  59195. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  59196. }
  59197. }
  59198. }
  59199. };
  59200. //--------------------------------------------------------------------------------------
  59201. // Convert cubemap face texel coordinates and face idx to 3D vector
  59202. // note the U and V coords are integer coords and range from 0 to size-1
  59203. // this routine can be used to generate a normalizer cube map
  59204. //--------------------------------------------------------------------------------------
  59205. // SL BEGIN
  59206. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  59207. var nvcU;
  59208. var nvcV;
  59209. var tempVec;
  59210. // Change from original AMD code
  59211. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  59212. // + 0.5f is for texel center addressing
  59213. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  59214. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  59215. // warp fixup
  59216. if (fixup && size > 1) {
  59217. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  59218. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  59219. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  59220. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  59221. }
  59222. // Get current vector
  59223. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  59224. // U contribution
  59225. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  59226. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  59227. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  59228. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  59229. // V contribution and Sum
  59230. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  59231. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  59232. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  59233. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  59234. //add face axis
  59235. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  59236. PMREMGenerator._vectorTemp.x += faceAxis[0];
  59237. PMREMGenerator._vectorTemp.y += faceAxis[1];
  59238. PMREMGenerator._vectorTemp.z += faceAxis[2];
  59239. //normalize vector
  59240. PMREMGenerator._vectorTemp.normalize();
  59241. return PMREMGenerator._vectorTemp;
  59242. };
  59243. //--------------------------------------------------------------------------------------
  59244. // Convert 3D vector to cubemap face texel coordinates and face idx
  59245. // note the U and V coords are integer coords and range from 0 to size-1
  59246. // this routine can be used to generate a normalizer cube map
  59247. //
  59248. // returns face IDX and texel coords
  59249. //--------------------------------------------------------------------------------------
  59250. // SL BEGIN
  59251. /*
  59252. Mapping Texture Coordinates to Cube Map Faces
  59253. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  59254. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  59255. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  59256. map arrangement in Pixar's RenderMan package.
  59257. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  59258. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  59259. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  59260. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  59261. the major axis direction). The target column in the table below explains how the major axis direction
  59262. maps to the 2D image of a particular cube map target.
  59263. major axis
  59264. direction target sc tc ma
  59265. ---------- --------------------------------- --- --- ---
  59266. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  59267. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  59268. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  59269. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  59270. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  59271. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  59272. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  59273. an updated (s,t) is calculated as follows
  59274. s = ( sc/|ma| + 1 ) / 2
  59275. t = ( tc/|ma| + 1 ) / 2
  59276. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  59277. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  59278. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  59279. */
  59280. // Note this method return U and V in range from 0 to size-1
  59281. // SL END
  59282. // Store the information in vector3 for convenience (faceindex, u, v)
  59283. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  59284. var maxCoord;
  59285. var faceIdx;
  59286. //absolute value 3
  59287. var absX = Math.abs(x);
  59288. var absY = Math.abs(y);
  59289. var absZ = Math.abs(z);
  59290. if (absX >= absY && absX >= absZ) {
  59291. maxCoord = absX;
  59292. if (x >= 0) {
  59293. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  59294. }
  59295. else {
  59296. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  59297. }
  59298. }
  59299. else if (absY >= absX && absY >= absZ) {
  59300. maxCoord = absY;
  59301. if (y >= 0) {
  59302. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  59303. }
  59304. else {
  59305. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  59306. }
  59307. }
  59308. else {
  59309. maxCoord = absZ;
  59310. if (z >= 0) {
  59311. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  59312. }
  59313. else {
  59314. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  59315. }
  59316. }
  59317. //divide through by max coord so face vector lies on cube face
  59318. var scale = 1 / maxCoord;
  59319. x *= scale;
  59320. y *= scale;
  59321. z *= scale;
  59322. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  59323. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  59324. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  59325. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  59326. // Modify original AMD code to return value from 0 to Size - 1
  59327. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  59328. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  59329. PMREMGenerator._vectorTemp.x = faceIdx;
  59330. PMREMGenerator._vectorTemp.y = u;
  59331. PMREMGenerator._vectorTemp.z = v;
  59332. return PMREMGenerator._vectorTemp;
  59333. };
  59334. //--------------------------------------------------------------------------------------
  59335. //Original code from Ignacio CastaÒo
  59336. // This formula is from Manne ÷hrstrˆm's thesis.
  59337. // Take two coordiantes in the range [-1, 1] that define a portion of a
  59338. // cube face and return the area of the projection of that portion on the
  59339. // surface of the sphere.
  59340. //--------------------------------------------------------------------------------------
  59341. PMREMGenerator.prototype.areaElement = function (x, y) {
  59342. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  59343. };
  59344. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  59345. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  59346. // (+ 0.5f is for texel center addressing)
  59347. u = (2.0 * (u + 0.5) / size) - 1.0;
  59348. v = (2.0 * (v + 0.5) / size) - 1.0;
  59349. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  59350. var invResolution = 1.0 / size;
  59351. // U and V are the -1..1 texture coordinate on the current face.
  59352. // Get projected area for this texel
  59353. var x0 = u - invResolution;
  59354. var y0 = v - invResolution;
  59355. var x1 = u + invResolution;
  59356. var y1 = v + invResolution;
  59357. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  59358. return solidAngle;
  59359. };
  59360. //--------------------------------------------------------------------------------------
  59361. //The key to the speed of these filtering routines is to quickly define a per-face
  59362. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  59363. // Later these pixels are selectively processed based on their dot products to see if
  59364. // they reside within the filtering cone.
  59365. //
  59366. //This is done by computing the smallest per-texel angle to get a conservative estimate
  59367. // of the number of texels needed to be covered in width and height order to filter the
  59368. // region. the bounding box for the center taps face is defined first, and if the
  59369. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  59370. // defined next
  59371. //--------------------------------------------------------------------------------------
  59372. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  59373. // note that pixels within these regions may be rejected
  59374. // based on the anlge
  59375. var iCubeFace;
  59376. var u;
  59377. var v;
  59378. // bounding box per face to specify region to process
  59379. var filterExtents = [];
  59380. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  59381. filterExtents.push(new CMGBoundinBox());
  59382. }
  59383. // min angle a src texel can cover (in degrees)
  59384. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  59385. // angle about center tap to define filter cone
  59386. // filter angle is 1/2 the cone angle
  59387. var filterAngle = filterConeAngle / 2.0;
  59388. //ensure filter angle is larger than a texel
  59389. if (filterAngle < srcTexelAngle) {
  59390. filterAngle = srcTexelAngle;
  59391. }
  59392. //ensure filter cone is always smaller than the hemisphere
  59393. if (filterAngle > 90.0) {
  59394. filterAngle = 90.0;
  59395. }
  59396. // the maximum number of texels in 1D the filter cone angle will cover
  59397. // used to determine bounding box size for filter extents
  59398. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  59399. // ensure conservative region always covers at least one texel
  59400. if (filterSize < 1) {
  59401. filterSize = 1;
  59402. }
  59403. // dotProdThresh threshold based on cone angle to determine whether or not taps
  59404. // reside within the cone angle
  59405. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  59406. // process required faces
  59407. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  59408. //iterate over dst cube map face texel
  59409. for (v = 0; v < dstSize; v++) {
  59410. for (u = 0; u < dstSize; u++) {
  59411. //get center tap direction
  59412. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  59413. //clear old per-face filter extents
  59414. this.clearFilterExtents(filterExtents);
  59415. //define per-face filter extents
  59416. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  59417. //perform filtering of src faces using filter extents
  59418. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  59419. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  59420. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  59421. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  59422. }
  59423. }
  59424. }
  59425. };
  59426. //--------------------------------------------------------------------------------------
  59427. //Clear filter extents for the 6 cube map faces
  59428. //--------------------------------------------------------------------------------------
  59429. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  59430. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  59431. filterExtents[iCubeFaces].clear();
  59432. }
  59433. };
  59434. //--------------------------------------------------------------------------------------
  59435. //Define per-face bounding box filter extents
  59436. //
  59437. // These define conservative texel regions in each of the faces the filter can possibly
  59438. // process. When the pixels in the regions are actually processed, the dot product
  59439. // between the tap vector and the center tap vector is used to determine the weight of
  59440. // the tap and whether or not the tap is within the cone.
  59441. //
  59442. //--------------------------------------------------------------------------------------
  59443. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  59444. //neighboring face and bleed over amount, and width of BBOX for
  59445. // left, right, top, and bottom edges of this face
  59446. var bleedOverAmount = [0, 0, 0, 0];
  59447. var bleedOverBBoxMin = [0, 0, 0, 0];
  59448. var bleedOverBBoxMax = [0, 0, 0, 0];
  59449. var neighborFace;
  59450. var neighborEdge;
  59451. var oppositeFaceIdx;
  59452. //get face idx, and u, v info from center tap dir
  59453. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  59454. var faceIdx = result.x;
  59455. var u = result.y;
  59456. var v = result.z;
  59457. //define bbox size within face
  59458. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  59459. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  59460. filterExtents[faceIdx].clampMin(0, 0, 0);
  59461. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  59462. //u and v extent in face corresponding to center tap
  59463. var minU = filterExtents[faceIdx].min.x;
  59464. var minV = filterExtents[faceIdx].min.y;
  59465. var maxU = filterExtents[faceIdx].max.x;
  59466. var maxV = filterExtents[faceIdx].max.y;
  59467. //bleed over amounts for face across u=0 edge (left)
  59468. bleedOverAmount[0] = (bboxSize - u);
  59469. bleedOverBBoxMin[0] = minV;
  59470. bleedOverBBoxMax[0] = maxV;
  59471. //bleed over amounts for face across u=1 edge (right)
  59472. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  59473. bleedOverBBoxMin[1] = minV;
  59474. bleedOverBBoxMax[1] = maxV;
  59475. //bleed over to face across v=0 edge (up)
  59476. bleedOverAmount[2] = (bboxSize - v);
  59477. bleedOverBBoxMin[2] = minU;
  59478. bleedOverBBoxMax[2] = maxU;
  59479. //bleed over to face across v=1 edge (down)
  59480. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  59481. bleedOverBBoxMin[3] = minU;
  59482. bleedOverBBoxMax[3] = maxU;
  59483. //compute bleed over regions in neighboring faces
  59484. for (var i = 0; i < 4; i++) {
  59485. if (bleedOverAmount[i] > 0) {
  59486. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  59487. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  59488. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  59489. // be flipped: the cases are
  59490. // if a left edge mates with a left or bottom edge on the neighbor
  59491. // if a top edge mates with a top or right edge on the neighbor
  59492. // if a right edge mates with a right or top edge on the neighbor
  59493. // if a bottom edge mates with a bottom or left edge on the neighbor
  59494. //Seeing as the edges are enumerated as follows
  59495. // left =0
  59496. // right =1
  59497. // top =2
  59498. // bottom =3
  59499. //
  59500. // so if the edge enums are the same, or the sum of the enums == 3,
  59501. // the bbox needs to be flipped
  59502. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  59503. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  59504. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  59505. }
  59506. //The way the bounding box is extended onto the neighboring face
  59507. // depends on which edge of neighboring face abuts with this one
  59508. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  59509. case PMREMGenerator.CP_EDGE_LEFT:
  59510. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  59511. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  59512. break;
  59513. case PMREMGenerator.CP_EDGE_RIGHT:
  59514. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  59515. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  59516. break;
  59517. case PMREMGenerator.CP_EDGE_TOP:
  59518. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  59519. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  59520. break;
  59521. case PMREMGenerator.CP_EDGE_BOTTOM:
  59522. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  59523. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  59524. break;
  59525. }
  59526. //clamp filter extents in non-center tap faces to remain within surface
  59527. filterExtents[neighborFace].clampMin(0, 0, 0);
  59528. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  59529. }
  59530. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  59531. // from the center tap face, then process the opposite face entirely for now.
  59532. //Note that the cases in which this happens, what usually happens is that
  59533. // more than one edge bleeds onto the opposite face, and the bounding box
  59534. // encompasses the entire cube map face.
  59535. if (bleedOverAmount[i] > srcSize) {
  59536. //determine opposite face
  59537. switch (faceIdx) {
  59538. case PMREMGenerator.CP_FACE_X_POS:
  59539. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  59540. break;
  59541. case PMREMGenerator.CP_FACE_X_NEG:
  59542. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  59543. break;
  59544. case PMREMGenerator.CP_FACE_Y_POS:
  59545. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  59546. break;
  59547. case PMREMGenerator.CP_FACE_Y_NEG:
  59548. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  59549. break;
  59550. case PMREMGenerator.CP_FACE_Z_POS:
  59551. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  59552. break;
  59553. case PMREMGenerator.CP_FACE_Z_NEG:
  59554. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  59555. break;
  59556. default:
  59557. break;
  59558. }
  59559. //just encompass entire face for now
  59560. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  59561. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  59562. }
  59563. }
  59564. };
  59565. //--------------------------------------------------------------------------------------
  59566. //ProcessFilterExtents
  59567. // Process bounding box in each cube face
  59568. //
  59569. //--------------------------------------------------------------------------------------
  59570. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  59571. //accumulators are 64-bit floats in order to have the precision needed
  59572. // over a summation of a large number of pixels
  59573. var dstAccum = [0, 0, 0, 0];
  59574. var weightAccum = 0;
  59575. var k = 0;
  59576. var nSrcChannels = this.numChannels;
  59577. // norm cube map and srcCubeMap have same face width
  59578. var faceWidth = srcSize;
  59579. //amount to add to pointer to move to next scanline in images
  59580. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  59581. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  59582. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  59583. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  59584. // iterate over cubefaces
  59585. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  59586. //if bbox is non empty
  59587. if (!filterExtents[iFaceIdx].empty()) {
  59588. var uStart = filterExtents[iFaceIdx].min.x;
  59589. var vStart = filterExtents[iFaceIdx].min.y;
  59590. var uEnd = filterExtents[iFaceIdx].max.x;
  59591. var vEnd = filterExtents[iFaceIdx].max.y;
  59592. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  59593. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  59594. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  59595. for (var v = vStart; v <= vEnd; v++) {
  59596. var normCubeRowWalk = 0;
  59597. var srcCubeRowWalk = 0;
  59598. for (var u = uStart; u <= uEnd; u++) {
  59599. //pointer to direction in cube map associated with texel
  59600. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  59601. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  59602. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  59603. //check dot product to see if texel is within cone
  59604. var tapDotProd = texelVectX * centerTapDir.x +
  59605. texelVectY * centerTapDir.y +
  59606. texelVectZ * centerTapDir.z;
  59607. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  59608. //solid angle stored in 4th channel of normalizer/solid angle cube map
  59609. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  59610. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  59611. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  59612. // so just adding one to specularpower do the trick.
  59613. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  59614. //iterate over channels
  59615. for (k = 0; k < nSrcChannels; k++) {
  59616. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  59617. srcCubeRowWalk++;
  59618. }
  59619. weightAccum += weight; //accumulate weight
  59620. }
  59621. else {
  59622. //step across source pixel
  59623. srcCubeRowWalk += nSrcChannels;
  59624. }
  59625. normCubeRowWalk += 4; // 4 channels per norm cube map.
  59626. }
  59627. startIndexNormCubeMap += normCubePitch;
  59628. startIndexSrcCubeMap += srcCubePitch;
  59629. }
  59630. }
  59631. }
  59632. //divide through by weights if weight is non zero
  59633. if (weightAccum != 0.0) {
  59634. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  59635. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  59636. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  59637. if (this.numChannels > 3) {
  59638. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  59639. }
  59640. }
  59641. else {
  59642. // otherwise sample nearest
  59643. // get face idx and u, v texel coordinate in face
  59644. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  59645. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  59646. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  59647. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  59648. if (this.numChannels > 3) {
  59649. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  59650. }
  59651. }
  59652. return PMREMGenerator._vectorTemp;
  59653. };
  59654. //--------------------------------------------------------------------------------------
  59655. // Fixup cube edges
  59656. //
  59657. // average texels on cube map faces across the edges
  59658. // WARP/BENT Method Only.
  59659. //--------------------------------------------------------------------------------------
  59660. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  59661. var k;
  59662. var j;
  59663. var i;
  59664. var iFace;
  59665. var iCorner = 0;
  59666. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  59667. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  59668. // note that if functionality to filter across the three texels for each corner, then
  59669. //indexed by corner and face idx. the array contains the face the start points belongs to.
  59670. var cornerPtr = [
  59671. [[], [], []],
  59672. [[], [], []],
  59673. [[], [], []],
  59674. [[], [], []],
  59675. [[], [], []],
  59676. [[], [], []],
  59677. [[], [], []],
  59678. [[], [], []]
  59679. ];
  59680. //if there is no fixup, or fixup width = 0, do nothing
  59681. if (cubeMapSize < 1) {
  59682. return;
  59683. }
  59684. //special case 1x1 cubemap, average face colors
  59685. if (cubeMapSize == 1) {
  59686. //iterate over channels
  59687. for (k = 0; k < this.numChannels; k++) {
  59688. var accum = 0.0;
  59689. //iterate over faces to accumulate face colors
  59690. for (iFace = 0; iFace < 6; iFace++) {
  59691. accum += cubeMap[iFace][k];
  59692. }
  59693. //compute average over 6 face colors
  59694. accum /= 6.0;
  59695. //iterate over faces to distribute face colors
  59696. for (iFace = 0; iFace < 6; iFace++) {
  59697. cubeMap[iFace][k] = accum;
  59698. }
  59699. }
  59700. return;
  59701. }
  59702. //iterate over faces to collect list of corner texel pointers
  59703. for (iFace = 0; iFace < 6; iFace++) {
  59704. //the 4 corner pointers for this face
  59705. faceCornerStartIndicies[0] = [iFace, 0];
  59706. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  59707. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  59708. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  59709. //iterate over face corners to collect cube corner pointers
  59710. for (iCorner = 0; iCorner < 4; iCorner++) {
  59711. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  59712. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  59713. cornerNumPtrs[corner]++;
  59714. }
  59715. }
  59716. //iterate over corners to average across corner tap values
  59717. for (iCorner = 0; iCorner < 8; iCorner++) {
  59718. for (k = 0; k < this.numChannels; k++) {
  59719. var cornerTapAccum = 0.0;
  59720. //iterate over corner texels and average results
  59721. for (i = 0; i < 3; i++) {
  59722. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  59723. }
  59724. //divide by 3 to compute average of corner tap values
  59725. cornerTapAccum *= (1.0 / 3.0);
  59726. //iterate over corner texels and average results
  59727. for (i = 0; i < 3; i++) {
  59728. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  59729. }
  59730. }
  59731. }
  59732. //iterate over the twelve edges of the cube to average across edges
  59733. for (i = 0; i < 12; i++) {
  59734. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  59735. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  59736. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  59737. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  59738. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  59739. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  59740. var edgeWalk = 0;
  59741. var neighborEdgeWalk = 0;
  59742. //Determine walking pointers based on edge type
  59743. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  59744. switch (edge) {
  59745. case PMREMGenerator.CP_EDGE_LEFT:
  59746. // no change to faceEdgeStartPtr
  59747. edgeWalk = this.numChannels * cubeMapSize;
  59748. break;
  59749. case PMREMGenerator.CP_EDGE_RIGHT:
  59750. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  59751. edgeWalk = this.numChannels * cubeMapSize;
  59752. break;
  59753. case PMREMGenerator.CP_EDGE_TOP:
  59754. // no change to faceEdgeStartPtr
  59755. edgeWalk = this.numChannels;
  59756. break;
  59757. case PMREMGenerator.CP_EDGE_BOTTOM:
  59758. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  59759. edgeWalk = this.numChannels;
  59760. break;
  59761. }
  59762. //For certain types of edge abutments, the neighbor edge walk needs to
  59763. // be flipped: the cases are
  59764. // if a left edge mates with a left or bottom edge on the neighbor
  59765. // if a top edge mates with a top or right edge on the neighbor
  59766. // if a right edge mates with a right or top edge on the neighbor
  59767. // if a bottom edge mates with a bottom or left edge on the neighbor
  59768. //Seeing as the edges are enumerated as follows
  59769. // left =0
  59770. // right =1
  59771. // top =2
  59772. // bottom =3
  59773. //
  59774. //If the edge enums are the same, or the sum of the enums == 3,
  59775. // the neighbor edge walk needs to be flipped
  59776. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  59777. switch (neighborEdge) {
  59778. case PMREMGenerator.CP_EDGE_LEFT:
  59779. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  59780. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  59781. break;
  59782. case PMREMGenerator.CP_EDGE_RIGHT:
  59783. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  59784. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  59785. break;
  59786. case PMREMGenerator.CP_EDGE_TOP:
  59787. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  59788. neighborEdgeWalk = -this.numChannels;
  59789. break;
  59790. case PMREMGenerator.CP_EDGE_BOTTOM:
  59791. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  59792. neighborEdgeWalk = -this.numChannels;
  59793. break;
  59794. }
  59795. }
  59796. else {
  59797. //swapped direction neighbor edge walk
  59798. switch (neighborEdge) {
  59799. case PMREMGenerator.CP_EDGE_LEFT:
  59800. //no change to neighborEdgeStartPtr for this case since it points
  59801. // to the upper left corner already
  59802. neighborEdgeWalk = this.numChannels * cubeMapSize;
  59803. break;
  59804. case PMREMGenerator.CP_EDGE_RIGHT:
  59805. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  59806. neighborEdgeWalk = this.numChannels * cubeMapSize;
  59807. break;
  59808. case PMREMGenerator.CP_EDGE_TOP:
  59809. //no change to neighborEdgeStartPtr for this case since it points
  59810. // to the upper left corner already
  59811. neighborEdgeWalk = this.numChannels;
  59812. break;
  59813. case PMREMGenerator.CP_EDGE_BOTTOM:
  59814. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  59815. neighborEdgeWalk = this.numChannels;
  59816. break;
  59817. }
  59818. }
  59819. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  59820. //nearby neighborhood
  59821. //step ahead one texel on edge
  59822. edgeStartIndex += edgeWalk;
  59823. neighborEdgeStartIndex += neighborEdgeWalk;
  59824. // note that this loop does not process the corner texels, since they have already been
  59825. // averaged across faces across earlier
  59826. for (j = 1; j < (cubeMapSize - 1); j++) {
  59827. //for each set of taps along edge, average them
  59828. // and rewrite the results into the edges
  59829. for (k = 0; k < this.numChannels; k++) {
  59830. var edgeTap = cubeMap[face][edgeStartIndex + k];
  59831. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  59832. //compute average of tap intensity values
  59833. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  59834. //propagate average of taps to edge taps
  59835. cubeMap[face][edgeStartIndex + k] = avgTap;
  59836. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  59837. }
  59838. edgeStartIndex += edgeWalk;
  59839. neighborEdgeStartIndex += neighborEdgeWalk;
  59840. }
  59841. }
  59842. };
  59843. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  59844. PMREMGenerator.CP_UDIR = 0;
  59845. PMREMGenerator.CP_VDIR = 1;
  59846. PMREMGenerator.CP_FACEAXIS = 2;
  59847. //used to index cube faces
  59848. PMREMGenerator.CP_FACE_X_POS = 0;
  59849. PMREMGenerator.CP_FACE_X_NEG = 1;
  59850. PMREMGenerator.CP_FACE_Y_POS = 2;
  59851. PMREMGenerator.CP_FACE_Y_NEG = 3;
  59852. PMREMGenerator.CP_FACE_Z_POS = 4;
  59853. PMREMGenerator.CP_FACE_Z_NEG = 5;
  59854. //used to index image edges
  59855. // NOTE.. the actual number corresponding to the edge is important
  59856. // do not change these, or the code will break
  59857. //
  59858. // CP_EDGE_LEFT is u = 0
  59859. // CP_EDGE_RIGHT is u = width-1
  59860. // CP_EDGE_TOP is v = 0
  59861. // CP_EDGE_BOTTOM is v = height-1
  59862. PMREMGenerator.CP_EDGE_LEFT = 0;
  59863. PMREMGenerator.CP_EDGE_RIGHT = 1;
  59864. PMREMGenerator.CP_EDGE_TOP = 2;
  59865. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  59866. //corners of CUBE map (P or N specifys if it corresponds to the
  59867. // positive or negative direction each of X, Y, and Z
  59868. PMREMGenerator.CP_CORNER_NNN = 0;
  59869. PMREMGenerator.CP_CORNER_NNP = 1;
  59870. PMREMGenerator.CP_CORNER_NPN = 2;
  59871. PMREMGenerator.CP_CORNER_NPP = 3;
  59872. PMREMGenerator.CP_CORNER_PNN = 4;
  59873. PMREMGenerator.CP_CORNER_PNP = 5;
  59874. PMREMGenerator.CP_CORNER_PPN = 6;
  59875. PMREMGenerator.CP_CORNER_PPP = 7;
  59876. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  59877. //3x2 matrices that map cube map indexing vectors in 3d
  59878. // (after face selection and divide through by the
  59879. // _ABSOLUTE VALUE_ of the max coord)
  59880. // into NVC space
  59881. //Note this currently assumes the D3D cube face ordering and orientation
  59882. PMREMGenerator._sgFace2DMapping = [
  59883. //XPOS face
  59884. [[0, 0, -1],
  59885. [0, -1, 0],
  59886. [1, 0, 0]],
  59887. //XNEG face
  59888. [[0, 0, 1],
  59889. [0, -1, 0],
  59890. [-1, 0, 0]],
  59891. //YPOS face
  59892. [[1, 0, 0],
  59893. [0, 0, 1],
  59894. [0, 1, 0]],
  59895. //YNEG face
  59896. [[1, 0, 0],
  59897. [0, 0, -1],
  59898. [0, -1, 0]],
  59899. //ZPOS face
  59900. [[1, 0, 0],
  59901. [0, -1, 0],
  59902. [0, 0, 1]],
  59903. //ZNEG face
  59904. [[-1, 0, 0],
  59905. [0, -1, 0],
  59906. [0, 0, -1]],
  59907. ];
  59908. //------------------------------------------------------------------------------
  59909. // D3D cube map face specification
  59910. // mapping from 3D x,y,z cube map lookup coordinates
  59911. // to 2D within face u,v coordinates
  59912. //
  59913. // --------------------> U direction
  59914. // | (within-face texture space)
  59915. // | _____
  59916. // | | |
  59917. // | | +Y |
  59918. // | _____|_____|_____ _____
  59919. // | | | | | |
  59920. // | | -X | +Z | +X | -Z |
  59921. // | |_____|_____|_____|_____|
  59922. // | | |
  59923. // | | -Y |
  59924. // | |_____|
  59925. // |
  59926. // v V direction
  59927. // (within-face texture space)
  59928. //------------------------------------------------------------------------------
  59929. //Information about neighbors and how texture coorrdinates change across faces
  59930. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  59931. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  59932. //Note this currently assumes the D3D cube face ordering and orientation
  59933. PMREMGenerator._sgCubeNgh = [
  59934. //XPOS face
  59935. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  59936. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  59937. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  59938. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  59939. //XNEG face
  59940. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  59941. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  59942. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  59943. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  59944. //YPOS face
  59945. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  59946. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  59947. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  59948. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  59949. //YNEG face
  59950. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  59951. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  59952. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  59953. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  59954. //ZPOS face
  59955. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  59956. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  59957. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  59958. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  59959. //ZNEG face
  59960. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  59961. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  59962. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  59963. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  59964. ];
  59965. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  59966. // this table is used to average over the edges.
  59967. PMREMGenerator._sgCubeEdgeList = [
  59968. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  59969. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  59970. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  59971. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  59972. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  59973. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  59974. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  59975. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  59976. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  59977. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  59978. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  59979. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  59980. ];
  59981. //Information about which of the 8 cube corners are correspond to the
  59982. // the 4 corners in each cube face
  59983. // the order is upper left, upper right, lower left, lower right
  59984. PMREMGenerator._sgCubeCornerList = [
  59985. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  59986. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  59987. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  59988. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  59989. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  59990. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  59991. ];
  59992. return PMREMGenerator;
  59993. })();
  59994. Internals.PMREMGenerator = PMREMGenerator;
  59995. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  59996. })(BABYLON || (BABYLON = {}));
  59997. var BABYLON;
  59998. (function (BABYLON) {
  59999. /**
  60000. * This represents a texture coming from an HDR input.
  60001. *
  60002. * The only supported format is currently panorama picture stored in RGBE format.
  60003. * Example of such files can be found on HDRLib: http://hdrlib.com/
  60004. */
  60005. var HDRCubeTexture = (function (_super) {
  60006. __extends(HDRCubeTexture, _super);
  60007. /**
  60008. * Instantiates an HDRTexture from the following parameters.
  60009. *
  60010. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  60011. * @param scene The scene the texture will be used in
  60012. * @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.
  60013. * @param noMipmap Forces to not generate the mipmap if true
  60014. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  60015. * @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)
  60016. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  60017. */
  60018. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  60019. if (noMipmap === void 0) { noMipmap = false; }
  60020. if (generateHarmonics === void 0) { generateHarmonics = true; }
  60021. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  60022. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  60023. _super.call(this, scene);
  60024. this._useInGammaSpace = false;
  60025. this._generateHarmonics = true;
  60026. this._isBABYLONPreprocessed = false;
  60027. /**
  60028. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  60029. */
  60030. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  60031. /**
  60032. * The spherical polynomial data extracted from the texture.
  60033. */
  60034. this.sphericalPolynomial = null;
  60035. /**
  60036. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  60037. * This is usefull at run time to apply the good shader.
  60038. */
  60039. this.isPMREM = false;
  60040. if (!url) {
  60041. return;
  60042. }
  60043. this.name = url;
  60044. this.url = url;
  60045. this.hasAlpha = false;
  60046. this.isCube = true;
  60047. this._textureMatrix = BABYLON.Matrix.Identity();
  60048. if (size) {
  60049. this._isBABYLONPreprocessed = false;
  60050. this._noMipmap = noMipmap;
  60051. this._size = size;
  60052. this._useInGammaSpace = useInGammaSpace;
  60053. this._usePMREMGenerator = usePMREMGenerator &&
  60054. scene.getEngine().getCaps().textureLOD &&
  60055. this.getScene().getEngine().getCaps().textureFloat &&
  60056. !this._useInGammaSpace;
  60057. }
  60058. else {
  60059. this._isBABYLONPreprocessed = true;
  60060. this._noMipmap = false;
  60061. this._useInGammaSpace = false;
  60062. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  60063. this.getScene().getEngine().getCaps().textureFloat &&
  60064. !this._useInGammaSpace;
  60065. }
  60066. this.isPMREM = this._usePMREMGenerator;
  60067. this._texture = this._getFromCache(url, this._noMipmap);
  60068. if (!this._texture) {
  60069. if (!scene.useDelayedTextureLoading) {
  60070. this.loadTexture();
  60071. }
  60072. else {
  60073. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  60074. }
  60075. }
  60076. }
  60077. /**
  60078. * Occurs when the file is a preprocessed .babylon.hdr file.
  60079. */
  60080. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  60081. var _this = this;
  60082. var mipLevels = 0;
  60083. var floatArrayView = null;
  60084. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  60085. var mips = [];
  60086. var startIndex = 30;
  60087. for (var level = 0; level < mipLevels; level++) {
  60088. mips.push([]);
  60089. // Fill each pixel of the mip level.
  60090. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  60091. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  60092. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  60093. mips[level].push(faceData);
  60094. startIndex += faceSize;
  60095. }
  60096. }
  60097. return mips;
  60098. } : null;
  60099. var callback = function (buffer) {
  60100. // Create Native Array Views
  60101. var intArrayView = new Int32Array(buffer);
  60102. floatArrayView = new Float32Array(buffer);
  60103. // Fill header.
  60104. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  60105. _this._size = intArrayView[1]; // CubeMap max mip face size.
  60106. // Update Texture Information.
  60107. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  60108. // Fill polynomial information.
  60109. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  60110. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  60111. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  60112. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  60113. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  60114. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  60115. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  60116. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  60117. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  60118. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  60119. // Fill pixel data.
  60120. mipLevels = intArrayView[29]; // Number of mip levels.
  60121. var startIndex = 30;
  60122. var data = [];
  60123. var faceSize = Math.pow(_this._size, 2) * 3;
  60124. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  60125. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  60126. startIndex += faceSize;
  60127. }
  60128. var results = [];
  60129. var byteArray = null;
  60130. // Push each faces.
  60131. for (var k = 0; k < 6; k++) {
  60132. var dataFace = null;
  60133. // If special cases.
  60134. if (!mipmapGenerator) {
  60135. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  60136. dataFace = data[j];
  60137. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  60138. // 3 channels of 1 bytes per pixel in bytes.
  60139. var byteBuffer = new ArrayBuffer(faceSize);
  60140. byteArray = new Uint8Array(byteBuffer);
  60141. }
  60142. for (var i = 0; i < _this._size * _this._size; i++) {
  60143. // Put in gamma space if requested.
  60144. if (_this._useInGammaSpace) {
  60145. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  60146. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  60147. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  60148. }
  60149. // Convert to int texture for fallback.
  60150. if (byteArray) {
  60151. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  60152. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  60153. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  60154. // May use luminance instead if the result is not accurate.
  60155. var max = Math.max(Math.max(r, g), b);
  60156. if (max > 255) {
  60157. var scale = 255 / max;
  60158. r *= scale;
  60159. g *= scale;
  60160. b *= scale;
  60161. }
  60162. byteArray[(i * 3) + 0] = r;
  60163. byteArray[(i * 3) + 1] = g;
  60164. byteArray[(i * 3) + 2] = b;
  60165. }
  60166. }
  60167. }
  60168. else {
  60169. dataFace = data[k];
  60170. }
  60171. // Fill the array accordingly.
  60172. if (byteArray) {
  60173. results.push(byteArray);
  60174. }
  60175. else {
  60176. results.push(dataFace);
  60177. }
  60178. }
  60179. return results;
  60180. };
  60181. 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);
  60182. };
  60183. /**
  60184. * Occurs when the file is raw .hdr file.
  60185. */
  60186. HDRCubeTexture.prototype.loadHDRTexture = function () {
  60187. var _this = this;
  60188. var callback = function (buffer) {
  60189. // Extract the raw linear data.
  60190. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  60191. // Generate harmonics if needed.
  60192. if (_this._generateHarmonics) {
  60193. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  60194. }
  60195. var results = [];
  60196. var byteArray = null;
  60197. // Push each faces.
  60198. for (var j = 0; j < 6; j++) {
  60199. // Create uintarray fallback.
  60200. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  60201. // 3 channels of 1 bytes per pixel in bytes.
  60202. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  60203. byteArray = new Uint8Array(byteBuffer);
  60204. }
  60205. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  60206. // If special cases.
  60207. if (_this._useInGammaSpace || byteArray) {
  60208. for (var i = 0; i < _this._size * _this._size; i++) {
  60209. // Put in gamma space if requested.
  60210. if (_this._useInGammaSpace) {
  60211. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  60212. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  60213. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  60214. }
  60215. // Convert to int texture for fallback.
  60216. if (byteArray) {
  60217. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  60218. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  60219. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  60220. // May use luminance instead if the result is not accurate.
  60221. var max = Math.max(Math.max(r, g), b);
  60222. if (max > 255) {
  60223. var scale = 255 / max;
  60224. r *= scale;
  60225. g *= scale;
  60226. b *= scale;
  60227. }
  60228. byteArray[(i * 3) + 0] = r;
  60229. byteArray[(i * 3) + 1] = g;
  60230. byteArray[(i * 3) + 2] = b;
  60231. }
  60232. }
  60233. }
  60234. if (byteArray) {
  60235. results.push(byteArray);
  60236. }
  60237. else {
  60238. results.push(dataFace);
  60239. }
  60240. }
  60241. return results;
  60242. };
  60243. var mipmapGenerator = null;
  60244. if (!this._noMipmap &&
  60245. this._usePMREMGenerator) {
  60246. mipmapGenerator = function (data) {
  60247. // Custom setup of the generator matching with the PBR shader values.
  60248. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  60249. return generator.filterCubeMap();
  60250. };
  60251. }
  60252. 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);
  60253. };
  60254. /**
  60255. * Starts the loading process of the texture.
  60256. */
  60257. HDRCubeTexture.prototype.loadTexture = function () {
  60258. if (this._isBABYLONPreprocessed) {
  60259. this.loadBabylonTexture();
  60260. }
  60261. else {
  60262. this.loadHDRTexture();
  60263. }
  60264. };
  60265. HDRCubeTexture.prototype.clone = function () {
  60266. var size = this._isBABYLONPreprocessed ? null : this._size;
  60267. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  60268. // Base texture
  60269. newTexture.level = this.level;
  60270. newTexture.wrapU = this.wrapU;
  60271. newTexture.wrapV = this.wrapV;
  60272. newTexture.coordinatesIndex = this.coordinatesIndex;
  60273. newTexture.coordinatesMode = this.coordinatesMode;
  60274. return newTexture;
  60275. };
  60276. // Methods
  60277. HDRCubeTexture.prototype.delayLoad = function () {
  60278. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  60279. return;
  60280. }
  60281. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  60282. this._texture = this._getFromCache(this.url, this._noMipmap);
  60283. if (!this._texture) {
  60284. this.loadTexture();
  60285. }
  60286. };
  60287. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  60288. return this._textureMatrix;
  60289. };
  60290. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  60291. var texture = null;
  60292. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  60293. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  60294. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  60295. texture.name = parsedTexture.name;
  60296. texture.hasAlpha = parsedTexture.hasAlpha;
  60297. texture.level = parsedTexture.level;
  60298. texture.coordinatesMode = parsedTexture.coordinatesMode;
  60299. }
  60300. return texture;
  60301. };
  60302. HDRCubeTexture.prototype.serialize = function () {
  60303. if (!this.name) {
  60304. return null;
  60305. }
  60306. var serializationObject = {};
  60307. serializationObject.name = this.name;
  60308. serializationObject.hasAlpha = this.hasAlpha;
  60309. serializationObject.isCube = true;
  60310. serializationObject.level = this.level;
  60311. serializationObject.size = this._size;
  60312. serializationObject.coordinatesMode = this.coordinatesMode;
  60313. serializationObject.useInGammaSpace = this._useInGammaSpace;
  60314. serializationObject.generateHarmonics = this._generateHarmonics;
  60315. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  60316. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  60317. serializationObject.customType = "BABYLON.HDRCubeTexture";
  60318. return serializationObject;
  60319. };
  60320. /**
  60321. * Saves as a file the data contained in the texture in a binary format.
  60322. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  60323. * as the spherical used in the lighting.
  60324. * @param url The HDR file url.
  60325. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  60326. * @param onError Method called if any error happens during download.
  60327. * @return The packed binary data.
  60328. */
  60329. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  60330. if (onError === void 0) { onError = null; }
  60331. var callback = function (buffer) {
  60332. var data = new Blob([buffer], { type: 'application/octet-stream' });
  60333. // Returns a URL you can use as a href.
  60334. var objUrl = window.URL.createObjectURL(data);
  60335. // Simulates a link to it and click to dowload.
  60336. var a = document.createElement("a");
  60337. document.body.appendChild(a);
  60338. a.style.display = "none";
  60339. a.href = objUrl;
  60340. a.download = "envmap.babylon.hdr";
  60341. a.click();
  60342. };
  60343. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  60344. };
  60345. /**
  60346. * Serializes the data contained in the texture in a binary format.
  60347. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  60348. * as the spherical used in the lighting.
  60349. * @param url The HDR file url.
  60350. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  60351. * @param onError Method called if any error happens during download.
  60352. * @return The packed binary data.
  60353. */
  60354. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  60355. if (onError === void 0) { onError = null; }
  60356. // Needs the url tho create the texture.
  60357. if (!url) {
  60358. return null;
  60359. }
  60360. // Check Power of two size.
  60361. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  60362. return null;
  60363. }
  60364. var getDataCallback = function (dataBuffer) {
  60365. // Extract the raw linear data.
  60366. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  60367. // Generate harmonics if needed.
  60368. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  60369. // Generate seamless faces
  60370. var mipGeneratorArray = [];
  60371. // Data are known to be in +X +Y +Z -X -Y -Z
  60372. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  60373. mipGeneratorArray.push(cubeData.right); // +X
  60374. mipGeneratorArray.push(cubeData.left); // -X
  60375. mipGeneratorArray.push(cubeData.up); // +Y
  60376. mipGeneratorArray.push(cubeData.down); // -Y
  60377. mipGeneratorArray.push(cubeData.front); // +Z
  60378. mipGeneratorArray.push(cubeData.back); // -Z
  60379. // Custom setup of the generator matching with the PBR shader values.
  60380. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  60381. var mippedData = generator.filterCubeMap();
  60382. // Compute required byte length.
  60383. var byteLength = 1 * 4; // Raw Data Version int32.
  60384. byteLength += 4; // CubeMap max mip face size int32.
  60385. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  60386. // Add data size.
  60387. byteLength += 4; // Number of mip levels int32.
  60388. for (var level = 0; level < mippedData.length; level++) {
  60389. var mipSize = size >> level;
  60390. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  60391. }
  60392. // Prepare binary structure.
  60393. var buffer = new ArrayBuffer(byteLength);
  60394. var intArrayView = new Int32Array(buffer);
  60395. var floatArrayView = new Float32Array(buffer);
  60396. // Fill header.
  60397. intArrayView[0] = 1; // Version 1.
  60398. intArrayView[1] = size; // CubeMap max mip face size.
  60399. // Fill polynomial information.
  60400. sphericalPolynomial.x.toArray(floatArrayView, 2);
  60401. sphericalPolynomial.y.toArray(floatArrayView, 5);
  60402. sphericalPolynomial.z.toArray(floatArrayView, 8);
  60403. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  60404. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  60405. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  60406. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  60407. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  60408. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  60409. // Fill pixel data.
  60410. intArrayView[29] = mippedData.length; // Number of mip levels.
  60411. var startIndex = 30;
  60412. for (var level = 0; level < mippedData.length; level++) {
  60413. // Fill each pixel of the mip level.
  60414. var faceSize = Math.pow(size >> level, 2) * 3;
  60415. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  60416. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  60417. startIndex += faceSize;
  60418. }
  60419. }
  60420. // Callback.
  60421. callback(buffer);
  60422. };
  60423. // Download and process.
  60424. BABYLON.Tools.LoadFile(url, function (data) {
  60425. getDataCallback(data);
  60426. }, null, null, true, onError);
  60427. };
  60428. HDRCubeTexture._facesMapping = [
  60429. "right",
  60430. "up",
  60431. "front",
  60432. "left",
  60433. "down",
  60434. "back"
  60435. ];
  60436. return HDRCubeTexture;
  60437. })(BABYLON.BaseTexture);
  60438. BABYLON.HDRCubeTexture = HDRCubeTexture;
  60439. })(BABYLON || (BABYLON = {}));
  60440. var BABYLON;
  60441. (function (BABYLON) {
  60442. var Debug;
  60443. (function (Debug) {
  60444. /**
  60445. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  60446. */
  60447. var SkeletonViewer = (function () {
  60448. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  60449. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  60450. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  60451. this.skeleton = skeleton;
  60452. this.mesh = mesh;
  60453. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  60454. this.renderingGroupId = renderingGroupId;
  60455. this.color = BABYLON.Color3.White();
  60456. this._debugLines = [];
  60457. this._isEnabled = false;
  60458. this._scene = scene;
  60459. this.update();
  60460. this._renderFunction = this.update.bind(this);
  60461. }
  60462. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  60463. get: function () {
  60464. return this._isEnabled;
  60465. },
  60466. set: function (value) {
  60467. if (this._isEnabled === value) {
  60468. return;
  60469. }
  60470. this._isEnabled = value;
  60471. if (value) {
  60472. this._scene.registerBeforeRender(this._renderFunction);
  60473. }
  60474. else {
  60475. this._scene.unregisterBeforeRender(this._renderFunction);
  60476. }
  60477. },
  60478. enumerable: true,
  60479. configurable: true
  60480. });
  60481. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  60482. if (x === void 0) { x = 0; }
  60483. if (y === void 0) { y = 0; }
  60484. if (z === void 0) { z = 0; }
  60485. var tmat = BABYLON.Tmp.Matrix[0];
  60486. var parentBone = bone.getParent();
  60487. tmat.copyFrom(bone.getLocalMatrix());
  60488. if (x !== 0 || y !== 0 || z !== 0) {
  60489. var tmat2 = BABYLON.Tmp.Matrix[1];
  60490. BABYLON.Matrix.IdentityToRef(tmat2);
  60491. tmat2.m[12] = x;
  60492. tmat2.m[13] = y;
  60493. tmat2.m[14] = z;
  60494. tmat2.multiplyToRef(tmat, tmat);
  60495. }
  60496. if (parentBone) {
  60497. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  60498. }
  60499. tmat.multiplyToRef(meshMat, tmat);
  60500. position.x = tmat.m[12];
  60501. position.y = tmat.m[13];
  60502. position.z = tmat.m[14];
  60503. };
  60504. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  60505. var len = bones.length;
  60506. for (var i = 0; i < len; i++) {
  60507. var bone = bones[i];
  60508. var points = this._debugLines[i];
  60509. if (!points) {
  60510. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60511. this._debugLines[i] = points;
  60512. }
  60513. this._getBonePosition(points[0], bone, meshMat);
  60514. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  60515. }
  60516. };
  60517. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  60518. var len = bones.length;
  60519. var boneNum = 0;
  60520. for (var i = len - 1; i >= 0; i--) {
  60521. var childBone = bones[i];
  60522. var parentBone = childBone.getParent();
  60523. if (!parentBone) {
  60524. continue;
  60525. }
  60526. var points = this._debugLines[boneNum];
  60527. if (!points) {
  60528. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60529. this._debugLines[boneNum] = points;
  60530. }
  60531. this._getBonePosition(points[0], childBone, meshMat);
  60532. this._getBonePosition(points[1], parentBone, meshMat);
  60533. boneNum++;
  60534. }
  60535. };
  60536. SkeletonViewer.prototype.update = function () {
  60537. if (this.autoUpdateBonesMatrices) {
  60538. this._updateBoneMatrix(this.skeleton.bones[0]);
  60539. }
  60540. if (this.skeleton.bones[0].length === undefined) {
  60541. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60542. }
  60543. else {
  60544. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60545. }
  60546. if (!this._debugMesh) {
  60547. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  60548. this._debugMesh.renderingGroupId = this.renderingGroupId;
  60549. }
  60550. else {
  60551. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  60552. }
  60553. this._debugMesh.color = this.color;
  60554. };
  60555. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  60556. if (bone.getParent()) {
  60557. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  60558. }
  60559. var children = bone.children;
  60560. var len = children.length;
  60561. for (var i = 0; i < len; i++) {
  60562. this._updateBoneMatrix(children[i]);
  60563. }
  60564. };
  60565. SkeletonViewer.prototype.dispose = function () {
  60566. if (this._debugMesh) {
  60567. this.isEnabled = false;
  60568. this._debugMesh.dispose();
  60569. this._debugMesh = null;
  60570. }
  60571. };
  60572. return SkeletonViewer;
  60573. })();
  60574. Debug.SkeletonViewer = SkeletonViewer;
  60575. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60576. })(BABYLON || (BABYLON = {}));
  60577. var BABYLON;
  60578. (function (BABYLON) {
  60579. /**
  60580. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  60581. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  60582. * 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;
  60583. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  60584. */
  60585. var ColorCurves = (function () {
  60586. function ColorCurves() {
  60587. this._dirty = true;
  60588. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  60589. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  60590. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  60591. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  60592. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  60593. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  60594. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  60595. this._globalHue = 30;
  60596. this._globalDensity = 0;
  60597. this._globalSaturation = 0;
  60598. this._globalExposure = 0;
  60599. this._highlightsHue = 30;
  60600. this._highlightsDensity = 0;
  60601. this._highlightsSaturation = 0;
  60602. this._highlightsExposure = 0;
  60603. this._midtonesHue = 30;
  60604. this._midtonesDensity = 0;
  60605. this._midtonesSaturation = 0;
  60606. this._midtonesExposure = 0;
  60607. this._shadowsHue = 30;
  60608. this._shadowsDensity = 0;
  60609. this._shadowsSaturation = 0;
  60610. this._shadowsExposure = 0;
  60611. }
  60612. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  60613. /**
  60614. * Gets the global Hue value.
  60615. * 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).
  60616. */
  60617. get: function () {
  60618. return this._globalHue;
  60619. },
  60620. /**
  60621. * Sets the global Hue value.
  60622. * 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).
  60623. */
  60624. set: function (value) {
  60625. this._globalHue = value;
  60626. this._dirty = true;
  60627. },
  60628. enumerable: true,
  60629. configurable: true
  60630. });
  60631. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  60632. /**
  60633. * Gets the global Density value.
  60634. * 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.
  60635. * Values less than zero provide a filter of opposite hue.
  60636. */
  60637. get: function () {
  60638. return this._globalDensity;
  60639. },
  60640. /**
  60641. * Sets the global Density value.
  60642. * 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.
  60643. * Values less than zero provide a filter of opposite hue.
  60644. */
  60645. set: function (value) {
  60646. this._globalDensity = value;
  60647. this._dirty = true;
  60648. },
  60649. enumerable: true,
  60650. configurable: true
  60651. });
  60652. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  60653. /**
  60654. * Gets the global Saturation value.
  60655. * 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.
  60656. */
  60657. get: function () {
  60658. return this._globalSaturation;
  60659. },
  60660. /**
  60661. * Sets the global Saturation value.
  60662. * 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.
  60663. */
  60664. set: function (value) {
  60665. this._globalSaturation = value;
  60666. this._dirty = true;
  60667. },
  60668. enumerable: true,
  60669. configurable: true
  60670. });
  60671. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  60672. /**
  60673. * Gets the highlights Hue value.
  60674. * 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).
  60675. */
  60676. get: function () {
  60677. return this._highlightsHue;
  60678. },
  60679. /**
  60680. * Sets the highlights Hue value.
  60681. * 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).
  60682. */
  60683. set: function (value) {
  60684. this._highlightsHue = value;
  60685. this._dirty = true;
  60686. },
  60687. enumerable: true,
  60688. configurable: true
  60689. });
  60690. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  60691. /**
  60692. * Gets the highlights Density value.
  60693. * 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.
  60694. * Values less than zero provide a filter of opposite hue.
  60695. */
  60696. get: function () {
  60697. return this._highlightsDensity;
  60698. },
  60699. /**
  60700. * Sets the highlights Density value.
  60701. * 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.
  60702. * Values less than zero provide a filter of opposite hue.
  60703. */
  60704. set: function (value) {
  60705. this._highlightsDensity = value;
  60706. this._dirty = true;
  60707. },
  60708. enumerable: true,
  60709. configurable: true
  60710. });
  60711. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  60712. /**
  60713. * Gets the highlights Saturation value.
  60714. * 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.
  60715. */
  60716. get: function () {
  60717. return this._highlightsSaturation;
  60718. },
  60719. /**
  60720. * Sets the highlights Saturation value.
  60721. * 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.
  60722. */
  60723. set: function (value) {
  60724. this._highlightsSaturation = value;
  60725. this._dirty = true;
  60726. },
  60727. enumerable: true,
  60728. configurable: true
  60729. });
  60730. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  60731. /**
  60732. * Gets the highlights Exposure value.
  60733. * 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.
  60734. */
  60735. get: function () {
  60736. return this._highlightsExposure;
  60737. },
  60738. /**
  60739. * Sets the highlights Exposure value.
  60740. * 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.
  60741. */
  60742. set: function (value) {
  60743. this._highlightsExposure = value;
  60744. this._dirty = true;
  60745. },
  60746. enumerable: true,
  60747. configurable: true
  60748. });
  60749. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  60750. /**
  60751. * Gets the midtones Hue value.
  60752. * 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).
  60753. */
  60754. get: function () {
  60755. return this._midtonesHue;
  60756. },
  60757. /**
  60758. * Sets the midtones Hue value.
  60759. * 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).
  60760. */
  60761. set: function (value) {
  60762. this._midtonesHue = value;
  60763. this._dirty = true;
  60764. },
  60765. enumerable: true,
  60766. configurable: true
  60767. });
  60768. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  60769. /**
  60770. * Gets the midtones Density value.
  60771. * 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.
  60772. * Values less than zero provide a filter of opposite hue.
  60773. */
  60774. get: function () {
  60775. return this._midtonesDensity;
  60776. },
  60777. /**
  60778. * Sets the midtones Density value.
  60779. * 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.
  60780. * Values less than zero provide a filter of opposite hue.
  60781. */
  60782. set: function (value) {
  60783. this._midtonesDensity = value;
  60784. this._dirty = true;
  60785. },
  60786. enumerable: true,
  60787. configurable: true
  60788. });
  60789. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  60790. /**
  60791. * Gets the midtones Saturation value.
  60792. * 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.
  60793. */
  60794. get: function () {
  60795. return this._midtonesSaturation;
  60796. },
  60797. /**
  60798. * Sets the midtones Saturation value.
  60799. * 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.
  60800. */
  60801. set: function (value) {
  60802. this._midtonesSaturation = value;
  60803. this._dirty = true;
  60804. },
  60805. enumerable: true,
  60806. configurable: true
  60807. });
  60808. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  60809. /**
  60810. * Gets the midtones Exposure value.
  60811. * 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.
  60812. */
  60813. get: function () {
  60814. return this._midtonesExposure;
  60815. },
  60816. /**
  60817. * Sets the midtones Exposure value.
  60818. * 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.
  60819. */
  60820. set: function (value) {
  60821. this._midtonesExposure = value;
  60822. this._dirty = true;
  60823. },
  60824. enumerable: true,
  60825. configurable: true
  60826. });
  60827. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  60828. /**
  60829. * Gets the shadows Hue value.
  60830. * 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).
  60831. */
  60832. get: function () {
  60833. return this._shadowsHue;
  60834. },
  60835. /**
  60836. * Sets the shadows Hue value.
  60837. * 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).
  60838. */
  60839. set: function (value) {
  60840. this._shadowsHue = value;
  60841. this._dirty = true;
  60842. },
  60843. enumerable: true,
  60844. configurable: true
  60845. });
  60846. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  60847. /**
  60848. * Gets the shadows Density value.
  60849. * 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.
  60850. * Values less than zero provide a filter of opposite hue.
  60851. */
  60852. get: function () {
  60853. return this._shadowsDensity;
  60854. },
  60855. /**
  60856. * Sets the shadows Density value.
  60857. * 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.
  60858. * Values less than zero provide a filter of opposite hue.
  60859. */
  60860. set: function (value) {
  60861. this._shadowsDensity = value;
  60862. this._dirty = true;
  60863. },
  60864. enumerable: true,
  60865. configurable: true
  60866. });
  60867. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  60868. /**
  60869. * Gets the shadows Saturation value.
  60870. * 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.
  60871. */
  60872. get: function () {
  60873. return this._shadowsSaturation;
  60874. },
  60875. /**
  60876. * Sets the shadows Saturation value.
  60877. * 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.
  60878. */
  60879. set: function (value) {
  60880. this._shadowsSaturation = value;
  60881. this._dirty = true;
  60882. },
  60883. enumerable: true,
  60884. configurable: true
  60885. });
  60886. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  60887. /**
  60888. * Gets the shadows Exposure value.
  60889. * 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.
  60890. */
  60891. get: function () {
  60892. return this._shadowsExposure;
  60893. },
  60894. /**
  60895. * Sets the shadows Exposure value.
  60896. * 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.
  60897. */
  60898. set: function (value) {
  60899. this._shadowsExposure = value;
  60900. this._dirty = true;
  60901. },
  60902. enumerable: true,
  60903. configurable: true
  60904. });
  60905. /**
  60906. * Binds the color curves to the shader.
  60907. * @param colorCurves The color curve to bind
  60908. * @param effect The effect to bind to
  60909. */
  60910. ColorCurves.Bind = function (colorCurves, effect) {
  60911. if (colorCurves._dirty) {
  60912. colorCurves._dirty = false;
  60913. // Fill in global info.
  60914. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  60915. // Compute highlights info.
  60916. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  60917. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  60918. // Compute midtones info.
  60919. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  60920. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  60921. // Compute shadows info.
  60922. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  60923. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  60924. // Compute deltas (neutral is midtones).
  60925. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  60926. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  60927. }
  60928. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  60929. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  60930. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  60931. };
  60932. /**
  60933. * Prepare the list of uniforms associated with the ColorCurves effects.
  60934. * @param uniformsList The list of uniforms used in the effect
  60935. */
  60936. ColorCurves.PrepareUniforms = function (uniformsList) {
  60937. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  60938. };
  60939. /**
  60940. * Returns color grading data based on a hue, density, saturation and exposure value.
  60941. * @param filterHue The hue of the color filter.
  60942. * @param filterDensity The density of the color filter.
  60943. * @param saturation The saturation.
  60944. * @param exposure The exposure.
  60945. * @param result The result data container.
  60946. */
  60947. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  60948. if (hue == null) {
  60949. return;
  60950. }
  60951. hue = ColorCurves.clamp(hue, 0, 360);
  60952. density = ColorCurves.clamp(density, -100, 100);
  60953. saturation = ColorCurves.clamp(saturation, -100, 100);
  60954. exposure = ColorCurves.clamp(exposure, -100, 100);
  60955. // Remap the slider/config filter density with non-linear mapping and also scale by half
  60956. // so that the maximum filter density is only 50% control. This provides fine control
  60957. // for small values and reasonable range.
  60958. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  60959. density *= 0.5;
  60960. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  60961. if (density < 0) {
  60962. density *= -1;
  60963. hue = (hue + 180) % 360;
  60964. }
  60965. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  60966. result.scaleToRef(2, result);
  60967. result.a = 1 + 0.01 * saturation;
  60968. };
  60969. /**
  60970. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  60971. * @param value The input slider value in range [-100,100].
  60972. * @returns Adjusted value.
  60973. */
  60974. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  60975. value /= 100;
  60976. var x = Math.abs(value);
  60977. x = Math.pow(x, 2);
  60978. if (value < 0) {
  60979. x *= -1;
  60980. }
  60981. x *= 100;
  60982. return x;
  60983. };
  60984. /**
  60985. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  60986. * @param hue The hue (H) input.
  60987. * @param saturation The saturation (S) input.
  60988. * @param brightness The brightness (B) input.
  60989. * @result An RGBA color represented as Vector4.
  60990. */
  60991. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  60992. var h = ColorCurves.clamp(hue, 0, 360);
  60993. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  60994. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  60995. if (s === 0) {
  60996. result.r = v;
  60997. result.g = v;
  60998. result.b = v;
  60999. }
  61000. else {
  61001. // sector 0 to 5
  61002. h /= 60;
  61003. var i = Math.floor(h);
  61004. // fractional part of h
  61005. var f = h - i;
  61006. var p = v * (1 - s);
  61007. var q = v * (1 - s * f);
  61008. var t = v * (1 - s * (1 - f));
  61009. switch (i) {
  61010. case 0:
  61011. result.r = v;
  61012. result.g = t;
  61013. result.b = p;
  61014. break;
  61015. case 1:
  61016. result.r = q;
  61017. result.g = v;
  61018. result.b = p;
  61019. break;
  61020. case 2:
  61021. result.r = p;
  61022. result.g = v;
  61023. result.b = t;
  61024. break;
  61025. case 3:
  61026. result.r = p;
  61027. result.g = q;
  61028. result.b = v;
  61029. break;
  61030. case 4:
  61031. result.r = t;
  61032. result.g = p;
  61033. result.b = v;
  61034. break;
  61035. default:
  61036. result.r = v;
  61037. result.g = p;
  61038. result.b = q;
  61039. break;
  61040. }
  61041. }
  61042. result.a = 1;
  61043. };
  61044. /**
  61045. * Returns a value clamped between min and max
  61046. * @param value The value to clamp
  61047. * @param min The minimum of value
  61048. * @param max The maximum of value
  61049. * @returns The clamped value.
  61050. */
  61051. ColorCurves.clamp = function (value, min, max) {
  61052. return Math.min(Math.max(value, min), max);
  61053. };
  61054. /**
  61055. * Clones the current color curve instance.
  61056. * @return The cloned curves
  61057. */
  61058. ColorCurves.prototype.clone = function () {
  61059. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  61060. };
  61061. /**
  61062. * Serializes the current color curve instance to a json representation.
  61063. * @return a JSON representation
  61064. */
  61065. ColorCurves.prototype.serialize = function () {
  61066. return BABYLON.SerializationHelper.Serialize(this);
  61067. };
  61068. /**
  61069. * Parses the color curve from a json representation.
  61070. * @param source the JSON source to parse
  61071. * @return The parsed curves
  61072. */
  61073. ColorCurves.Parse = function (source) {
  61074. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  61075. };
  61076. __decorate([
  61077. BABYLON.serialize()
  61078. ], ColorCurves.prototype, "_globalHue", void 0);
  61079. __decorate([
  61080. BABYLON.serialize()
  61081. ], ColorCurves.prototype, "_globalDensity", void 0);
  61082. __decorate([
  61083. BABYLON.serialize()
  61084. ], ColorCurves.prototype, "_globalSaturation", void 0);
  61085. __decorate([
  61086. BABYLON.serialize()
  61087. ], ColorCurves.prototype, "_globalExposure", void 0);
  61088. __decorate([
  61089. BABYLON.serialize()
  61090. ], ColorCurves.prototype, "_highlightsHue", void 0);
  61091. __decorate([
  61092. BABYLON.serialize()
  61093. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  61094. __decorate([
  61095. BABYLON.serialize()
  61096. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  61097. __decorate([
  61098. BABYLON.serialize()
  61099. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  61100. __decorate([
  61101. BABYLON.serialize()
  61102. ], ColorCurves.prototype, "_midtonesHue", void 0);
  61103. __decorate([
  61104. BABYLON.serialize()
  61105. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  61106. __decorate([
  61107. BABYLON.serialize()
  61108. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  61109. __decorate([
  61110. BABYLON.serialize()
  61111. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  61112. return ColorCurves;
  61113. })();
  61114. BABYLON.ColorCurves = ColorCurves;
  61115. })(BABYLON || (BABYLON = {}));
  61116. var BABYLON;
  61117. (function (BABYLON) {
  61118. /**
  61119. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  61120. * It can help converting any input color in a desired output one. This can then be used to create effects
  61121. * from sepia, black and white to sixties or futuristic rendering...
  61122. *
  61123. * The only supported format is currently 3dl.
  61124. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  61125. */
  61126. var ColorGradingTexture = (function (_super) {
  61127. __extends(ColorGradingTexture, _super);
  61128. /**
  61129. * Instantiates a ColorGradingTexture from the following parameters.
  61130. *
  61131. * @param url The location of the color gradind data (currently only supporting 3dl)
  61132. * @param scene The scene the texture will be used in
  61133. */
  61134. function ColorGradingTexture(url, scene) {
  61135. _super.call(this, scene);
  61136. if (!url) {
  61137. return;
  61138. }
  61139. this._textureMatrix = BABYLON.Matrix.Identity();
  61140. this.name = url;
  61141. this.url = url;
  61142. this.hasAlpha = false;
  61143. this.isCube = false;
  61144. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61145. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61146. this.anisotropicFilteringLevel = 1;
  61147. this._texture = this._getFromCache(url, true);
  61148. if (!this._texture) {
  61149. if (!scene.useDelayedTextureLoading) {
  61150. this.loadTexture();
  61151. }
  61152. else {
  61153. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  61154. }
  61155. }
  61156. }
  61157. /**
  61158. * Returns the texture matrix used in most of the material.
  61159. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  61160. */
  61161. ColorGradingTexture.prototype.getTextureMatrix = function () {
  61162. return this._textureMatrix;
  61163. };
  61164. /**
  61165. * Occurs when the file being loaded is a .3dl LUT file.
  61166. */
  61167. ColorGradingTexture.prototype.load3dlTexture = function () {
  61168. var _this = this;
  61169. var mipLevels = 0;
  61170. var floatArrayView = null;
  61171. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61172. this._texture = texture;
  61173. var callback = function (text) {
  61174. var data;
  61175. var tempData;
  61176. var line;
  61177. var lines = text.split('\n');
  61178. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  61179. var maxColor = 0;
  61180. for (var i = 0; i < lines.length; i++) {
  61181. line = lines[i];
  61182. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  61183. continue;
  61184. if (line.indexOf('#') === 0)
  61185. continue;
  61186. var words = line.split(" ");
  61187. if (size === 0) {
  61188. // Number of space + one
  61189. size = words.length;
  61190. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  61191. tempData = new Float32Array(size * size * size * 4);
  61192. continue;
  61193. }
  61194. if (size != 0) {
  61195. var r = Math.max(parseInt(words[0]), 0);
  61196. var g = Math.max(parseInt(words[1]), 0);
  61197. var b = Math.max(parseInt(words[2]), 0);
  61198. maxColor = Math.max(r, maxColor);
  61199. maxColor = Math.max(g, maxColor);
  61200. maxColor = Math.max(b, maxColor);
  61201. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  61202. tempData[pixelStorageIndex + 0] = r;
  61203. tempData[pixelStorageIndex + 1] = g;
  61204. tempData[pixelStorageIndex + 2] = b;
  61205. tempData[pixelStorageIndex + 3] = 0;
  61206. pixelIndexSlice++;
  61207. if (pixelIndexSlice % size == 0) {
  61208. pixelIndexH++;
  61209. pixelIndexSlice = 0;
  61210. if (pixelIndexH % size == 0) {
  61211. pixelIndexW++;
  61212. pixelIndexH = 0;
  61213. }
  61214. }
  61215. }
  61216. }
  61217. for (var i = 0; i < tempData.length; i++) {
  61218. var value = tempData[i];
  61219. data[i] = (value / maxColor * 255);
  61220. }
  61221. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  61222. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  61223. };
  61224. BABYLON.Tools.LoadFile(this.url, callback);
  61225. return this._texture;
  61226. };
  61227. /**
  61228. * Starts the loading process of the texture.
  61229. */
  61230. ColorGradingTexture.prototype.loadTexture = function () {
  61231. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  61232. this.load3dlTexture();
  61233. }
  61234. };
  61235. /**
  61236. * Clones the color gradind texture.
  61237. */
  61238. ColorGradingTexture.prototype.clone = function () {
  61239. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  61240. // Base texture
  61241. newTexture.level = this.level;
  61242. return newTexture;
  61243. };
  61244. /**
  61245. * Called during delayed load for textures.
  61246. */
  61247. ColorGradingTexture.prototype.delayLoad = function () {
  61248. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  61249. return;
  61250. }
  61251. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  61252. this._texture = this._getFromCache(this.url, true);
  61253. if (!this._texture) {
  61254. this.loadTexture();
  61255. }
  61256. };
  61257. /**
  61258. * Binds the color grading to the shader.
  61259. * @param colorGrading The texture to bind
  61260. * @param effect The effect to bind to
  61261. */
  61262. ColorGradingTexture.Bind = function (colorGrading, effect) {
  61263. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  61264. var x = colorGrading.level; // Texture Level
  61265. var y = colorGrading.getSize().height; // Texture Size example with 8
  61266. var z = y - 1.0; // SizeMinusOne 8 - 1
  61267. var w = 1 / y; // Space of 1 slice 1 / 8
  61268. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  61269. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  61270. 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
  61271. 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
  61272. 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
  61273. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  61274. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  61275. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  61276. };
  61277. /**
  61278. * Prepare the list of uniforms associated with the ColorGrading effects.
  61279. * @param uniformsList The list of uniforms used in the effect
  61280. * @param samplersList The list of samplers used in the effect
  61281. */
  61282. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  61283. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  61284. samplersList.push("cameraColorGrading2DSampler");
  61285. };
  61286. /**
  61287. * Parses a color grading texture serialized by Babylon.
  61288. * @param parsedTexture The texture information being parsedTexture
  61289. * @param scene The scene to load the texture in
  61290. * @param rootUrl The root url of the data assets to load
  61291. * @return A color gradind texture
  61292. */
  61293. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  61294. var texture = null;
  61295. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  61296. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  61297. texture.name = parsedTexture.name;
  61298. texture.level = parsedTexture.level;
  61299. }
  61300. return texture;
  61301. };
  61302. /**
  61303. * Serializes the LUT texture to json format.
  61304. */
  61305. ColorGradingTexture.prototype.serialize = function () {
  61306. if (!this.name) {
  61307. return null;
  61308. }
  61309. var serializationObject = {};
  61310. serializationObject.name = this.name;
  61311. serializationObject.level = this.level;
  61312. serializationObject.customType = "BABYLON.ColorGradingTexture";
  61313. return serializationObject;
  61314. };
  61315. /**
  61316. * Empty line regex stored for GC.
  61317. */
  61318. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  61319. return ColorGradingTexture;
  61320. })(BABYLON.BaseTexture);
  61321. BABYLON.ColorGradingTexture = ColorGradingTexture;
  61322. })(BABYLON || (BABYLON = {}));
  61323. var BABYLON;
  61324. (function (BABYLON) {
  61325. var PBRMaterialDefines = (function (_super) {
  61326. __extends(PBRMaterialDefines, _super);
  61327. function PBRMaterialDefines() {
  61328. _super.call(this);
  61329. this.ALBEDO = false;
  61330. this.AMBIENT = false;
  61331. this.OPACITY = false;
  61332. this.OPACITYRGB = false;
  61333. this.REFLECTION = false;
  61334. this.EMISSIVE = false;
  61335. this.REFLECTIVITY = false;
  61336. this.BUMP = false;
  61337. this.PARALLAX = false;
  61338. this.PARALLAXOCCLUSION = false;
  61339. this.SPECULAROVERALPHA = false;
  61340. this.CLIPPLANE = false;
  61341. this.ALPHATEST = false;
  61342. this.ALPHAFROMALBEDO = false;
  61343. this.POINTSIZE = false;
  61344. this.FOG = false;
  61345. this.SPECULARTERM = false;
  61346. this.OPACITYFRESNEL = false;
  61347. this.EMISSIVEFRESNEL = false;
  61348. this.FRESNEL = false;
  61349. this.NORMAL = false;
  61350. this.UV1 = false;
  61351. this.UV2 = false;
  61352. this.VERTEXCOLOR = false;
  61353. this.VERTEXALPHA = false;
  61354. this.NUM_BONE_INFLUENCERS = 0;
  61355. this.BonesPerMesh = 0;
  61356. this.INSTANCES = false;
  61357. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  61358. this.MICROSURFACEAUTOMATIC = false;
  61359. this.EMISSIVEASILLUMINATION = false;
  61360. this.LINKEMISSIVEWITHALBEDO = false;
  61361. this.LIGHTMAP = false;
  61362. this.USELIGHTMAPASSHADOWMAP = false;
  61363. this.REFLECTIONMAP_3D = false;
  61364. this.REFLECTIONMAP_SPHERICAL = false;
  61365. this.REFLECTIONMAP_PLANAR = false;
  61366. this.REFLECTIONMAP_CUBIC = false;
  61367. this.REFLECTIONMAP_PROJECTION = false;
  61368. this.REFLECTIONMAP_SKYBOX = false;
  61369. this.REFLECTIONMAP_EXPLICIT = false;
  61370. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  61371. this.INVERTCUBICMAP = false;
  61372. this.LOGARITHMICDEPTH = false;
  61373. this.CAMERATONEMAP = false;
  61374. this.CAMERACONTRAST = false;
  61375. this.CAMERACOLORGRADING = false;
  61376. this.CAMERACOLORCURVES = false;
  61377. this.OVERLOADEDVALUES = false;
  61378. this.OVERLOADEDSHADOWVALUES = false;
  61379. this.USESPHERICALFROMREFLECTIONMAP = false;
  61380. this.REFRACTION = false;
  61381. this.REFRACTIONMAP_3D = false;
  61382. this.LINKREFRACTIONTOTRANSPARENCY = false;
  61383. this.REFRACTIONMAPINLINEARSPACE = false;
  61384. this.LODBASEDMICROSFURACE = false;
  61385. this.USEPHYSICALLIGHTFALLOFF = false;
  61386. this.RADIANCEOVERALPHA = false;
  61387. this.USEPMREMREFLECTION = false;
  61388. this.USEPMREMREFRACTION = false;
  61389. this.OPENGLNORMALMAP = false;
  61390. this.INVERTNORMALMAPX = false;
  61391. this.INVERTNORMALMAPY = false;
  61392. this.SHADOWFULLFLOAT = false;
  61393. this.rebuild();
  61394. }
  61395. return PBRMaterialDefines;
  61396. })(BABYLON.MaterialDefines);
  61397. /**
  61398. * The Physically based material of BJS.
  61399. *
  61400. * This offers the main features of a standard PBR material.
  61401. * For more information, please refer to the documentation :
  61402. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  61403. */
  61404. var PBRMaterial = (function (_super) {
  61405. __extends(PBRMaterial, _super);
  61406. /**
  61407. * Instantiates a new PBRMaterial instance.
  61408. *
  61409. * @param name The material name
  61410. * @param scene The scene the material will be use in.
  61411. */
  61412. function PBRMaterial(name, scene) {
  61413. var _this = this;
  61414. _super.call(this, name, scene);
  61415. /**
  61416. * Intensity of the direct lights e.g. the four lights available in your scene.
  61417. * This impacts both the direct diffuse and specular highlights.
  61418. */
  61419. this.directIntensity = 1.0;
  61420. /**
  61421. * Intensity of the emissive part of the material.
  61422. * This helps controlling the emissive effect without modifying the emissive color.
  61423. */
  61424. this.emissiveIntensity = 1.0;
  61425. /**
  61426. * Intensity of the environment e.g. how much the environment will light the object
  61427. * either through harmonics for rough material or through the refelction for shiny ones.
  61428. */
  61429. this.environmentIntensity = 1.0;
  61430. /**
  61431. * This is a special control allowing the reduction of the specular highlights coming from the
  61432. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  61433. */
  61434. this.specularIntensity = 1.0;
  61435. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  61436. /**
  61437. * Debug Control allowing disabling the bump map on this material.
  61438. */
  61439. this.disableBumpMap = false;
  61440. /**
  61441. * Debug Control helping enforcing or dropping the darkness of shadows.
  61442. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  61443. */
  61444. this.overloadedShadowIntensity = 1.0;
  61445. /**
  61446. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  61447. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  61448. */
  61449. this.overloadedShadeIntensity = 1.0;
  61450. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  61451. /**
  61452. * The camera exposure used on this material.
  61453. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  61454. * This corresponds to a photographic exposure.
  61455. */
  61456. this.cameraExposure = 1.0;
  61457. /**
  61458. * The camera contrast used on this material.
  61459. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  61460. */
  61461. this.cameraContrast = 1.0;
  61462. /**
  61463. * Color Grading 2D Lookup Texture.
  61464. * This allows special effects like sepia, black and white to sixties rendering style.
  61465. */
  61466. this.cameraColorGradingTexture = null;
  61467. /**
  61468. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  61469. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  61470. * 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;
  61471. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  61472. */
  61473. this.cameraColorCurves = null;
  61474. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  61475. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  61476. /**
  61477. * Debug Control allowing to overload the ambient color.
  61478. * This as to be use with the overloadedAmbientIntensity parameter.
  61479. */
  61480. this.overloadedAmbient = BABYLON.Color3.White();
  61481. /**
  61482. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  61483. */
  61484. this.overloadedAmbientIntensity = 0.0;
  61485. /**
  61486. * Debug Control allowing to overload the albedo color.
  61487. * This as to be use with the overloadedAlbedoIntensity parameter.
  61488. */
  61489. this.overloadedAlbedo = BABYLON.Color3.White();
  61490. /**
  61491. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  61492. */
  61493. this.overloadedAlbedoIntensity = 0.0;
  61494. /**
  61495. * Debug Control allowing to overload the reflectivity color.
  61496. * This as to be use with the overloadedReflectivityIntensity parameter.
  61497. */
  61498. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  61499. /**
  61500. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  61501. */
  61502. this.overloadedReflectivityIntensity = 0.0;
  61503. /**
  61504. * Debug Control allowing to overload the emissive color.
  61505. * This as to be use with the overloadedEmissiveIntensity parameter.
  61506. */
  61507. this.overloadedEmissive = BABYLON.Color3.White();
  61508. /**
  61509. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  61510. */
  61511. this.overloadedEmissiveIntensity = 0.0;
  61512. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  61513. /**
  61514. * Debug Control allowing to overload the reflection color.
  61515. * This as to be use with the overloadedReflectionIntensity parameter.
  61516. */
  61517. this.overloadedReflection = BABYLON.Color3.White();
  61518. /**
  61519. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  61520. */
  61521. this.overloadedReflectionIntensity = 0.0;
  61522. /**
  61523. * Debug Control allowing to overload the microsurface.
  61524. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  61525. */
  61526. this.overloadedMicroSurface = 0.0;
  61527. /**
  61528. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  61529. */
  61530. this.overloadedMicroSurfaceIntensity = 0.0;
  61531. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  61532. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  61533. /**
  61534. * AKA Diffuse Color in other nomenclature.
  61535. */
  61536. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  61537. /**
  61538. * AKA Specular Color in other nomenclature.
  61539. */
  61540. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  61541. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  61542. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  61543. /**
  61544. * AKA Glossiness in other nomenclature.
  61545. */
  61546. this.microSurface = 0.9;
  61547. /**
  61548. * source material index of refraction (IOR)' / 'destination material IOR.
  61549. */
  61550. this.indexOfRefraction = 0.66;
  61551. /**
  61552. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  61553. */
  61554. this.invertRefractionY = false;
  61555. /**
  61556. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  61557. * Materials half opaque for instance using refraction could benefit from this control.
  61558. */
  61559. this.linkRefractionWithTransparency = false;
  61560. /**
  61561. * The emissive and albedo are linked to never be more than one (Energy conservation).
  61562. */
  61563. this.linkEmissiveWithAlbedo = false;
  61564. this.useLightmapAsShadowmap = false;
  61565. /**
  61566. * In this mode, the emissive informtaion will always be added to the lighting once.
  61567. * A light for instance can be thought as emissive.
  61568. */
  61569. this.useEmissiveAsIllumination = false;
  61570. /**
  61571. * Secifies that the alpha is coming form the albedo channel alpha channel.
  61572. */
  61573. this.useAlphaFromAlbedoTexture = false;
  61574. /**
  61575. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  61576. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  61577. */
  61578. this.useSpecularOverAlpha = true;
  61579. /**
  61580. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  61581. */
  61582. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  61583. /**
  61584. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  61585. * The material will try to infer what glossiness each pixel should be.
  61586. */
  61587. this.useAutoMicroSurfaceFromReflectivityMap = false;
  61588. /**
  61589. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  61590. * the creation of the material.
  61591. */
  61592. this.useScalarInLinearSpace = false;
  61593. /**
  61594. * BJS is using an harcoded light falloff based on a manually sets up range.
  61595. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  61596. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  61597. */
  61598. this.usePhysicalLightFalloff = true;
  61599. /**
  61600. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  61601. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  61602. */
  61603. this.useRadianceOverAlpha = true;
  61604. /**
  61605. * Allows using the bump map in parallax mode.
  61606. */
  61607. this.useParallax = false;
  61608. /**
  61609. * Allows using the bump map in parallax occlusion mode.
  61610. */
  61611. this.useParallaxOcclusion = false;
  61612. /**
  61613. * Controls the scale bias of the parallax mode.
  61614. */
  61615. this.parallaxScaleBias = 0.05;
  61616. /**
  61617. * If sets to true, disables all the lights affecting the material.
  61618. */
  61619. this.disableLighting = false;
  61620. /**
  61621. * Number of Simultaneous lights allowed on the material.
  61622. */
  61623. this.maxSimultaneousLights = 4;
  61624. /**
  61625. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  61626. */
  61627. this.invertNormalMapX = false;
  61628. /**
  61629. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  61630. */
  61631. this.invertNormalMapY = false;
  61632. this._renderTargets = new BABYLON.SmartArray(16);
  61633. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  61634. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  61635. this._tempColor = new BABYLON.Color3();
  61636. this._defines = new PBRMaterialDefines();
  61637. this._cachedDefines = new PBRMaterialDefines();
  61638. this._myScene = null;
  61639. this._myShadowGenerator = null;
  61640. this._cachedDefines.BonesPerMesh = -1;
  61641. this.getRenderTargetTextures = function () {
  61642. _this._renderTargets.reset();
  61643. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  61644. _this._renderTargets.push(_this.reflectionTexture);
  61645. }
  61646. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  61647. _this._renderTargets.push(_this.refractionTexture);
  61648. }
  61649. return _this._renderTargets;
  61650. };
  61651. }
  61652. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  61653. get: function () {
  61654. return this._useLogarithmicDepth;
  61655. },
  61656. set: function (value) {
  61657. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  61658. },
  61659. enumerable: true,
  61660. configurable: true
  61661. });
  61662. PBRMaterial.prototype.needAlphaBlending = function () {
  61663. if (this.linkRefractionWithTransparency) {
  61664. return false;
  61665. }
  61666. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  61667. };
  61668. PBRMaterial.prototype.needAlphaTesting = function () {
  61669. if (this.linkRefractionWithTransparency) {
  61670. return false;
  61671. }
  61672. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  61673. };
  61674. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  61675. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  61676. };
  61677. PBRMaterial.prototype.getAlphaTestTexture = function () {
  61678. return this.albedoTexture;
  61679. };
  61680. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  61681. if (!mesh) {
  61682. return true;
  61683. }
  61684. if (this._defines.INSTANCES !== useInstances) {
  61685. return false;
  61686. }
  61687. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  61688. return true;
  61689. }
  61690. return false;
  61691. };
  61692. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  61693. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  61694. };
  61695. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  61696. if (!useScalarInLinear) {
  61697. color.toLinearSpaceToRef(ref);
  61698. }
  61699. else {
  61700. ref.r = color.r;
  61701. ref.g = color.g;
  61702. ref.b = color.b;
  61703. }
  61704. };
  61705. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  61706. var lightIndex = 0;
  61707. var depthValuesAlreadySet = false;
  61708. for (var index = 0; index < scene.lights.length; index++) {
  61709. var light = scene.lights[index];
  61710. if (!light.isEnabled()) {
  61711. continue;
  61712. }
  61713. if (!light.canAffectMesh(mesh)) {
  61714. continue;
  61715. }
  61716. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  61717. // GAMMA CORRECTION.
  61718. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  61719. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  61720. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  61721. if (defines["SPECULARTERM"]) {
  61722. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  61723. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  61724. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  61725. }
  61726. // Shadows
  61727. if (scene.shadowsEnabled) {
  61728. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  61729. }
  61730. lightIndex++;
  61731. if (lightIndex === maxSimultaneousLights)
  61732. break;
  61733. }
  61734. };
  61735. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  61736. if (this.checkReadyOnlyOnce) {
  61737. if (this._wasPreviouslyReady) {
  61738. return true;
  61739. }
  61740. }
  61741. var scene = this.getScene();
  61742. if (!this.checkReadyOnEveryCall) {
  61743. if (this._renderId === scene.getRenderId()) {
  61744. if (this._checkCache(scene, mesh, useInstances)) {
  61745. return true;
  61746. }
  61747. }
  61748. }
  61749. var engine = scene.getEngine();
  61750. var needNormals = false;
  61751. var needUVs = false;
  61752. this._defines.reset();
  61753. if (scene.texturesEnabled) {
  61754. // Textures
  61755. if (scene.texturesEnabled) {
  61756. if (scene.getEngine().getCaps().textureLOD) {
  61757. this._defines.LODBASEDMICROSFURACE = true;
  61758. }
  61759. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  61760. if (!this.albedoTexture.isReady()) {
  61761. return false;
  61762. }
  61763. else {
  61764. needUVs = true;
  61765. this._defines.ALBEDO = true;
  61766. }
  61767. }
  61768. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  61769. if (!this.ambientTexture.isReady()) {
  61770. return false;
  61771. }
  61772. else {
  61773. needUVs = true;
  61774. this._defines.AMBIENT = true;
  61775. }
  61776. }
  61777. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  61778. if (!this.opacityTexture.isReady()) {
  61779. return false;
  61780. }
  61781. else {
  61782. needUVs = true;
  61783. this._defines.OPACITY = true;
  61784. if (this.opacityTexture.getAlphaFromRGB) {
  61785. this._defines.OPACITYRGB = true;
  61786. }
  61787. }
  61788. }
  61789. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  61790. if (!this.reflectionTexture.isReady()) {
  61791. return false;
  61792. }
  61793. else {
  61794. needNormals = true;
  61795. this._defines.REFLECTION = true;
  61796. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  61797. this._defines.INVERTCUBICMAP = true;
  61798. }
  61799. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  61800. switch (this.reflectionTexture.coordinatesMode) {
  61801. case BABYLON.Texture.CUBIC_MODE:
  61802. case BABYLON.Texture.INVCUBIC_MODE:
  61803. this._defines.REFLECTIONMAP_CUBIC = true;
  61804. break;
  61805. case BABYLON.Texture.EXPLICIT_MODE:
  61806. this._defines.REFLECTIONMAP_EXPLICIT = true;
  61807. break;
  61808. case BABYLON.Texture.PLANAR_MODE:
  61809. this._defines.REFLECTIONMAP_PLANAR = true;
  61810. break;
  61811. case BABYLON.Texture.PROJECTION_MODE:
  61812. this._defines.REFLECTIONMAP_PROJECTION = true;
  61813. break;
  61814. case BABYLON.Texture.SKYBOX_MODE:
  61815. this._defines.REFLECTIONMAP_SKYBOX = true;
  61816. break;
  61817. case BABYLON.Texture.SPHERICAL_MODE:
  61818. this._defines.REFLECTIONMAP_SPHERICAL = true;
  61819. break;
  61820. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  61821. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  61822. break;
  61823. }
  61824. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  61825. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  61826. needNormals = true;
  61827. if (this.reflectionTexture.isPMREM) {
  61828. this._defines.USEPMREMREFLECTION = true;
  61829. }
  61830. }
  61831. }
  61832. }
  61833. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  61834. if (!this.lightmapTexture.isReady()) {
  61835. return false;
  61836. }
  61837. else {
  61838. needUVs = true;
  61839. this._defines.LIGHTMAP = true;
  61840. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  61841. }
  61842. }
  61843. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  61844. if (!this.emissiveTexture.isReady()) {
  61845. return false;
  61846. }
  61847. else {
  61848. needUVs = true;
  61849. this._defines.EMISSIVE = true;
  61850. }
  61851. }
  61852. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  61853. if (!this.reflectivityTexture.isReady()) {
  61854. return false;
  61855. }
  61856. else {
  61857. needUVs = true;
  61858. this._defines.REFLECTIVITY = true;
  61859. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  61860. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  61861. }
  61862. }
  61863. }
  61864. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  61865. if (!this.bumpTexture.isReady()) {
  61866. return false;
  61867. }
  61868. else {
  61869. needUVs = true;
  61870. this._defines.BUMP = true;
  61871. if (this.useParallax) {
  61872. this._defines.PARALLAX = true;
  61873. if (this.useParallaxOcclusion) {
  61874. this._defines.PARALLAXOCCLUSION = true;
  61875. }
  61876. }
  61877. if (this.invertNormalMapX) {
  61878. this._defines.INVERTNORMALMAPX = true;
  61879. }
  61880. if (this.invertNormalMapY) {
  61881. this._defines.INVERTNORMALMAPY = true;
  61882. }
  61883. }
  61884. }
  61885. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  61886. if (!this.refractionTexture.isReady()) {
  61887. return false;
  61888. }
  61889. else {
  61890. needUVs = true;
  61891. this._defines.REFRACTION = true;
  61892. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  61893. if (this.linkRefractionWithTransparency) {
  61894. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  61895. }
  61896. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  61897. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  61898. if (this.refractionTexture.isPMREM) {
  61899. this._defines.USEPMREMREFRACTION = true;
  61900. }
  61901. }
  61902. }
  61903. }
  61904. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  61905. if (!this.cameraColorGradingTexture.isReady()) {
  61906. return false;
  61907. }
  61908. else {
  61909. this._defines.CAMERACOLORGRADING = true;
  61910. }
  61911. }
  61912. }
  61913. // Effect
  61914. if (scene.clipPlane) {
  61915. this._defines.CLIPPLANE = true;
  61916. }
  61917. if (engine.getAlphaTesting()) {
  61918. this._defines.ALPHATEST = true;
  61919. }
  61920. if (this._shouldUseAlphaFromAlbedoTexture()) {
  61921. this._defines.ALPHAFROMALBEDO = true;
  61922. }
  61923. if (this.useEmissiveAsIllumination) {
  61924. this._defines.EMISSIVEASILLUMINATION = true;
  61925. }
  61926. if (this.linkEmissiveWithAlbedo) {
  61927. this._defines.LINKEMISSIVEWITHALBEDO = true;
  61928. }
  61929. if (this.useLogarithmicDepth) {
  61930. this._defines.LOGARITHMICDEPTH = true;
  61931. }
  61932. if (this.cameraContrast != 1) {
  61933. this._defines.CAMERACONTRAST = true;
  61934. }
  61935. if (this.cameraExposure != 1) {
  61936. this._defines.CAMERATONEMAP = true;
  61937. }
  61938. if (this.cameraColorCurves) {
  61939. this._defines.CAMERACOLORCURVES = true;
  61940. }
  61941. if (this.overloadedShadeIntensity != 1 ||
  61942. this.overloadedShadowIntensity != 1) {
  61943. this._defines.OVERLOADEDSHADOWVALUES = true;
  61944. }
  61945. if (this.overloadedMicroSurfaceIntensity > 0 ||
  61946. this.overloadedEmissiveIntensity > 0 ||
  61947. this.overloadedReflectivityIntensity > 0 ||
  61948. this.overloadedAlbedoIntensity > 0 ||
  61949. this.overloadedAmbientIntensity > 0 ||
  61950. this.overloadedReflectionIntensity > 0) {
  61951. this._defines.OVERLOADEDVALUES = true;
  61952. }
  61953. // Point size
  61954. if (this.pointsCloud || scene.forcePointsCloud) {
  61955. this._defines.POINTSIZE = true;
  61956. }
  61957. // Fog
  61958. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  61959. this._defines.FOG = true;
  61960. }
  61961. if (scene.lightsEnabled && !this.disableLighting) {
  61962. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  61963. }
  61964. if (BABYLON.StandardMaterial.FresnelEnabled) {
  61965. // Fresnel
  61966. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  61967. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  61968. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  61969. this._defines.OPACITYFRESNEL = true;
  61970. }
  61971. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  61972. this._defines.EMISSIVEFRESNEL = true;
  61973. }
  61974. needNormals = true;
  61975. this._defines.FRESNEL = true;
  61976. }
  61977. }
  61978. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  61979. this._defines.SPECULAROVERALPHA = true;
  61980. }
  61981. if (this.usePhysicalLightFalloff) {
  61982. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  61983. }
  61984. if (this.useRadianceOverAlpha) {
  61985. this._defines.RADIANCEOVERALPHA = true;
  61986. }
  61987. // Attribs
  61988. if (mesh) {
  61989. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  61990. this._defines.NORMAL = true;
  61991. }
  61992. if (needUVs) {
  61993. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61994. this._defines.UV1 = true;
  61995. }
  61996. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61997. this._defines.UV2 = true;
  61998. }
  61999. }
  62000. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  62001. this._defines.VERTEXCOLOR = true;
  62002. if (mesh.hasVertexAlpha) {
  62003. this._defines.VERTEXALPHA = true;
  62004. }
  62005. }
  62006. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62007. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  62008. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  62009. }
  62010. // Instances
  62011. if (useInstances) {
  62012. this._defines.INSTANCES = true;
  62013. }
  62014. }
  62015. // Get correct effect
  62016. if (!this._defines.isEqual(this._cachedDefines)) {
  62017. this._defines.cloneTo(this._cachedDefines);
  62018. scene.resetCachedMaterial();
  62019. // Fallbacks
  62020. var fallbacks = new BABYLON.EffectFallbacks();
  62021. if (this._defines.REFLECTION) {
  62022. fallbacks.addFallback(0, "REFLECTION");
  62023. }
  62024. if (this._defines.REFRACTION) {
  62025. fallbacks.addFallback(0, "REFRACTION");
  62026. }
  62027. if (this._defines.REFLECTIVITY) {
  62028. fallbacks.addFallback(0, "REFLECTIVITY");
  62029. }
  62030. if (this._defines.BUMP) {
  62031. fallbacks.addFallback(0, "BUMP");
  62032. }
  62033. if (this._defines.PARALLAX) {
  62034. fallbacks.addFallback(1, "PARALLAX");
  62035. }
  62036. if (this._defines.PARALLAXOCCLUSION) {
  62037. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  62038. }
  62039. if (this._defines.SPECULAROVERALPHA) {
  62040. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  62041. }
  62042. if (this._defines.FOG) {
  62043. fallbacks.addFallback(1, "FOG");
  62044. }
  62045. if (this._defines.POINTSIZE) {
  62046. fallbacks.addFallback(0, "POINTSIZE");
  62047. }
  62048. if (this._defines.LOGARITHMICDEPTH) {
  62049. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  62050. }
  62051. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  62052. if (this._defines.SPECULARTERM) {
  62053. fallbacks.addFallback(0, "SPECULARTERM");
  62054. }
  62055. if (this._defines.OPACITYFRESNEL) {
  62056. fallbacks.addFallback(1, "OPACITYFRESNEL");
  62057. }
  62058. if (this._defines.EMISSIVEFRESNEL) {
  62059. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  62060. }
  62061. if (this._defines.FRESNEL) {
  62062. fallbacks.addFallback(3, "FRESNEL");
  62063. }
  62064. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  62065. fallbacks.addCPUSkinningFallback(0, mesh);
  62066. }
  62067. //Attributes
  62068. var attribs = [BABYLON.VertexBuffer.PositionKind];
  62069. if (this._defines.NORMAL) {
  62070. attribs.push(BABYLON.VertexBuffer.NormalKind);
  62071. }
  62072. if (this._defines.UV1) {
  62073. attribs.push(BABYLON.VertexBuffer.UVKind);
  62074. }
  62075. if (this._defines.UV2) {
  62076. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  62077. }
  62078. if (this._defines.VERTEXCOLOR) {
  62079. attribs.push(BABYLON.VertexBuffer.ColorKind);
  62080. }
  62081. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  62082. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  62083. // Legacy browser patch
  62084. var shaderName = "pbr";
  62085. if (!scene.getEngine().getCaps().standardDerivatives) {
  62086. shaderName = "legacypbr";
  62087. }
  62088. var join = this._defines.toString();
  62089. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  62090. "vFogInfos", "vFogColor", "pointSize",
  62091. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  62092. "mBones",
  62093. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  62094. "depthValues",
  62095. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  62096. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  62097. "logarithmicDepthConstant",
  62098. "vSphericalX", "vSphericalY", "vSphericalZ",
  62099. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  62100. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  62101. "vMicrosurfaceTextureLods",
  62102. "vCameraInfos"
  62103. ];
  62104. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  62105. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  62106. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  62107. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  62108. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  62109. }
  62110. if (!this._effect.isReady()) {
  62111. return false;
  62112. }
  62113. this._renderId = scene.getRenderId();
  62114. this._wasPreviouslyReady = true;
  62115. if (mesh) {
  62116. if (!mesh._materialDefines) {
  62117. mesh._materialDefines = new PBRMaterialDefines();
  62118. }
  62119. this._defines.cloneTo(mesh._materialDefines);
  62120. }
  62121. return true;
  62122. };
  62123. PBRMaterial.prototype.unbind = function () {
  62124. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  62125. this._effect.setTexture("reflection2DSampler", null);
  62126. }
  62127. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  62128. this._effect.setTexture("refraction2DSampler", null);
  62129. }
  62130. _super.prototype.unbind.call(this);
  62131. };
  62132. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  62133. this._effect.setMatrix("world", world);
  62134. };
  62135. PBRMaterial.prototype.bind = function (world, mesh) {
  62136. this._myScene = this.getScene();
  62137. // Matrices
  62138. this.bindOnlyWorldMatrix(world);
  62139. // Bones
  62140. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  62141. if (this._myScene.getCachedMaterial() !== this) {
  62142. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  62143. if (BABYLON.StandardMaterial.FresnelEnabled) {
  62144. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  62145. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  62146. }
  62147. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  62148. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  62149. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  62150. }
  62151. }
  62152. // Textures
  62153. if (this._myScene.texturesEnabled) {
  62154. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  62155. this._effect.setTexture("albedoSampler", this.albedoTexture);
  62156. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  62157. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  62158. }
  62159. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  62160. this._effect.setTexture("ambientSampler", this.ambientTexture);
  62161. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  62162. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  62163. }
  62164. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  62165. this._effect.setTexture("opacitySampler", this.opacityTexture);
  62166. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  62167. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  62168. }
  62169. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  62170. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  62171. if (this.reflectionTexture.isCube) {
  62172. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  62173. }
  62174. else {
  62175. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  62176. }
  62177. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  62178. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  62179. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  62180. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  62181. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  62182. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  62183. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  62184. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  62185. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  62186. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  62187. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  62188. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  62189. }
  62190. }
  62191. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  62192. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  62193. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  62194. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  62195. }
  62196. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  62197. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  62198. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  62199. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  62200. }
  62201. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  62202. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  62203. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  62204. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  62205. }
  62206. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  62207. this._effect.setTexture("bumpSampler", this.bumpTexture);
  62208. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  62209. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  62210. }
  62211. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  62212. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  62213. var depth = 1.0;
  62214. if (this.refractionTexture.isCube) {
  62215. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  62216. }
  62217. else {
  62218. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  62219. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  62220. if (this.refractionTexture.depth) {
  62221. depth = this.refractionTexture.depth;
  62222. }
  62223. }
  62224. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  62225. }
  62226. if ((this.reflectionTexture || this.refractionTexture)) {
  62227. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  62228. }
  62229. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  62230. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  62231. }
  62232. }
  62233. // Clip plane
  62234. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  62235. // Point size
  62236. if (this.pointsCloud) {
  62237. this._effect.setFloat("pointSize", this.pointSize);
  62238. }
  62239. // Colors
  62240. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  62241. // GAMMA CORRECTION.
  62242. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  62243. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  62244. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  62245. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  62246. // GAMMA CORRECTION.
  62247. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  62248. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  62249. // GAMMA CORRECTION.
  62250. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  62251. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  62252. }
  62253. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  62254. // GAMMA CORRECTION.
  62255. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  62256. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  62257. // Lights
  62258. if (this._myScene.lightsEnabled && !this.disableLighting) {
  62259. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  62260. }
  62261. // View
  62262. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  62263. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  62264. }
  62265. // Fog
  62266. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  62267. this._lightingInfos.x = this.directIntensity;
  62268. this._lightingInfos.y = this.emissiveIntensity;
  62269. this._lightingInfos.z = this.environmentIntensity;
  62270. this._lightingInfos.w = this.specularIntensity;
  62271. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  62272. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  62273. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  62274. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  62275. this._cameraInfos.x = this.cameraExposure;
  62276. this._cameraInfos.y = this.cameraContrast;
  62277. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  62278. if (this.cameraColorCurves) {
  62279. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  62280. }
  62281. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  62282. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  62283. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  62284. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  62285. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  62286. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  62287. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  62288. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  62289. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  62290. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  62291. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  62292. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  62293. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  62294. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  62295. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  62296. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  62297. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  62298. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  62299. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  62300. // Log. depth
  62301. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  62302. }
  62303. _super.prototype.bind.call(this, world, mesh);
  62304. this._myScene = null;
  62305. };
  62306. PBRMaterial.prototype.getAnimatables = function () {
  62307. var results = [];
  62308. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  62309. results.push(this.albedoTexture);
  62310. }
  62311. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  62312. results.push(this.ambientTexture);
  62313. }
  62314. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  62315. results.push(this.opacityTexture);
  62316. }
  62317. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  62318. results.push(this.reflectionTexture);
  62319. }
  62320. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  62321. results.push(this.emissiveTexture);
  62322. }
  62323. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  62324. results.push(this.reflectivityTexture);
  62325. }
  62326. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  62327. results.push(this.bumpTexture);
  62328. }
  62329. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  62330. results.push(this.lightmapTexture);
  62331. }
  62332. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  62333. results.push(this.refractionTexture);
  62334. }
  62335. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  62336. results.push(this.cameraColorGradingTexture);
  62337. }
  62338. return results;
  62339. };
  62340. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  62341. if (forceDisposeTextures) {
  62342. if (this.albedoTexture) {
  62343. this.albedoTexture.dispose();
  62344. }
  62345. if (this.ambientTexture) {
  62346. this.ambientTexture.dispose();
  62347. }
  62348. if (this.opacityTexture) {
  62349. this.opacityTexture.dispose();
  62350. }
  62351. if (this.reflectionTexture) {
  62352. this.reflectionTexture.dispose();
  62353. }
  62354. if (this.emissiveTexture) {
  62355. this.emissiveTexture.dispose();
  62356. }
  62357. if (this.reflectivityTexture) {
  62358. this.reflectivityTexture.dispose();
  62359. }
  62360. if (this.bumpTexture) {
  62361. this.bumpTexture.dispose();
  62362. }
  62363. if (this.lightmapTexture) {
  62364. this.lightmapTexture.dispose();
  62365. }
  62366. if (this.refractionTexture) {
  62367. this.refractionTexture.dispose();
  62368. }
  62369. if (this.cameraColorGradingTexture) {
  62370. this.cameraColorGradingTexture.dispose();
  62371. }
  62372. }
  62373. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  62374. };
  62375. PBRMaterial.prototype.clone = function (name) {
  62376. var _this = this;
  62377. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  62378. };
  62379. PBRMaterial.prototype.serialize = function () {
  62380. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  62381. serializationObject.customType = "BABYLON.PBRMaterial";
  62382. return serializationObject;
  62383. };
  62384. // Statics
  62385. PBRMaterial.Parse = function (source, scene, rootUrl) {
  62386. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  62387. };
  62388. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  62389. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  62390. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  62391. PBRMaterial._scaledReflection = new BABYLON.Color3();
  62392. __decorate([
  62393. BABYLON.serialize()
  62394. ], PBRMaterial.prototype, "directIntensity", void 0);
  62395. __decorate([
  62396. BABYLON.serialize()
  62397. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  62398. __decorate([
  62399. BABYLON.serialize()
  62400. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  62401. __decorate([
  62402. BABYLON.serialize()
  62403. ], PBRMaterial.prototype, "specularIntensity", void 0);
  62404. __decorate([
  62405. BABYLON.serialize()
  62406. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  62407. __decorate([
  62408. BABYLON.serialize()
  62409. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  62410. __decorate([
  62411. BABYLON.serialize()
  62412. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  62413. __decorate([
  62414. BABYLON.serialize()
  62415. ], PBRMaterial.prototype, "cameraExposure", void 0);
  62416. __decorate([
  62417. BABYLON.serialize()
  62418. ], PBRMaterial.prototype, "cameraContrast", void 0);
  62419. __decorate([
  62420. BABYLON.serializeAsTexture()
  62421. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  62422. __decorate([
  62423. BABYLON.serializeAsColorCurves()
  62424. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  62425. __decorate([
  62426. BABYLON.serializeAsColor3()
  62427. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  62428. __decorate([
  62429. BABYLON.serialize()
  62430. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  62431. __decorate([
  62432. BABYLON.serializeAsColor3()
  62433. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  62434. __decorate([
  62435. BABYLON.serialize()
  62436. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  62437. __decorate([
  62438. BABYLON.serializeAsColor3()
  62439. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  62440. __decorate([
  62441. BABYLON.serialize()
  62442. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  62443. __decorate([
  62444. BABYLON.serializeAsColor3()
  62445. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  62446. __decorate([
  62447. BABYLON.serialize()
  62448. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  62449. __decorate([
  62450. BABYLON.serializeAsColor3()
  62451. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  62452. __decorate([
  62453. BABYLON.serialize()
  62454. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  62455. __decorate([
  62456. BABYLON.serialize()
  62457. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  62458. __decorate([
  62459. BABYLON.serialize()
  62460. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  62461. __decorate([
  62462. BABYLON.serializeAsTexture()
  62463. ], PBRMaterial.prototype, "albedoTexture", void 0);
  62464. __decorate([
  62465. BABYLON.serializeAsTexture()
  62466. ], PBRMaterial.prototype, "ambientTexture", void 0);
  62467. __decorate([
  62468. BABYLON.serializeAsTexture()
  62469. ], PBRMaterial.prototype, "opacityTexture", void 0);
  62470. __decorate([
  62471. BABYLON.serializeAsTexture()
  62472. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  62473. __decorate([
  62474. BABYLON.serializeAsTexture()
  62475. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  62476. __decorate([
  62477. BABYLON.serializeAsTexture()
  62478. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  62479. __decorate([
  62480. BABYLON.serializeAsTexture()
  62481. ], PBRMaterial.prototype, "bumpTexture", void 0);
  62482. __decorate([
  62483. BABYLON.serializeAsTexture()
  62484. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  62485. __decorate([
  62486. BABYLON.serializeAsTexture()
  62487. ], PBRMaterial.prototype, "refractionTexture", void 0);
  62488. __decorate([
  62489. BABYLON.serializeAsColor3("ambient")
  62490. ], PBRMaterial.prototype, "ambientColor", void 0);
  62491. __decorate([
  62492. BABYLON.serializeAsColor3("albedo")
  62493. ], PBRMaterial.prototype, "albedoColor", void 0);
  62494. __decorate([
  62495. BABYLON.serializeAsColor3("reflectivity")
  62496. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  62497. __decorate([
  62498. BABYLON.serializeAsColor3("reflection")
  62499. ], PBRMaterial.prototype, "reflectionColor", void 0);
  62500. __decorate([
  62501. BABYLON.serializeAsColor3("emissive")
  62502. ], PBRMaterial.prototype, "emissiveColor", void 0);
  62503. __decorate([
  62504. BABYLON.serialize()
  62505. ], PBRMaterial.prototype, "microSurface", void 0);
  62506. __decorate([
  62507. BABYLON.serialize()
  62508. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  62509. __decorate([
  62510. BABYLON.serialize()
  62511. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  62512. __decorate([
  62513. BABYLON.serializeAsFresnelParameters()
  62514. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  62515. __decorate([
  62516. BABYLON.serializeAsFresnelParameters()
  62517. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  62518. __decorate([
  62519. BABYLON.serialize()
  62520. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  62521. __decorate([
  62522. BABYLON.serialize()
  62523. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  62524. __decorate([
  62525. BABYLON.serialize()
  62526. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  62527. __decorate([
  62528. BABYLON.serialize()
  62529. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  62530. __decorate([
  62531. BABYLON.serialize()
  62532. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  62533. __decorate([
  62534. BABYLON.serialize()
  62535. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  62536. __decorate([
  62537. BABYLON.serialize()
  62538. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  62539. __decorate([
  62540. BABYLON.serialize()
  62541. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  62542. __decorate([
  62543. BABYLON.serialize()
  62544. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  62545. __decorate([
  62546. BABYLON.serialize()
  62547. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  62548. __decorate([
  62549. BABYLON.serialize()
  62550. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  62551. __decorate([
  62552. BABYLON.serialize()
  62553. ], PBRMaterial.prototype, "useParallax", void 0);
  62554. __decorate([
  62555. BABYLON.serialize()
  62556. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  62557. __decorate([
  62558. BABYLON.serialize()
  62559. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  62560. __decorate([
  62561. BABYLON.serialize()
  62562. ], PBRMaterial.prototype, "disableLighting", void 0);
  62563. __decorate([
  62564. BABYLON.serialize()
  62565. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  62566. __decorate([
  62567. BABYLON.serialize()
  62568. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  62569. __decorate([
  62570. BABYLON.serialize()
  62571. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  62572. __decorate([
  62573. BABYLON.serialize()
  62574. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  62575. return PBRMaterial;
  62576. })(BABYLON.Material);
  62577. BABYLON.PBRMaterial = PBRMaterial;
  62578. })(BABYLON || (BABYLON = {}));
  62579. var BABYLON;
  62580. (function (BABYLON) {
  62581. var StandardRenderingPipeline = (function (_super) {
  62582. __extends(StandardRenderingPipeline, _super);
  62583. /**
  62584. * @constructor
  62585. * @param {string} name - The rendering pipeline name
  62586. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62587. * @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)
  62588. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  62589. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62590. */
  62591. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  62592. var _this = this;
  62593. if (originalPostProcess === void 0) { originalPostProcess = null; }
  62594. _super.call(this, scene.getEngine(), name);
  62595. this.downSampleX4PostProcess = null;
  62596. this.brightPassPostProcess = null;
  62597. this.gaussianBlurHPostProcesses = [];
  62598. this.gaussianBlurVPostProcesses = [];
  62599. this.textureAdderPostProcess = null;
  62600. this.depthOfFieldSourcePostProcess = null;
  62601. this.depthOfFieldPostProcess = null;
  62602. this.brightThreshold = 1.0;
  62603. this.gaussianCoefficient = 0.25;
  62604. this.gaussianMean = 1.0;
  62605. this.gaussianStandardDeviation = 1.0;
  62606. this.exposure = 1.0;
  62607. this.lensTexture = null;
  62608. this.depthOfFieldDistance = 10.0;
  62609. this._depthRenderer = null;
  62610. // Getters and setters
  62611. this._blurEnabled = true;
  62612. this._depthOfFieldEnabled = false;
  62613. // Initialize
  62614. this._scene = scene;
  62615. // Create pass post-processe
  62616. if (!originalPostProcess) {
  62617. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  62618. }
  62619. else {
  62620. this.originalPostProcess = originalPostProcess;
  62621. }
  62622. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  62623. // Create down sample X4 post-process
  62624. this._createDownSampleX4PostProcess(scene, ratio / 2);
  62625. // Create bright pass post-process
  62626. this._createBrightPassPostProcess(scene, ratio / 2);
  62627. // Create gaussian blur post-processes (down sampling blurs)
  62628. this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  62629. this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  62630. this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  62631. this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  62632. // Create texture adder post-process
  62633. this._createTextureAdderPostProcess(scene, ratio);
  62634. // Create depth-of-field source post-process
  62635. this.depthOfFieldSourcePostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62636. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.depthOfFieldSourcePostProcess; }, true));
  62637. // Create gaussian blur used by depth-of-field
  62638. this._createGaussianBlurPostProcesses(scene, ratio / 2, 4);
  62639. // Create depth-of-field post-process
  62640. this._createDepthOfFieldPostProcess(scene, ratio);
  62641. // Finish
  62642. scene.postProcessRenderPipelineManager.addPipeline(this);
  62643. if (cameras !== null) {
  62644. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  62645. }
  62646. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfFieldSource", cameras);
  62647. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH4", cameras);
  62648. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV4", cameras);
  62649. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", cameras);
  62650. }
  62651. Object.defineProperty(StandardRenderingPipeline.prototype, "BlurEnabled", {
  62652. get: function () {
  62653. return this._blurEnabled;
  62654. },
  62655. set: function (enabled) {
  62656. if (enabled && !this._blurEnabled || !enabled && this._blurEnabled) {
  62657. for (var i = 0; i < this.gaussianBlurHPostProcesses.length - 1; i++) {
  62658. if (enabled) {
  62659. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + i, this._scene.cameras);
  62660. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + i, this._scene.cameras);
  62661. }
  62662. else {
  62663. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + i, this._scene.cameras);
  62664. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + i, this._scene.cameras);
  62665. }
  62666. }
  62667. }
  62668. this._blurEnabled = enabled;
  62669. },
  62670. enumerable: true,
  62671. configurable: true
  62672. });
  62673. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  62674. get: function () {
  62675. return this._depthOfFieldEnabled;
  62676. },
  62677. set: function (enabled) {
  62678. if (enabled && !this._depthOfFieldEnabled) {
  62679. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfFieldSource", this._scene.cameras);
  62680. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH4", this._scene.cameras);
  62681. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV4", this._scene.cameras);
  62682. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  62683. this._depthRenderer = this._scene.enableDepthRenderer();
  62684. }
  62685. else if (!enabled && this._depthOfFieldEnabled) {
  62686. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfFieldSource", this._scene.cameras);
  62687. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH4", this._scene.cameras);
  62688. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV4", this._scene.cameras);
  62689. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  62690. }
  62691. this._depthOfFieldEnabled = enabled;
  62692. },
  62693. enumerable: true,
  62694. configurable: true
  62695. });
  62696. // Down Sample X4 Post-Processs
  62697. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  62698. var _this = this;
  62699. var downSampleX4Offsets = new Array(32);
  62700. this.downSampleX4PostProcess = new BABYLON.PostProcess("HDRDownSampleX4", "standard", ["dsOffsets"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62701. this.downSampleX4PostProcess.onApply = function (effect) {
  62702. var id = 0;
  62703. for (var i = -2; i < 2; i++) {
  62704. for (var j = -2; j < 2; j++) {
  62705. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  62706. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  62707. id += 2;
  62708. }
  62709. }
  62710. effect.setArray2("dsOffsets", downSampleX4Offsets);
  62711. };
  62712. // Add to pipeline
  62713. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  62714. };
  62715. // Brightpass Post-Process
  62716. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  62717. var _this = this;
  62718. var brightOffsets = new Array(8);
  62719. this.brightPassPostProcess = new BABYLON.PostProcess("HDRBrightPass", "standard", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62720. this.brightPassPostProcess.onApply = function (effect) {
  62721. var sU = (1.0 / _this.brightPassPostProcess.width);
  62722. var sV = (1.0 / _this.brightPassPostProcess.height);
  62723. brightOffsets[0] = -0.5 * sU;
  62724. brightOffsets[1] = 0.5 * sV;
  62725. brightOffsets[2] = 0.5 * sU;
  62726. brightOffsets[3] = 0.5 * sV;
  62727. brightOffsets[4] = -0.5 * sU;
  62728. brightOffsets[5] = -0.5 * sV;
  62729. brightOffsets[6] = 0.5 * sU;
  62730. brightOffsets[7] = -0.5 * sV;
  62731. effect.setArray2("dsOffsets", brightOffsets);
  62732. effect.setFloat("brightThreshold", _this.brightThreshold);
  62733. };
  62734. // Add to pipeline
  62735. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  62736. };
  62737. // Create gaussian blur H&V post-processes
  62738. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
  62739. var _this = this;
  62740. var blurOffsets = new Array(9);
  62741. var blurWeights = new Array(9);
  62742. var uniforms = ["blurOffsets", "blurWeights"];
  62743. var callback = function (height) {
  62744. return function (effect) {
  62745. // Weights
  62746. var x = 0.0;
  62747. for (var i = 0; i < 9; i++) {
  62748. x = (i - 4.0) / 4.0;
  62749. blurWeights[i] =
  62750. _this.gaussianCoefficient
  62751. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  62752. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  62753. }
  62754. var lastOutputDimensions = {
  62755. width: scene.getEngine().getRenderWidth(),
  62756. height: scene.getEngine().getRenderHeight()
  62757. };
  62758. for (var i = 0; i < 9; i++) {
  62759. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  62760. blurOffsets[i] = value;
  62761. }
  62762. effect.setArray("blurOffsets", blurOffsets);
  62763. effect.setArray("blurWeights", blurWeights);
  62764. };
  62765. };
  62766. // Create horizontal gaussian blur post-processes
  62767. var gaussianBlurHPostProcess = new BABYLON.PostProcess("HDRGaussianBlurH" + ratio, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62768. gaussianBlurHPostProcess.onApply = callback(false);
  62769. // Create vertical gaussian blur post-process
  62770. var gaussianBlurVPostProcess = new BABYLON.PostProcess("HDRGaussianBlurV" + ratio, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62771. gaussianBlurVPostProcess.onApply = callback(true);
  62772. // Add to pipeline
  62773. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  62774. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  62775. // Finish
  62776. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  62777. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  62778. };
  62779. // Create texture adder post-process
  62780. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  62781. var _this = this;
  62782. var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
  62783. this.textureAdderPostProcess = new BABYLON.PostProcess("HDRTextureAdder", "standard", ["exposure"], ["otherSampler", "lensSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define TEXTURE_ADDER", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62784. this.textureAdderPostProcess.onApply = function (effect) {
  62785. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  62786. effect.setTexture("lensSampler", _this.lensTexture);
  62787. effect.setFloat("exposure", _this.exposure);
  62788. };
  62789. // Add to pipeline
  62790. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  62791. };
  62792. // Create depth-of-field post-process
  62793. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  62794. var _this = this;
  62795. this.depthOfFieldPostProcess = new BABYLON.PostProcess("HDRDepthOfField", "standard", ["distance"], ["otherSampler", "depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DEPTH_OF_FIELD", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62796. this.depthOfFieldPostProcess.onApply = function (effect) {
  62797. effect.setTextureFromPostProcess("otherSampler", _this.depthOfFieldSourcePostProcess);
  62798. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  62799. effect.setFloat("distance", _this.depthOfFieldDistance);
  62800. };
  62801. // Add to pipeline
  62802. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  62803. };
  62804. return StandardRenderingPipeline;
  62805. })(BABYLON.PostProcessRenderPipeline);
  62806. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  62807. })(BABYLON || (BABYLON = {}));
  62808. 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#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\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\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","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.; \n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\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\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","rect2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","rect2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n\n#define rsub0 17.0\n#define rsub1 33.0\n#define rsub2 49.0\n#define rsub3 65.0\n#define rsub 64.0\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (properties.z == 0.0) {\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<4.0) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=4.0;\n}\nif (segi == 0.0) {\npos2=vec2(1.0,1.0);\n} \nelse if (segi == 1.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (segi == 2.0) {\npos2=vec2(0.0,0.0);\n} \nelse {\npos2=vec2(0.0,1.0);\n}\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse if (index == 1.0) {\npos2=vec2(1.0,1.0);\n}\nelse if (index == 2.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (index == 3.0) {\npos2=vec2(0.0,0.0);\n}\nelse {\npos2=vec2(0.0,1.0);\n}\n#endif\n}\nelse\n{\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<rsub) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=rsub;\n}\n\nif (segi<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (segi<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (segi<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\n\nif (index<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (index<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (index<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\n}\n#endif\n}\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=pos2.xy*properties.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"#ifndef FULLFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\n#endif\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\n#ifndef FULLFLOAT\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=vec4(moment1,moment2,1.0,1.0);\n#endif\n#else\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","sprite2dPixelShader":"varying vec2 vUV;\nvarying float vOpacity;\nuniform bool alphaTest;\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest)\n{\nif (color.a<0.95) {\ndiscard;\n}\n}\ncolor.a*=vOpacity;\ngl_FragColor=color;\n}","sprite2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 scaleFactor;\natt vec2 textureSize;\n\natt vec3 properties;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n\n\nvarying vec2 vUV;\nvarying float vOpacity;\nvoid main(void) {\nvec2 pos2;\n\nvec2 off=vec2(0.0,0.0);\nvec2 sfSizeUV=sizeUV*scaleFactor;\nfloat frame=properties.x;\nfloat invertY=properties.y;\nfloat alignToPixel=properties.z;\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x+(frame*sfSizeUV.x)+off.x,topLeftUV.y-off.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x+(frame*sfSizeUV.x)+off.x,(topLeftUV.y+sfSizeUV.y));\n}\n\nelse if (index == 2.0) {\npos2=vec2( 1.0,1.0);\nvUV=vec2(topLeftUV.x+sfSizeUV.x+(frame*sfSizeUV.x),(topLeftUV.y+sfSizeUV.y));\n}\n\nelse if (index == 3.0) {\npos2=vec2( 1.0,0.0);\nvUV=vec2(topLeftUV.x+sfSizeUV.x+(frame*sfSizeUV.x),topLeftUV.y-off.y);\n}\nif (invertY == 1.0) {\nvUV.y=1.0-vUV.y;\n}\nvec4 pos;\nif (alignToPixel == 1.0)\n{\npos.xy=floor(pos2.xy*sizeUV*textureSize);\n} else {\npos.xy=pos2.xy*sizeUV*textureSize;\n}\nvOpacity=opacity;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n} ","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nvoid main(void)\n{\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*2.0,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*2.0,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*2.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*2.0))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\ngl_FragColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","text2dPixelShader":"varying vec4 vColor;\nvarying vec2 vUV;\n\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\ngl_FragColor=color*vColor;\n}","text2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 textureSize;\natt vec4 color;\natt float superSampleFactor;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y+sizeUV.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y);\n}\n\nelse if (index == 2.0) {\npos2=vec2(1.0,1.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y);\n}\n\nelse if (index == 3.0) {\npos2=vec2(1.0,0.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y+sizeUV.y);\n}\n\nvUV=(floor(vUV*textureSize)+vec2(0.0,0.0))/textureSize;\nvColor=color;\nvColor.a*=opacity;\nvec4 pos;\npos.xy=floor(pos2.xy*superSampleFactor*sizeUV*textureSize); \npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
  62809. 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#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW-lightDirection.xyz);\nNdotL=max(0.00000000001,dot(vNormal,-lightDirection.xyz));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nnotShadowLevel=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\nlightDiffuseContribution+=lightmapColor*notShadowLevel;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nlightSpecularContribution+=info.specular*notShadowLevel*lightmapColor;\n#endif\n#endif\n#else\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif\n#endif","pbrShadowFunctions":"\n#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y =-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n#endif\n}\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n"};
  62810. 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.addInPlace=function(t){return this.x+=t.x,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.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},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,x=0,l=0,z=0,w=0,v=-1,d=0,g=M.Vector3[0],R=0,T=M.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?x=1:(w=a.z/a.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),T.x=x,T.y=l,T.z=z,T.normalize(),r.CrossToRef(h,T,g),g.normalize(),r.Dot(a,g)<0&&(v=1),R=r.Dot(h,T),R=Math.min(1,Math.max(-1,R)),f=Math.acos(R)*v,r.Dot(T,u)<0&&(f=Math.PI+f,T=T.scaleInPlace(-1),d++);var _=M.Vector3[2],A=M.Vector3[3];x=0,l=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?x=1:(w=T.z/T.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),_.x=x,_.y=l,_.z=z,_.normalize(),r.CrossToRef(_,T,A),A.normalize(),r.CrossToRef(a,_,g),g.normalize(),r.Dot(T,g)<0&&(v=1),R=r.Dot(a,_),R=Math.min(1,Math.max(-1,R)),c=Math.acos(R)*v,r.Dot(A,m)<0&&(c=Math.PI+c,d++),v=-1,r.CrossToRef(u,T,g),g.normalize(),r.Dot(g,m)<0&&(v=1),R=r.Dot(T,u),R=Math.min(1,Math.max(-1,R)),y=-Math.acos(R)*v,0>R&&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],x=this.m[14],l=this.m[15],z=y*l-c*x,w=m*l-c*f,v=m*x-y*f,d=u*l-c*p,g=u*x-y*p,R=u*f-m*p,T=s*z-h*w+a*v,_=-(e*z-h*d+a*g),M=e*w-s*d+a*R,A=-(e*v-s*g+h*R),b=1/(i*T+r*_+n*M+o*A),F=h*l-a*x,L=s*l-a*f,C=s*x-h*f,P=e*l-a*p,Z=e*x-h*p,S=e*f-s*p,I=h*c-a*y,H=s*c-a*m,D=s*y-h*m,q=e*c-a*u,V=e*y-h*u,N=e*m-s*u;return t.m[0]=T*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=A*b,t.m[1]=-(r*z-n*w+o*v)*b,t.m[5]=(i*z-n*d+o*g)*b,t.m[9]=-(i*w-r*d+o*R)*b,t.m[13]=(i*v-r*g+n*R)*b,t.m[2]=(r*F-n*L+o*C)*b,t.m[6]=-(i*F-n*P+o*Z)*b,t.m[10]=(i*L-r*P+o*S)*b,t.m[14]=-(i*C-r*Z+n*S)*b,t.m[3]=-(r*I-n*H+o*D)*b,t.m[7]=(i*I-n*q+o*V)*b,t.m[11]=-(i*H-r*q+o*N)*b,t.m[15]=(i*D-r*V+n*N)*b,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.getTranslation=function(){return new e(this.m[12],this.m[13],this.m[14])},t.prototype.multiply=function(i){var 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),\nthis},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],x=this.m[12],l=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],R=t.m[3],T=t.m[4],_=t.m[5],M=t.m[6],A=t.m[7],b=t.m[8],F=t.m[9],L=t.m[10],C=t.m[11],P=t.m[12],Z=t.m[13],S=t.m[14],I=t.m[15];return i[r]=n*v+o*T+e*b+s*P,i[r+1]=n*d+o*_+e*F+s*Z,i[r+2]=n*g+o*M+e*L+s*S,i[r+3]=n*R+o*A+e*C+s*I,i[r+4]=h*v+a*T+u*b+m*P,i[r+5]=h*d+a*_+u*F+m*Z,i[r+6]=h*g+a*M+u*L+m*S,i[r+7]=h*R+a*A+u*C+m*I,i[r+8]=y*v+c*T+p*b+f*P,i[r+9]=y*d+c*_+p*F+f*Z,i[r+10]=y*g+c*M+p*L+f*S,i[r+11]=y*R+c*A+p*C+f*I,i[r+12]=x*v+l*T+z*b+w*P,i[r+13]=x*d+l*_+z*F+w*Z,i[r+14]=x*g+l*M+z*L+w*S,i[r+15]=x*R+l*A+z*C+w*I,this},t.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},t.prototype.clone=function(){return t.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},t.prototype.getClassName=function(){return\"Matrix\"},t.prototype.getHashCode=function(){for(var t=this.m[0]||0,i=1;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,x,l){l.m[0]=t,l.m[1]=i,l.m[2]=r,l.m[3]=n,l.m[4]=o,l.m[5]=e,l.m[6]=s,l.m[7]=h,l.m[8]=a,l.m[9]=u,l.m[10]=m,l.m[11]=y,l.m[12]=c,l.m[13]=p,l.m[14]=f,l.m[15]=x},t.prototype.getRow=function(t){if(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,x,l){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]=x,z.m[15]=l,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.LookAtRH=function(i,r,n){var o=t.Zero();return t.LookAtRHToRef(i,r,n,o),o},t.LookAtRHToRef=function(i,r,n,o){i.subtractToRef(r,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/(e-o),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/(e-o),s.m[15]=1},t.OrthoOffCenterRH=function(i,r,n,o,e,s){var h=t.Zero();return t.OrthoOffCenterRHToRef(i,r,n,o,e,s,h),h},t.OrthoOffCenterRHToRef=function(i,r,n,o,e,s,h){t.OrthoOffCenterLHToRef(i,r,n,o,e,s,h),h.m[10]*=-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/(n-r),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=-(r*n)/(n-r)},t.PerspectiveFovRH=function(i,r,n,o){var e=t.Zero();return t.PerspectiveFovRHToRef(i,r,n,o,e),e},t.PerspectiveFovRHToRef=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.PerspectiveFovWebVRToRef=function(t,i,r,n,o){void 0===o&&(o=!0);var e=Math.tan(t.upDegrees*Math.PI/180),s=Math.tan(t.downDegrees*Math.PI/180),h=Math.tan(t.leftDegrees*Math.PI/180),a=Math.tan(t.rightDegrees*Math.PI/180),u=2/(h+a),m=2/(e+s);n.m[0]=u,n.m[1]=n.m[2]=n.m[3]=n.m[4]=0,n.m[5]=m,n.m[6]=n.m[7]=0,n.m[8]=(h-a)*u*.5,n.m[9]=-((e-s)*m*.5),n.m[10]=-r/(i-r),n.m[11]=1,n.m[12]=n.m[13]=n.m[15]=0,n.m[14]=i*r/(i-r)},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 x=t.Orientation,l=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,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=l;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=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?x.CW:x.CCW,this.angle=l.FromDegrees(this.orientation===x.CW?a-m:m-a)}return t}();t.Arc2=z;var w=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var 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===x.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,h=n.length();if(0===h&&(h=1),void 0===o||null===o){var a;i.WithinEpsilon(Math.abs(n.y)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.x)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.z)/h,1,t.Epsilon)||(a=new e(0,0,1)):a=new e(1,0,0):a=new e(0,-1,0),s=e.Cross(n,a)}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 R=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var 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=R;var T=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=T;var _=function(){function t(t,i,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={}));";
  62811. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  62812. module.exports = BABYLON;
  62813. };